text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>waveapi.robot_abstract.RobotListener</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package waveapi ::
        Module robot_abstract ::
        Class RobotListener

[hide private]

[frames] | no frames]

type RobotListener

source code

object --+
         |
        RobotListener

Listener interface for robot events.

The RobotListener is a high-level construct that hides away the details
of events. Instead, a client will derive from this class and register
it with the robot. All event handlers are automatically registered. When
a relevant event comes in, logic is applied based on the incoming data and
the appropriate function is invoked.

For example:
  If the user implements the "OnRobotAdded" method, the OnParticipantChanged
  method of their subclass, this will automatically register the
  events.WAVELET_PARTICIPANTS_CHANGED handler and respond to any events
  that add the robot.

  class MyRobotListener(robot.RobotListener):

    def OnRobotAdded(self):
      wavelet = self.context.GetRootWavelet()
      blip = wavelet.CreateBlip()
      blip.GetDocument.SetText("Thanks for adding me!")

  robot = robots.Robot()
  robot.RegisterListener(MyRobotListener)
  robot.Run()

TODO(davidbyttow): Implement this functionality.

        Instance Methods
        [hide private]

          __init__(self)

            source code

          OnRobotAdded(self)

            source code

          OnRobotRemoved(self)

            source code

        Method Details
        [hide private]

__init__(self)

(Constructor)

  	source code

Overrides:
        object.__init__

(inherited documentation)

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1
    on Wed May 27 22:42:20 2009

      http://epydoc.sourceforge.net


text:
namespace EnergyTrading.MDM.Test
{
    using System;
    using System.Linq;
    using System.Runtime.Serialization;

    using Microsoft.Http;
    using NUnit.Framework;

    [TestFixture]
    public class when_a_request_is_made_for_a_location_and_they_exist : IntegrationTestBase
    {
        private static MDM.Location location;

        private static EnergyTrading.MDM.Contracts.Sample.Location returnedLocation;

        [TestFixtureSetUp]
        public static void ClassInit()
        {
            Establish_context();
            Because_of();
        }

        protected static void Establish_context()
        {
            location = Script.LocationData.CreateBasicEntity();
        }

        protected static void Because_of()
        {
            using (var client = new HttpClient(ServiceUrl["Location"] +
                location.Id))
            {
                using (HttpResponseMessage response = client.Get())
                {
                    returnedLocation = response.Content.ReadAsDataContract<EnergyTrading.MDM.Contracts.Sample.Location>();
                }
            }
        }

        [Test]
        public void should_return_the_location_with_the_correct_details()
        {
            Script.LocationDataChecker.CompareContractWithSavedEntity(returnedLocation);
        }
    }

    [TestFixture]
    public class when_a_request_is_made_for_a_location_as_of_a_date_and_they_exist : IntegrationTestBase
    {
        private static MDM.Location location;
        private static EnergyTrading.MDM.Contracts.Sample.Location returnedLocation;
        private static DateTime asof;
        private static HttpClient client;

        [TestFixtureSetUp]
        public static void ClassInit()
        {
            Establish_context();
            Because_of();
        }

        protected static void Establish_context()
        {
            location = Script.LocationData.CreateBasicEntity();
        }

        protected static void Because_of()
        {
            asof = Script.baseDate.AddSeconds(1);
            client =
                new HttpClient(ServiceUrl["Location"] + string.Format("{0}?as-of={1}",
                    location.Id.ToString(), asof.ToString(DateFormatString)));

            HttpResponseMessage response = client.Get();
            returnedLocation = response.Content.ReadAsDataContract<EnergyTrading.MDM.Contracts.Sample.Location>();
        }

        [Test]
        public void should_return_the_location_with_the_correct_details()
        {
            Script.LocationDataChecker.CompareContractWithSavedEntity(returnedLocation);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<title>Windbox - Example 1</title>
	<meta name="viewport" content="initial-scale=1,minimum-scale=1, maximum-scale=1,user-scalable=no">
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">

	<link  rel="stylesheet" href="../windbox/windbox.css">

	Voltar -
	Box simply

	Visualize o código desta página com CTRL+U


text:
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Actions, Effect} from '@ngrx/effects';
import {Observable} from 'rxjs/Observable';
import {Action} from '@ngrx/store';
import * as tellerActions from '../teller.actions';

@Injectable()
export class TellerRouteEffects {

  @Effect({ dispatch: false })
  createTellerSuccess$: Observable<Action> = this.actions$
    .ofType(tellerActions.CREATE_TELLER_SUCCESS, tellerActions.UPDATE_TELLER_SUCCESS)
    .map(action => action.payload)
    .do(payload => {
      this.router.navigate(['../'], { relativeTo: payload.activatedRoute });
    });

  @Effect({ dispatch: false })
  executeCommandSuccess$: Observable<Action> = this.actions$
    .ofType(tellerActions.EXECUTE_COMMAND_SUCCESS)
    .map(action => action.payload)
    .do(payload => {
      this.router.navigate(['../'], { relativeTo: payload.activatedRoute });
    });

  constructor(private actions$: Actions, private router: Router) { }
}


text:
Ext.define('Portal.controller.Main', {
    extend: 'Ext.app.Controller'
});


text:
import daemon
import optparse
import time
import logging

import s7
import domotica.settings as settings

from pollers import AlarmPoller, TemperaturePoller

POLL_INTERVAL = 5

def poll(s7conn, pollers):
    for poller in pollers:
        poller.poll(s7conn)

def connect():
    return s7.S7Comm(settings.PLC_IP)

def setup_logger(options):
    lvl = logging.INFO
    if options.debug:
        lvl = logging.DEBUG

    fmt = "%(asctime)s:%(levelname)s:%(module)s:%(message)s"
    logging.basicConfig(level=lvl, format=fmt)

def main():
    parser = optparse.OptionParser()
    parser.add_option("-f", "--foreground", action="store_true",
            dest="foreground", help="Do not daemonize", default=False)
    parser.add_option("-d", "--debug", action="store_true",
            dest="debug", help="Debug logging", default=False)
    (options, args) = parser.parse_args()

    if not options.foreground:
        d = daemon.DaemonContext(prevent_core=False)
        d.open()

    setup_logger(options)

    logging.info("Starting domd...")

    pollers = [
            AlarmPoller(),
            TemperaturePoller()
        ]

    s7conn = connect()

    while True:
        try:
            poll(s7conn, pollers)
        except s7.S7Exception, e:
            if e.errno() == s7.S7Exception.ERR_CONNECTION_CLOSED:
                logging.warn("Connection lost. Reconnecting...")
                s7conn = connect()
            else:
                logging.error("Unknown error: %s", e)
                raise

        time.sleep(POLL_INTERVAL)

if __name__ == "__main__":
    main()


text:
namespace PickUp.Web.Areas.Administration.ViewModels.Trips
{
    using System;
    using AutoMapper;
    using PickUp.Data.Models;
    using PickUp.Web.Infrastructure.Mapping;

    public class TripGridViewModel : IMapFrom<Trip>, IHaveCustomMappings
    {
        public int Id { get; set; }

        public string From { get; set; }

        public string To { get; set; }

        public string Description { get; set; }

        public int AvailableSeats { get; set; }

        public string Driver { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime CreatedOn { get; set; }

        public void CreateMappings(IMapperConfiguration configuration)
        {
            configuration.CreateMap<Trip, TripGridViewModel>()
                .ForMember(x => x.From, opt => opt.MapFrom(x => x.From.Name));

            configuration.CreateMap<Trip, TripGridViewModel>()
                .ForMember(x => x.To, opt => opt.MapFrom(x => x.To.Name));

            configuration.CreateMap<Trip, TripGridViewModel>()
                .ForMember(x => x.Driver, opt => opt.MapFrom(x => x.Driver.UserName));
        }
    }
}


text:
var React = require('react')

module.exports = React.createClass({

  getInitialState: function() {
    return { text: '', ok: false }
  },

  handleSubmit: function(e) {
    e.preventDefault()
    if (this.props.onAdd(this.state.text)) {
      this.setState({text: '', ok: false})
    }
  },

  onChange: function(e) {
    this.setState({text: e.target.value, ok: !!e.target.value})
  },

  render: function() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input onChange={this.onChange} value={this.state.text} />
        <button disabled={!this.state.ok}>Add marker</button>
      </form>
    )
  }
})


text:
package com.lightbend.lagom.scaladsl.persistence.cassandra

import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter

import akka.persistence.query.TimeBasedUUID
import scala.concurrent.Future
import scala.concurrent.duration._

import com.typesafe.config.ConfigFactory
import com.lightbend.lagom.internal.persistence.ReadSideConfig
import com.lightbend.lagom.internal.persistence.cassandra.CassandraReadSideSettings
import com.lightbend.lagom.internal.scaladsl.persistence.cassandra.CassandraPersistentEntityRegistry
import com.lightbend.lagom.internal.scaladsl.persistence.cassandra.CassandraReadSideImpl
import com.lightbend.lagom.internal.scaladsl.persistence.cassandra.ScaladslCassandraOffsetStore
import com.lightbend.lagom.scaladsl.persistence.TestEntity.Evt
import com.lightbend.lagom.scaladsl.persistence._

object CassandraReadSideSpec {
  def firstTimeBucket: String = {
    val today                                = LocalDateTime.now(ZoneOffset.UTC)
    val firstBucketFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm")
    today.minusHours(3).format(firstBucketFormat)
  }

  val readSideConfig = ConfigFactory.parseString(s"""
    # speed up read-side queries
    cassandra-query-journal {
      first-time-bucket = "$firstTimeBucket"
      refresh-interval = 1s
      events-by-tag.eventual-consistency-delay = 1s
    }
    """)

  val defaultConfig =
    ConfigFactory
      .parseString("akka.loglevel = INFO")
      .withFallback(readSideConfig)

  val noAutoCreateConfig =
    ConfigFactory
      .parseString("lagom.persistence.read-side.cassandra.tables-autocreate = false")
      .withFallback(defaultConfig)
}

class CassandraReadSideSpec
    extends CassandraPersistenceSpec(CassandraReadSideSpec.defaultConfig, TestEntitySerializerRegistry)
    with AbstractReadSideSpec {
  import system.dispatcher

  protected override lazy val persistentEntityRegistry = new CassandraPersistentEntityRegistry(system)

  private lazy val testCasReadSideSettings: CassandraReadSideSettings = new CassandraReadSideSettings(system)
  private lazy val testSession: CassandraSession                      = new CassandraSession(system)
  private lazy val offsetStore =
    new ScaladslCassandraOffsetStore(system, testSession, testCasReadSideSettings, ReadSideConfig())
  private lazy val cassandraReadSide =
    new CassandraReadSideImpl(system, testSession, testCasReadSideSettings, offsetStore)

  override def processorFactory(): ReadSideProcessor[Evt] =
    new TestEntityReadSide.TestEntityReadSideProcessor(system, cassandraReadSide, testSession)

  private lazy val readSide = new TestEntityReadSide(system, testSession)

  override def getAppendCount(id: String): Future[Long] = readSide.getAppendCount(id)

  override def afterAll(): Unit = {
    super.afterAll()
  }
}

class CassandraReadSideAutoCreateSpec
    extends CassandraPersistenceSpec(CassandraReadSideSpec.noAutoCreateConfig, TestEntitySerializerRegistry) {
  import system.dispatcher

  private lazy val testSession: CassandraSession                      = new CassandraSession(system)
  private lazy val testCasReadSideSettings: CassandraReadSideSettings = new CassandraReadSideSettings(system)
  private lazy val offsetStore =
    new ScaladslCassandraOffsetStore(system, testSession, testCasReadSideSettings, ReadSideConfig())

  "A Cassandra Read-Side" must {
    "not send ClusterStartupTask message, so startupTask must return None" +
      "when 'lagom.persistence.read-side.cassandra.tables-autocreate' flag is 'false'" in {
      offsetStore.startupTask shouldBe None
    }
  }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>BatteryTech Engine: 2D Graphics and Textures</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

BatteryTech Engine
    2.0

Cross-Platform Game Engine

Main Page

API Reference

Classes

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

 All Classes Files Functions Groups Pages

Functions

2D Graphics and Textures

Graphics and Rendering

How to render 2D Graphics and work with Textures.
More...

Detailed Description

How to render 2D Graphics and work with Textures.

The core 2D rendering function is Game::render2D(). This function renders a texture of a given size and rotation to any location. This is by far the most common method of 2D rendering used in most games and can be used to provide a variety of effects and styles with proper texturing.

By default all 2D graphics are drawn in actual pixels, that is, to the viewport size. Developers have 2 primary options for scaling to screen:

Scale position and size using getViewportSize() for all render calls

Change the projection to a world/reference system using Game::start2DProjection() and Game::end2DProjection()

Either technique is suitable and will produce uniform results across different screen sizes.

Textures can be configured in a number of ways, including clamping, nearest, linear, bilinear and trilinear filtering using mipmaps. Defaults, once set, will apply to all textures added until changed. Once a texture is loaded, it can not be changed so either the defaults or the specific texture parameters need to be set before load. See Loading Resources for more info on the loading state.

See also:

Fonts and Text Rendering

Render Options

Functions

scale 	getUIScale ()

 	Returns the singular scale value for scaling UI components.

scaleX__scaleY 	getScale2d ()

 	Returns the scale for both dimensions of the screen.

width__height 	getViewportSize ()

 	Returns the size of the current screen.

Texture Functions

 Texture Management

 	addTexture (string assetName, boolean onDemand)

 	Adds a texture file to the resource manager.

 	removeTexture (string assetName)

 	Removes a texture file from the resource manager.

 	setDefaultTextureParams (string paramName1, notype paramValue1,...)

 	Sets default texture parameters.

 	setTextureParams (string assetName, string paramName1, notype paramValue1,...)

 	Sets texture parameters.

origWidth__origHeight__trimmedWidth__trimmedHeight__offsetX__offsetY 	getTextureDimensions (string assetName)

 	Gets the texture dimensions for a texture.

 	clearTextures ()

 	Removes all textures from the resource manager.

2D Render Functions

 Functions that produce render items

renderItemId 	Game::render2D (string assetName, float x, float y, float width, float height, float rotation, float alpha)

 	Renders a 2D image.

renderItemId 	Game::start2DProjection (float left, float right, float bottom, float top, float near, float far)

 	Starts an alternate 2D Projection (Orthographic)

renderItemId 	Game::end2DProjection ()

 	Ends any alternate 2D Projection, restores default.

Function Documentation

          addTexture
          (
          string
          assetName,

          boolean
          onDemand

          )

Adds a texture file to the resource manager.

Parameters:

assetName	The texture file asset name

onDemand	(optional) Flags the texture to be only loaded on first use

          clearTextures
          (
          	)

Removes all textures from the resource manager.

          renderItemId Game::end2DProjection
          (
          	)

Ends any alternate 2D Projection, restores default.

Does not pop like a stack but instead restores actual screen-pixel projection

          scaleX__scaleY getScale2d
          (
          	)

Returns the scale for both dimensions of the screen.

Returns:

scaleX: The X-axis scale

scaleY: The Y-axis scale

          origWidth__origHeight__trimmedWidth__trimmedHeight__offsetX__offsetY getTextureDimensions
          (
          string
          assetName	)

Gets the texture dimensions for a texture.

Parameters:

assetName	The texture asset's name

Returns:

origWidth: The original width

origHeight: The original height

trimmedWidth: The trimmed width

trimmedHeight: The trimmed height

offsetX: The X offset

offsetY: The Y offset

          scale getUIScale
          (
          	)

Returns the singular scale value for scaling UI components.

This calculation uses the non-variable dimension of the current orientation to obtain a scale value that is appropriate for the current screen. Scaling both width and height by this value will result in correctly scaled, proportionate UI components.

Returns:

scale: The scale

          width__height getViewportSize
          (
          	)

Returns the size of the current screen.

Returns:

width: The screen's width

height: The screen's height

          removeTexture
          (
          string
          assetName	)

Removes a texture file from the resource manager.

Parameters:

assetName	The texture file asset name

          renderItemId Game::render2D
          (
          string
          assetName,

          float
          x,

          float
          y,

          float
          width,

          float
          height,

          float
          rotation,

          float
          alpha

          )

Renders a 2D image.

2D images are rendered as "textured quads." Because BatteryTech is fully ES compatible, this means 2 triangles per quad.

Render Order: 2D images are rendered in the order of draw calls from back to front, so it is your responsibility as the developer to call in the order which will correctly render your scene.

Texture Atlasing: Multiple images can be combined onto a single texture either manually or by using the 3rd party tool "Texture Packer." Texture Packer specifically supports BatteryTech and exports a .btx file alongside a packed .png which holds all of the texture data. Packed textures keep the same filenames as the original and will be rendered as if they are the original size, meaning even though alpha pixels may be trimmed during packing, they will be accounted for during the render. For example, if you put Sprite1.png and Sprite2.png into an atlas and the output was MySprites.png/MySprites.btx, you would simply call addTexture("MySprites.btx") then game:render2D("Sprite1.png", ...) as if you directly loaded that file. Removing works the same way - removing the packed texture removes all virtualized textures.

Optimizing: 2D sprites will be rendered in the most optimized way that still can render the scene correctly blindly back to front. The one major bottleneck is texture switching. Any time a texture switch is required, the current sprite buffer will be drawn. To optimize, specify a render order that groups draws by texture and pack multiple images into an atlas when they will be rendered all together on screen. BatteryTech does not analyze the scene to see if quads overlap so it is up to the developer to provide a draw order that can best utilize low texture switching, resulting in larger batches of quads to be drawn.

Coordinate System: Alternate coordinate systems can be specified by using Game::start2DProjection() / Game::end2DProjection() which makes it easier to manage scaling across different screen sizes. If no projection is specified, screen coordinates are used with 0,0 in the top left.

Example:

 -- Render an image centered at 200,200 drawn to be 400x400 in size and rotated 90 degrees

 local item = game:render2D("Textures/MyImage.png", 200, 200, 400, 400, math.rad(90))

 -- Now specify that we want to draw this at only 70% opacity - we could have also specified this in the render call

 game:setRenderItemParam(item, "alpha", .7)

Parameters:

assetName	The asset filename to use as the texture

x	The center x coordinate

y	The center y coordinate

width	The render width

height	The render height

rotation	(optional) The rotation in radians

alpha	(optional) The alpha value in range 0-1

          setDefaultTextureParams
          (
          string
          paramName1,

          notype
          paramValue1,

          ...

          )

Sets default texture parameters.

Parameters are set as key/value pairs and multiple may be specified. These defaults will be used for all newly loaded textures until changed or unless the texture overrides with setTextureParams().

Supported Parameters keys and values are:

"filter" - "nearest", "linear", "bilinear", "trilinear"

"repeat" - boolean true or false

Example:

 setDefaultTextureParams("filter", "linear", "repeat", false)

Parameters:

paramName1	The first parameter name

paramValue1	The first parameter value

          setTextureParams
          (
          string
          assetName,

          string
          paramName1,

          notype
          paramValue1,

          ...

          )

Sets texture parameters.

Note - may only be called AFTER addTexture() for that particular assetName

Parameters are set as key/value pairs and multiple may be specified.

Supported Parameters keys and values are:

"filter" - "nearest", "linear", "bilinear", "trilinear"

"minfilter" - "nearest", "linear"

"magfilter" - "nearest", "linear"

"repeat" - boolean true or false

"repeatX" - boolean true or false

"repeatY" - boolean true or false

Example:

 setTextureParams("tex/MyTex.png", "minfilter", "nearest", "repeat", false)

Parameters:

assetName	The texture's file asset name

paramName1	The first parameter name

paramValue1	The first parameter value

          renderItemId Game::start2DProjection
          (
          float
          left,

          float
          right,

          float
          bottom,

          float
          top,

          float
          near,

          float
          far

          )

Starts an alternate 2D Projection (Orthographic)

From when this projection is specified until end2DProjection or a different projection is specified, all 2D render calls will use this projection.

Parameters:

left	The left side coordinate

right	The right side coordinate

bottom	The bottom screen coordinate

top	The top screen coordinate

near	The near-plane

far	The far-plane

<address class="footer">
Generated on Fri Nov 30 2012 19:22:22 for BatteryTech Engine by

 1.8.1
</address>


text:
function arrayOf() {
  return [...arguments];
}

expect(Object.prototype.toString.call(arrayOf())).toBe('[object Array]');
expect(arrayOf(1, 2, 3)).toEqual([1, 2, 3]);


text:
set(lab5_msgs_MESSAGE_FILES "msg/ColorMsg.msg;msg/GUIEraseMsg.msg;msg/GUILineMsg.msg;msg/GUIPointMsg.msg;msg/GUISegmentMsg.msg")
set(lab5_msgs_SERVICE_FILES "")


text:
require 'fileutils'
require 'mvm'

class Init
  def self.run(args,options)
    dir_path = File.join(MVM::SETTING_DIR, MVM::DOWNLOAD_DIR)
    FileUtils.mkdir_p(dir_path)
    FileUtils.mkdir_p(MVM::INSTALL_DIR)

    versions_path  = File.join(MVM::SETTING_DIR, MVM::VERSIONS)
    installed_path = File.join(MVM::SETTING_DIR, MVM::INSTALLED)
    default_path   = File.join(MVM::SETTING_DIR, MVM::DEFAULT)
    install_dir    = MVM::INSTALL_DIR
    install_path   = MVM::INSTALL_PATH

    FileUtils.touch(versions_path)
    FileUtils.touch(installed_path)
    FileUtils.touch(default_path)
    FileUtils.touch(install_dir)
    FileUtils.touch(install_path)

    if options.installpath
      path = options.installpath
      open(MVM::INSTALL_PATH, 'w') do |f|
        f.write(path + "\n")
      end
    end

    puts 'Please input the following command.'
    puts '--- if all user use mvm ---'
    puts "echo 'export PATH=#{MVM::SYMBOLIC_LINK}:$PATH' >> /etc/profile"
    puts '--- if you use mvm ---'
    puts "echo 'export PATH=#{MVM::SYMBOLIC_LINK}:$PATH' >> ~/.bashrc"
  end
end


text:
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VI_IS_READY_REQUEST_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VI_IS_READY_REQUEST_H_

#include "application_manager/commands/hmi/request_to_hmi.h"

namespace application_manager {

namespace commands {

/**
 * @brief VIIsReadyRequest command class
 **/
class VIIsReadyRequest : public RequestToHMI,
                         public event_engine::EventObserver {
 public:
  /**
   * @brief VIIsReadyRequest class constructor
   *
   * @param message Incoming SmartObject message
   **/
  VIIsReadyRequest(const MessageSharedPtr& message,
                   ApplicationManager& application_manager);

  /**
   * @brief VIIsReadyRequest class destructor
   **/
  virtual ~VIIsReadyRequest();

  /**
   * @brief Execute command
   **/
  void Run() OVERRIDE;

  /**
   * @brief On event callback
   **/
  void on_event(const event_engine::Event& event) OVERRIDE;

  /**
   * @brief onTimeOut from requrst Controller
   */
  void onTimeOut() OVERRIDE;

  /**
   * @brief Send request to HMI for fetching of cappabilities
   */
  void SendMessageToHMI();

 private:
  DISALLOW_COPY_AND_ASSIGN(VIIsReadyRequest);
};

}  // namespace commands

}  // namespace application_manager

#endif  // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VI_IS_READY_REQUEST_H_


text:
package main

import (
	"fmt"

	"github.com/agencyrevolution/go-microservices-example/utils"
)

func main() {
	fmt.Println(utils.NewVulcandClient("", "", 0))
}


text:
'use strict';

let angular = require('angular');
let $ = require('jquery');

module.exports = angular.module('spinnaker.core.utils.jQuery', [])
  .factory('$', function() {
    return $;
  }).name;


text:
// Modifications copyright (C) 2017, Baidu.com, Inc.
// Copyright 2017 The Apache Software Foundation

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on 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.

package com.baidu.palo.analysis;

import com.baidu.palo.catalog.AccessPrivilege;
import com.baidu.palo.catalog.Catalog;
import com.baidu.palo.cluster.ClusterNamespace;
import com.baidu.palo.common.AnalysisException;
import com.baidu.palo.common.ErrorCode;
import com.baidu.palo.common.ErrorReport;
import com.baidu.palo.common.FeNameFormat;
import com.baidu.palo.mysql.privilege.PaloPrivilege;
import com.baidu.palo.mysql.privilege.PrivBitSet;
import com.baidu.palo.mysql.privilege.PrivPredicate;
import com.baidu.palo.qe.ConnectContext;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;

import java.util.List;

// REVOKE STMT
// revoke privilege from some user, this is an administrator operation.
//
// REVOKE privilege [, privilege] ON db.tbl FROM user [ROLE 'role'];
public class RevokeStmt extends DdlStmt {
    private UserIdentity userIdent;
    private String role;
    private TablePattern tblPattern;
    private List<PaloPrivilege> privileges;

    public RevokeStmt(UserIdentity userIdent, String role, TablePattern tblPattern, List<AccessPrivilege> privileges) {
        this.userIdent = userIdent;
        this.role = role;
        this.tblPattern = tblPattern;
        PrivBitSet privs = PrivBitSet.of();
        for (AccessPrivilege accessPrivilege : privileges) {
            privs.or(accessPrivilege.toPaloPrivilege());
        }
        this.privileges = privs.toPrivilegeList();
    }

    public UserIdentity getUserIdent() {
        return userIdent;
    }

    public TablePattern getTblPattern() {
        return tblPattern;
    }

    public String getQualifiedRole() {
        return role;
    }

    public List<PaloPrivilege> getPrivileges() {
        return privileges;
    }

    @Override
    public void analyze(Analyzer analyzer) throws AnalysisException {
        if (userIdent != null) {
            userIdent.analyze(analyzer.getClusterName());
        } else {
            FeNameFormat.checkRoleName(role, false /* can not be superuser */);
            role = ClusterNamespace.getFullName(analyzer.getClusterName(), role);
        }

        tblPattern.analyze(analyzer.getClusterName());

        if (privileges == null || privileges.isEmpty()) {
            throw new AnalysisException("No privileges in revoke statement.");
        }

        if (!Catalog.getCurrentCatalog().getAuth().checkGlobalPriv(ConnectContext.get(), PrivPredicate.GRANT)) {
            ErrorReport.reportAnalysisException(ErrorCode.ERR_SPECIFIC_ACCESS_DENIED_ERROR,
                                                "REVOKE");
        }
    }

    @Override
    public String toSql() {
        StringBuilder sb = new StringBuilder();
        sb.append("REVOKE ").append(Joiner.on(", ").join(privileges));
        sb.append(" ON ").append(tblPattern).append(" FROM ");
        if (!Strings.isNullOrEmpty(role)) {
            sb.append(" ROLE '").append(role).append("'");
        } else {
            sb.append(userIdent);
        }
        return sb.toString();
    }

    @Override
    public String toString() {
        return toSql();
    }
}


text:
<?php
/**
 * List Table API: WP_MS_Users_List_Table class
 *
 * @package WordPress
 * @subpackage Administration
 * @since 3.1.0
 */

/**
 * Core class used to implement displaying users in a list table for the network admin.
 *
 * @since 3.1.0
 * @access private
 *
 * @see WP_List_Table
 */
class WP_MS_Users_List_Table extends WP_List_Table {
	/**
	 *
	 * @return bool
	 */
	public function ajax_user_can() {
		return current_user_can( 'manage_network_users' );
	}

	/**
	 *
	 * @global string $usersearch
	 * @global string $role
	 * @global wpdb   $wpdb
	 * @global string $mode
	 */
	public function prepare_items() {
		global $usersearch, $role, $wpdb, $mode;

		$usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';

		$users_per_page = $this->get_items_per_page( 'users_network_per_page' );

		$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';

		$paged = $this->get_pagenum();

		$args = array(
			'number' => $users_per_page,
			'offset' => ( $paged-1 ) * $users_per_page,
			'search' => $usersearch,
			'blog_id' => 0,
			'fields' => 'all_with_meta'
		);

		if ( wp_is_large_network( 'users' ) ) {
			$args['search'] = ltrim( $args['search'], '*' );
		} else if ( '' !== $args['search'] ) {
			$args['search'] = trim( $args['search'], '*' );
			$args['search'] = '*' . $args['search'] . '*';
		}

		if ( $role === 'super' ) {
			$logins = implode( "', '", get_super_admins() );
			$args['include'] = $wpdb->get_col( "SELECT ID FROM $wpdb->users WHERE user_login IN ('$logins')" );
		}

		/*
		 * If the network is large and a search is not being performed,
		 * show only the latest users with no paging in order to avoid
		 * expensive count queries.
		 */
		if ( !$usersearch && wp_is_large_network( 'users' ) ) {
			if ( !isset($_REQUEST['orderby']) )
				$_GET['orderby'] = $_REQUEST['orderby'] = 'id';
			if ( !isset($_REQUEST['order']) )
				$_GET['order'] = $_REQUEST['order'] = 'DESC';
			$args['count_total'] = false;
		}

		if ( isset( $_REQUEST['orderby'] ) )
			$args['orderby'] = $_REQUEST['orderby'];

		if ( isset( $_REQUEST['order'] ) )
			$args['order'] = $_REQUEST['order'];

		if ( ! empty( $_REQUEST['mode'] ) ) {
			$mode = $_REQUEST['mode'] === 'excerpt' ? 'excerpt' : 'list';
			set_user_setting( 'network_users_list_mode', $mode );
		} else {
			$mode = get_user_setting( 'network_users_list_mode', 'list' );
		}

		/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
		$args = apply_filters( 'users_list_table_query_args', $args );

		// Query the user IDs for this page
		$wp_user_search = new WP_User_Query( $args );

		$this->items = $wp_user_search->get_results();

		$this->set_pagination_args( array(
			'total_items' => $wp_user_search->get_total(),
			'per_page' => $users_per_page,
		) );
	}

	/**
	 *
	 * @return array
	 */
	protected function get_bulk_actions() {
		$actions = array();
		if ( current_user_can( 'delete_users' ) )
			$actions['delete'] = __( 'Delete' );
		$actions['spam'] = _x( 'Mark as Spam', 'user' );
		$actions['notspam'] = _x( 'Not Spam', 'user' );

		return $actions;
	}

	/**
	 * @access public
	 */
	public function no_items() {
		_e( 'No users found.' );
	}

	/**
	 *
	 * @global string $role
	 * @return array
	 */
	protected function get_views() {
		global $role;

		$total_users = get_user_count();
		$super_admins = get_super_admins();
		$total_admins = count( $super_admins );

		$class = $role != 'super' ? ' class="current"' : '';
		$role_links = array();
		$role_links['all'] = "" . sprintf( _nx( 'All (%s)', 'All (%s)', $total_users, 'users' ), number_format_i18n( $total_users ) ) . '';
		$class = $role === 'super' ? ' class="current"' : '';
		$role_links['super'] = "" . sprintf( _n( 'Super Admin (%s)', 'Super Admins (%s)', $total_admins ), number_format_i18n( $total_admins ) ) . '';

		return $role_links;
	}

	/**
	 * @global string $mode List table view mode.
	 *
	 * @param string $which
	 */
	protected function pagination( $which ) {
		global $mode;

		parent::pagination ( $which );

		if ( 'top' === $which ) {
			$this->view_switcher( $mode );
		}
	}

	/**
	 *
	 * @return array
	 */
	public function get_columns() {
		$users_columns = array(
			'cb'         => '<input type="checkbox" />',
			'username'   => __( 'Username' ),
			'name'       => __( 'Name' ),
			'email'      => __( 'Email' ),
			'registered' => _x( 'Registered', 'user' ),
			'blogs'      => __( 'Sites' )
		);
		/**
		 * Filters the columns displayed in the Network Admin Users list table.
		 *
		 * @since MU
		 *
		 * @param array $users_columns An array of user columns. Default 'cb', 'username',
		 *                             'name', 'email', 'registered', 'blogs'.
		 */
		return apply_filters( 'wpmu_users_columns', $users_columns );
	}

	/**
	 *
	 * @return array
	 */
	protected function get_sortable_columns() {
		return array(
			'username'   => 'login',
			'name'       => 'name',
			'email'      => 'email',
			'registered' => 'id',
		);
	}

	/**
	 * Handles the checkbox column output.
	 *
	 * @since 4.3.0
	 * @access public
	 *
	 * @param WP_User $user The current WP_User object.
	 */
	public function column_cb( $user ) {
		if ( is_super_admin( $user->ID ) ) {
			return;
		}
		?>
		<label class="screen-reader-text" for="blog_<?php echo $user->ID; ?>"><?php echo sprintf( __( 'Select %s' ), $user->user_login ); ?>
		<input type="checkbox" id="blog_<?php echo $user->ID ?>" name="allusers[]" value="<?php echo esc_attr( $user->ID ) ?>" />
		<?php
	}

	/**
	 * Handles the ID column output.
	 *
	 * @since 4.4.0
	 * @access public
	 *
	 * @param WP_User $user The current WP_User object.
	 */
	public function column_id( $user ) {
		echo $user->ID;
	}

	/**
	 * Handles the username column output.
	 *
	 * @since 4.3.0
	 * @access public
	 *
	 * @param WP_User $user The current WP_User object.
	 */
	public function column_username( $user ) {
		$super_admins = get_super_admins();
		$avatar	= get_avatar( $user->user_email, 32 );
		$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );

		echo $avatar;

		?><a href="<?php echo $edit_link; ?>" class="edit"><?php echo $user->user_login; ?><?php
		if ( in_array( $user->user_login, $super_admins ) ) {
			echo ' - ' . __( 'Super Admin' );
		}
		?>
	<?php
	}

	/**
	 * Handles the name column output.
	 *
	 * @since 4.3.0
	 * @access public
	 *
	 * @param WP_User $user The current WP_User object.
	 */
	public function column_name( $user ) {
		echo "$user->first_name $user->last_name";
	}

	/**
	 * Handles the email column output.
	 *
	 * @since 4.3.0
	 * @access public
	 *
	 * @param WP_User $user The current WP_User object.
	 */
	public function column_email( $user ) {
		echo "user_email" ) . "'>$user->user_email";
	}

	/**
	 * Handles the registered date column output.
	 *
	 * @since 4.3.0
	 * @access public
	 *
	 * @global string $mode List table view mode.
	 *
	 * @param WP_User $user The current WP_User object.
	 */
	public function column_registered( $user ) {
		global $mode;
		if ( 'list' === $mode ) {
			$date = __( 'Y/m/d' );
		} else {
			$date = __( 'Y/m/d g:i:s a' );
		}
		echo mysql2date( $date, $user->user_registered );
	}

	/**
	 * @since 4.3.0
	 * @access protected
	 *
	 * @param WP_User $user
	 * @param string  $classes
	 * @param string  $data
	 * @param string  $primary
	 */
	protected function _column_blogs( $user, $classes, $data, $primary ) {
		echo '';
		echo $this->column_blogs( $user );
		echo $this->handle_row_actions( $user, 'blogs', $primary );
		echo '	';
	}

	/**
	 * Handles the sites column output.
	 *
	 * @since 4.3.0
	 * @access public
	 *
	 * @param WP_User $user The current WP_User object.
	 */
	public function column_blogs( $user ) {
		$blogs = get_blogs_of_user( $user->ID, true );
		if ( ! is_array( $blogs ) ) {
			return;
		}

		foreach ( $blogs as $val ) {
			if ( ! can_edit_network( $val->site_id ) ) {
				continue;
			}

			$path	= ( $val->path === '/' ) ? '' : $val->path;
			echo 'site_id . '" >';
			echo 'userblog_id ) ) .'">' . str_replace( '.' . get_network()->domain, '', $val->domain . $path ) . '';
			echo ' ';
			$actions = array();
			$actions['edit'] = 'userblog_id ) ) .'">' . __( 'Edit' ) . '';

			$class = '';
			if ( $val->spam == 1 ) {
				$class .= 'site-spammed ';
			}
			if ( $val->mature == 1 ) {
				$class .= 'site-mature ';
			}
			if ( $val->deleted == 1 ) {
				$class .= 'site-deleted ';
			}
			if ( $val->archived == 1 ) {
				$class .= 'site-archived ';
			}

			$actions['view'] = 'userblog_id ) ) . '">' . __( 'View' ) . '';

			/**
			 * Filters the action links displayed next the sites a user belongs to
			 * in the Network Admin Users list table.
			 *
			 * @since 3.1.0
			 *
			 * @param array $actions     An array of action links to be displayed.
			 *                           Default 'Edit', 'View'.
			 * @param int   $userblog_id The site ID.
			 */
			$actions = apply_filters( 'ms_user_list_site_actions', $actions, $val->userblog_id );

			$i=0;
			$action_count = count( $actions );
			foreach ( $actions as $action => $link ) {
				++$i;
				$sep = ( $i == $action_count ) ? '' : ' | ';
				echo "$link$sep";
			}
			echo '
';
		}
	}

	/**
	 * Handles the default column output.
	 *
	 * @since 4.3.0
	 * @access public
	 *
	 * @param WP_User $user       The current WP_User object.
	 * @param string $column_name The current column name.
	 */
	public function column_default( $user, $column_name ) {
		/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
		echo apply_filters( 'manage_users_custom_column', '', $column_name, $user->ID );
	}

	public function display_rows() {
		foreach ( $this->items as $user ) {
			$class = '';

			$status_list = array( 'spam' => 'site-spammed', 'deleted' => 'site-deleted' );

			foreach ( $status_list as $status => $col ) {
				if ( $user->$status ) {
					$class .= " $col";
				}
			}

			?>
			<tr class="<?php echo trim( $class ); ?>">
				<?php $this->single_row_columns( $user ); ?>

			<?php
		}
	}

	/**
	 * Gets the name of the default primary column.
	 *
	 * @since 4.3.0
	 * @access protected
	 *
	 * @return string Name of the default primary column, in this case, 'username'.
	 */
	protected function get_default_primary_column_name() {
		return 'username';
	}

	/**
	 * Generates and displays row action links.
	 *
	 * @since 4.3.0
	 * @access protected
	 *
	 * @param object $user        User being acted upon.
	 * @param string $column_name Current column name.
	 * @param string $primary     Primary column name.
	 * @return string Row actions output for users in Multisite.
	 */
	protected function handle_row_actions( $user, $column_name, $primary ) {
		if ( $primary !== $column_name ) {
			return '';
		}

		$super_admins = get_super_admins();
		$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );

		$actions = array();
		$actions['edit'] = '' . __( 'Edit' ) . '';

		if ( current_user_can( 'delete_user', $user->ID ) && ! in_array( $user->user_login, $super_admins ) ) {
			$actions['delete'] = 'ID ) ) ) . '" class="delete">' . __( 'Delete' ) . '';
		}

		/**
		 * Filters the action links displayed under each user in the Network Admin Users list table.
		 *
		 * @since 3.2.0
		 *
		 * @param array   $actions An array of action links to be displayed.
		 *                         Default 'Edit', 'Delete'.
		 * @param WP_User $user    WP_User object.
		 */
		$actions = apply_filters( 'ms_user_row_actions', $actions, $user );
		return $this->row_actions( $actions );
	}
}


text:
title: "Sunglasses and a hoodie"
excerpt: "PaperFaces portrait of @mh drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-mh-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-mh-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
---

PaperFaces portrait of project donator [@mh](https://twitter.com/mh).

{% include_cached boilerplate/paperfaces.md %}


text:
package de.passau.uni.sec.compose.id.core.event;

import java.util.Collection;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.passau.uni.sec.compose.id.common.exception.IdManagementException;

import de.passau.uni.sec.compose.id.core.domain.IPrincipal;
import de.passau.uni.sec.compose.id.core.service.security.RestAuthentication;
import de.passau.uni.sec.compose.id.rest.messages.UserCreateMessage;

public class GetUserSelfEvent extends AbstractGetEvent implements Event
{

	private static Logger LOG = LoggerFactory.getLogger(GetUserSelfEvent.class);

	public GetUserSelfEvent( Collection<IPrincipal> principals) throws IdManagementException
	{
		this.principals = principals;
	}

	@Override
	public String getLoggingDetails() {

		return "User querying data for himself. principals: "+RestAuthentication.getBasicInfoPrincipals(principals);

	}

}


text:
module Split
  class Experiment
    attr_accessor :name
    attr_writer :algorithm
    attr_accessor :resettable
    attr_accessor :goals
    attr_accessor :alternatives
    attr_accessor :max_participant_count
    attr_accessor :wiki_url

    DEFAULT_OPTIONS = {
      :resettable => true,
    }

    def initialize(name, options = {})
      options = DEFAULT_OPTIONS.merge(options)

      @name = name.to_s

      alternatives = extract_alternatives_from_options(options)

      if alternatives.empty? && (exp_config = Split.configuration.experiment_for(name))
        set_alternatives_and_options(
          alternatives: load_alternatives_from_configuration,
          goals: load_goals_from_configuration,
          resettable: exp_config[:resettable],
          algorithm: exp_config[:algorithm],
          max_participant_count: exp_config[:max_participant_count]
        )
      else
        set_alternatives_and_options(
          alternatives: alternatives,
          goals: options[:goals],
          resettable: options[:resettable],
          algorithm: options[:algorithm],
          max_participant_count: options[:max_participant_count]
        )
      end
    end

    def set_alternatives_and_options(options)
      self.alternatives = options[:alternatives]
      self.goals = options[:goals]
      self.resettable = options[:resettable]
      self.algorithm = options[:algorithm]
      unless options[:max_participant_count].nil?
        self.max_participant_count = options[:max_participant_count].to_i
      end
    end

    def extract_alternatives_from_options(options)
      alts = options[:alternatives] || []

      if alts.length == 1
        if alts[0].is_a? Hash
          alts = alts[0].map{|k,v| {k => v} }
        end
      end

      alts
    end

    def self.all
      ExperimentCatalog.all
    end

    # Return experiments without a winner (considered "active") first
    def self.all_active_first
      ExperimentCatalog.all_active_first
    end

    def self.find(name)
      ExperimentCatalog.find(name)
    end

    def self.find_or_create(label, *alternatives)
      ExperimentCatalog.find_or_create(label, *alternatives)
    end

    def save
      validate!

      Split.redis.with do |conn|

        if new_record?
          conn.sadd(:experiments, name)
          start unless Split.configuration.start_manually
          @alternatives.reverse.each {|a| conn.lpush(name, a.name)}
          @goals.reverse.each {|a| conn.lpush(goals_key, a)} unless @goals.nil?
        else
          existing_alternatives = load_alternatives_from_redis
          existing_goals = load_goals_from_redis
          unless existing_alternatives == @alternatives.map(&:name) && existing_goals == @goals
            reset
            @alternatives.each(&:delete)
            delete_goals
            conn.del(@name)
            @alternatives.reverse.each {|a| conn.lpush(name, a.name)}
            @goals.reverse.each {|a| conn.lpush(goals_key, a)} unless @goals.nil?
          end
        end

        conn.hset(experiment_config_key, :resettable, resettable)
        conn.hset(experiment_config_key, :algorithm, algorithm.to_s)
        conn.hset(experiment_config_key, :max_participant_count, max_participant_count) unless max_participant_count.nil?
      end
      self
    end

    def validate!
      if @alternatives.empty? && Split.configuration.experiment_for(@name).nil?
        raise ExperimentNotFound.new("Experiment #{@name} not found")
      end
      @alternatives.each {|a| a.validate! }
      unless @goals.nil? || goals.kind_of?(Array)
        raise ArgumentError, 'Goals must be an array'
      end
    end

    def new_record?
      Split.redis.with do |conn|
      !conn.exists(name)
      end
    end

    def to_hash
      {
        version: self.version,
        algorithm: self.algorithm,
        resettable: self.resettable,
        started_at: self.start_time,
        ended_at: self.end_time
      }
    end

    def ==(obj)
      self.name == obj.name
    end

    def [](name)
      alternatives.find{|a| a.name == name}
    end

    def wiki_url
      @wiki_url ||= load_wiki_url_from_redis
    end

    def algorithm
      @algorithm ||= Split.configuration.algorithm
    end

    def max_participant_count=(max_participant_count)
      @max_participant_count = max_participant_count.to_i
    end

    def algorithm=(algorithm)
      @algorithm = algorithm.is_a?(String) ? algorithm.constantize : algorithm
    end

    def resettable=(resettable)
      @resettable = resettable.is_a?(String) ? resettable == 'true' : resettable
    end

    def alternatives=(alts)
      @alternatives = alts.map do |alternative|
        if alternative.kind_of?(Split::Alternative)
          alternative
        else
          Split::Alternative.new(alternative, @name)
        end
      end
    end

    def wiki_url= url
      @wiki_url = url
      Split.redis.with do |conn|
        conn.hset(:wiki_urls, @name, @wiki_url)
      end
    end

    def winner
      Split.redis.with do |conn|
        if w = conn.hget(:experiment_winner, name)
          Split::Alternative.new(w, name)
        else
          nil
        end
      end
    end

    def has_enough_participants?
      if max_participant_count.nil? # it's never enough if no max participant count is set
        false
      elsif max_participant_count > participant_count # this can trigger as many as 4 Redis queries
        false
      else
        true
      end
    end

    def has_winner?
      @has_winner.nil? ? !winner.nil? : @has_winner
    end

    def has_winner!
      @has_winner = true
    end

    def has_no_winner!
      @has_winner = false
    end

    def winner=(winner_name)
      Split.redis.with do |conn|
        conn.hset(:experiment_winner, name, winner_name.to_s)
      end
      set_end_time
      delete_participants
      delete_finished
      alternatives.each(&:flatten_values)
    end

    def participant_count
      alternatives.inject(0){|sum,a| sum + a.participant_count}
    end

    def control
      alternatives.first
    end

    def reset_winner
      Split.redis.with do |conn|
        conn.hdel(:experiment_winner, name)
      end
    end

    def end_time
      Split.redis.with do |conn|
        t = conn.hget(:experiment_end_times, @name)
        if t
          # Check if stored time is an integer
          if t =~ /^[-+]?[0-9]+$/
            t = Time.at(t.to_i)
          else
            t = Time.parse(t)
          end
        end
      end
    end

    def set_end_time
      Split.redis.with do |conn|
        conn.hset(:experiment_end_times, name, Time.now.to_i)
      end
      Split.configuration.on_experiment_end.call(self)
    end

    def start
      Split.redis.with do |conn|
        conn.hset(:experiment_start_times, @name, Time.now.to_i)
      end
    end

    def start_time
      Split.redis.with do |conn|
        t = conn.hget(:experiment_start_times, @name)
        if t
          # Check if stored time is an integer
          if t =~ /^[-+]?[0-9]+$/
            t = Time.at(t.to_i)
          else
            t = Time.parse(t)
          end
        end
      end
    end

    #TODO: This currently only works with WeightedSample algorithm.
    def random_alternatives(num_participants)
      if winner
        Array.new(num_participants, winner)
      else
        algorithm.choose_alternatives(self, num_participants)
      end
    end

    def random_alternative(split_id)
      if alternatives.length > 1
        algorithm.choose_alternative(self, split_id)
      else
        alternatives.first
      end
    end

    def version
      Split.redis.with do |conn|
        @version ||= (conn.get("#{name.to_s}:version").to_i || 0)
      end
    end

    def increment_version
      Split.redis.with do |conn|
        @version = conn.incr("#{name}:version")
      end
    end

    def key(goal=nil)
      if version.to_i > 0
        if goal
          "#{name}:#{version}:#{goal}"
        else
          "#{name}:#{version}"
        end
      else
        if goal
          "#{name}:#{goal}"
        else
          "#{name}"
        end
      end
    end

    def goals_key
      "#{name}:goals"
    end

    def finished?(split_id, goal = nil)
      @finished ||= {}

      goalkey = goal || "nogoal"

      if !@finished[split_id].nil? && !@finished[split_id][goalkey].nil?
        return @finished[split_id][goalkey]
      else
        key = "#{self.key}:finished"
        key << ":#{goal}" if goal
        value = Split.redis.with do |conn|
          conn.sismember(key, split_id)
        end

        @finished[split_id] ||= {}
        @finished[split_id][goalkey] = value

        return value
      end
    end

    def cache_finished!(split_id, value, goal = nil)
      @finished ||= {}

      @finished[split_id] ||= {}

      if goal
        @finished[split_id][goal] = value
      else
        @finished[split_id]["nogoal"] = value
      end
    end

    def self.preload_participating!(experiments, split_ids)
      experiments = Array(experiments)
      split_ids = Array(split_ids)

      experiments_metadata = []
      experiments.each do |experiment|
        split_ids.each do |split_id|
          key = "#{experiment.key}:participants"

          experiments_metadata << {
              :key => key,
              :experiment => experiment,
              :split_id => split_id
          }
        end
      end

      if experiments_metadata.present?
        results = Split.redis.with do |conn|
          conn.pipelined do
            experiments_metadata.each do |metadata|
              conn.sismember metadata[:key], metadata[:split_id]
            end
          end
        end

        results.each_with_index do |result, index|
          metadata = experiments_metadata[index]
          metadata[:experiment].cache_participating!(metadata[:split_id], result)
        end
      end
    end

    def self.preload_finished!(experiments, goals, split_ids)
      experiments = Array(experiments)
      split_ids = Array(split_ids)

      experiments_metadata = []
      goals.each do |goal|
        experiments.each do |experiment|
          split_ids.each do |split_id|
            key = "#{experiment.key}:finished:#{goal}"

            experiments_metadata << {
                :key => key,
                :experiment => experiment,
                :goal => goal,
                :split_id => split_id
            }
          end
        end
      end

      if experiments_metadata.present?
        results = Split.redis.with do |conn|
          conn.pipelined do
            experiments_metadata.each do |metadata|
              conn.sismember metadata[:key], metadata[:split_id]
            end
          end
        end

        results.each_with_index do |result, index|
          metadata = experiments_metadata[index]
          metadata[:experiment].cache_finished!(metadata[:split_id], result, metadata[:goal])
        end
      end
    end

    def finish!(split_id, goal = nil)
      key = "#{self.key}:finished"
      key << ":#{goal}" if goal
      Split.redis.with do |conn|
        conn.sadd(key, split_id)
      end

      cache_finished!(split_id, true, goal)
    end

    def participate!(split_ids)
      split_ids = Array(split_ids)
      return if split_ids.blank?

      key = "#{self.key}:participants"
      Split.redis.with do |conn|
        conn.sadd(key, split_ids)
      end

      cache_participating!(split_ids, true)
    end

    def cache_participating!(split_ids, value)
      split_ids = Array(split_ids)

      @participating ||= {}

      split_ids.each do |split_id|
        @participating[split_id] = value
      end
    end

    def participating?(split_id)
      @participating ||= {}

      if !@participating[split_id].nil?
        return @participating[split_id]
      else
        key = "#{self.key}:participants"
        value = Split.redis.with do |conn|
          conn.sismember(key, split_id)
        end

        @participating[split_id] = value

        return value
      end
    end

    def resettable?
      resettable
    end

    def reset
      alternatives.each(&:reset)
      reset_winner
      delete_participants
      delete_finished
      Split.configuration.on_experiment_reset.call(self)
      increment_version
      Split.configuration.reset
    end

    def delete
      Split.redis.with do |conn|
        alternatives.each(&:delete)
        reset_winner
        conn.srem(:experiments, name)
        conn.del(name)
        delete_participants
        delete_finished
        delete_goals
        Split.configuration.on_experiment_delete.call(self)
        increment_version
        Split.configuration.reset
      end
    end

    def delete_participants
      Split.redis.with do |conn|
        Split::Persistence.adapter.garbage_collect("sets", "#{self.key}:participants")
      end
    end

    def delete_finished
      Split.redis.with do |conn|
        key = "#{self.key}:finished"
        Split::Persistence.adapter.garbage_collect("sets", key)
        (goals).each do |goal|
          Split::Persistence.adapter.garbage_collect("sets", "#{key}:#{goal}")
        end
      end
    end

    def delete_goals
      Split.redis.with do |conn|
        conn.del(goals_key)
      end
    end

    def load_from_redis
      Split.redis.with do |conn|
        exp_config = conn.hgetall(experiment_config_key)
        self.resettable = exp_config['resettable']
        self.algorithm = exp_config['algorithm']
        self.alternatives = load_alternatives_from_redis
        self.goals = load_goals_from_redis
        unless exp_config['max_participant_count'].nil?
          self.max_participant_count = exp_config['max_participant_count'].to_i
        end
      end
    end

    protected

    def experiment_config_key
      "experiment_configurations/#{@name}"
    end

    def load_goals_from_configuration
      goals = Split.configuration.experiment_for(@name)[:goals]
      if goals.nil?
        goals = []
      else
        goals.flatten
      end
    end

    def load_goals_from_redis
      Split.redis.with do |conn|
        conn.lrange(goals_key, 0, -1)
      end
    end

    def load_alternatives_from_configuration
      alts = Split.configuration.experiment_for(@name)[:alternatives]
      raise ArgumentError, "Experiment configuration is missing :alternatives array" unless alts
      if alts.is_a?(Hash)
        alts.keys
      else
        alts.flatten
      end
    end

    def load_wiki_url_from_redis
      Split.redis.with do |conn|
        @wiki_url = conn.hget(:wiki_urls, @name)
      end
    end

    def load_alternatives_from_redis
      Split.redis.with do |conn|
        case conn.type(@name)
        when 'set' # convert legacy sets to lists
          alts = conn.smembers(@name)
          conn.del(@name)
          alts.reverse.each {|a| Split.redis.lpush(@name, a) }
          conn.lrange(@name, 0, -1)
        else
          conn.lrange(@name, 0, -1)
        end
      end
    end
  end
end


text:
/* See license.txt for terms of usage */

define([], function() {

// ********************************************************************************************* //
// Constants

const Cu = Components.utils;

// ********************************************************************************************* //
// Tracing

try
{
    // Firebug tracing extension (FBTrace) must be installed
    var scope = {};
    Components.utils["import"]("resource://fbtrace/firebug-trace-service.js", scope);
    return scope.traceConsoleService.getTracer("extensions.firebug");
}
catch (e)
{
}

// ********************************************************************************************* //
// Empty implementation

var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"];
var TraceObj = {};
for (var i=0; i<TraceAPI.length; i++)
    TraceObj[TraceAPI[i]] = function() {};

return TraceObj;

// ********************************************************************************************* //
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="description" content="Shaka Player Demo">
    <meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="theme-color" content="#ffffff">

    <base target="_blank">

    <title>Shaka Player Demo</title>

    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="demo.css">
    <link rel="stylesheet" href="controls.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Condensed">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Shaka Player

This is a demo of Google's Shaka Player, a JavaScript library for
           adaptive video streaming.

Choose an asset and tap Load.
           (On Android, you may also need to press the play button on the
            video.)

          Documentation |
          Repo |
          NPM |
          CDNJS

          Asset:
          <select id="assetList" class="flex-grow"></select>

            Custom manifest:
            <input id="manifestInput" type="text" class="flex-grow">

            Custom license server:
            <input id="licenseServerInput" type="text" class="flex-grow">

          <button id="loadButton">Load</button>

x

        <video id="video"
               poster="//shaka-player-demo.appspot.com/assets/poster.jpg"
               autoplay></video>

          <button id="giantPlayButton" class="material-icons">play_arrow</button>

          <svg class="spinnerSvg" viewBox="25 25 50 50">
            <circle class="spinnerPath" cx="50" cy="50" r="20"
                    fill="none" stroke-width="2" stroke-miterlimit="10" />
          </svg>

          <button id="playPauseButton" class="material-icons">play_arrow</button>
          seek
          <input id="seekBar" type="range" step="any" min="0" max="1" value="0">
          <button id="rewindButton" class="material-icons">fast_rewind</button>

0:00

          <button id="fastForwardButton" class="material-icons">fast_forward</button>
          <button id="muteButton" class="material-icons">volume_up</button>
          volume
          <input id="volumeBar" type="range" step="any" min="0" max="1" value="0">
          <button id="castButton" class="material-icons">cast</button>
          <button id="captionButton" class="material-icons">closed_caption</button>
          <button id="fullscreenButton" class="material-icons">fullscreen</button>

        Logs

        Configuration

          Preferred audio language:
          <input id="preferredAudioLanguage" class="flex-grow" type="text">

          Preferred text language:
          <input id="preferredTextLanguage" class="flex-grow" type="text">

          Show trick play controls:
          <input id="showTrickPlay" type="checkbox">

          Enable adaptation:
          <input id="enableAdaptation" type="checkbox" checked>

          Log to the screen:
          <input id="logToScreen" type="checkbox">

        Info

          Audio languages:
          <select id="audioLanguages" class="flex-grow"></select>

          Video+audio track combinations:
          <select id="variantTracks" class="flex-grow"></select>

          Text languages:
          <select id="textLanguages" class="flex-grow"></select>

          Text tracks:
          <select id="textTracks" class="flex-grow"></select>

          Active resolution:

          Buffered:

        Offline

          <button id="storeDelete">Store</button>

          Progress:
          0%

          Name:
          <input id="offlineName" class="flex-grow" type="text">


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * String.prototype.lastIndexOf(searchString, position)
 *
 * @path ch15/15.5/15.5.4/15.5.4.8/S15.5.4.8_A1_T7.js
 * @description Call lastIndexOf(searchString, position) function with undefined argument of string object
 */

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
//since ToString(undefined) evaluates to "undefined" lastIndexOf(undefined) evaluates to lastIndexOf("undefined",0)
if (String("undefined").lastIndexOf(undefined) !== 0) {
  $ERROR('#1: String("undefined").lastIndexOf(undefined) === 0. Actual: '+String("undefined").lastIndexOf(undefined) );
}
//
//////////////////////////////////////////////////////////////////////////////


text:
package main

import (
	"fmt"
	"io/ioutil"
	"net/http/httptest"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"sync"
	"syscall"
	"testing"
	"time"

	"github.com/docker/docker/api/types/swarm"
	"github.com/docker/docker/integration-cli/checker"
	"github.com/docker/docker/integration-cli/cli"
	"github.com/docker/docker/integration-cli/cli/build/fakestorage"
	"github.com/docker/docker/integration-cli/daemon"
	"github.com/docker/docker/integration-cli/environment"
	"github.com/docker/docker/integration-cli/fixtures/plugin"
	"github.com/docker/docker/integration-cli/registry"
	ienv "github.com/docker/docker/internal/test/environment"
	"github.com/docker/docker/pkg/reexec"
	"github.com/go-check/check"
	"golang.org/x/net/context"
)

const (
	// the private registry to use for tests
	privateRegistryURL = "127.0.0.1:5000"

	// path to containerd's ctr binary
	ctrBinary = "docker-containerd-ctr"

	// the docker daemon binary to use
	dockerdBinary = "dockerd"
)

var (
	testEnv *environment.Execution

	// the docker client binary to use
	dockerBinary = ""
)

func init() {
	var err error

	reexec.Init() // This is required for external graphdriver tests

	testEnv, err = environment.New()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func TestMain(m *testing.M) {
	dockerBinary = testEnv.DockerBinary()
	err := ienv.EnsureFrozenImagesLinux(&testEnv.Execution)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	testEnv.Print()
	os.Exit(m.Run())
}

func Test(t *testing.T) {
	cli.SetTestEnvironment(testEnv)
	fakestorage.SetTestEnvironment(&testEnv.Execution)
	ienv.ProtectAll(t, &testEnv.Execution)
	check.TestingT(t)
}

func init() {
	check.Suite(&DockerSuite{})
}

type DockerSuite struct {
}

func (s *DockerSuite) OnTimeout(c *check.C) {
	if testEnv.IsRemoteDaemon() {
		return
	}
	path := filepath.Join(os.Getenv("DEST"), "docker.pid")
	b, err := ioutil.ReadFile(path)
	if err != nil {
		c.Fatalf("Failed to get daemon PID from %s\n", path)
	}

	rawPid, err := strconv.ParseInt(string(b), 10, 32)
	if err != nil {
		c.Fatalf("Failed to parse pid from %s: %s\n", path, err)
	}

	daemonPid := int(rawPid)
	if daemonPid > 0 {
		daemon.SignalDaemonDump(daemonPid)
	}
}

func (s *DockerSuite) TearDownTest(c *check.C) {
	testEnv.Clean(c)
}

func init() {
	check.Suite(&DockerRegistrySuite{
		ds: &DockerSuite{},
	})
}

type DockerRegistrySuite struct {
	ds  *DockerSuite
	reg *registry.V2
	d   *daemon.Daemon
}

func (s *DockerRegistrySuite) OnTimeout(c *check.C) {
	s.d.DumpStackAndQuit()
}

func (s *DockerRegistrySuite) SetUpTest(c *check.C) {
	testRequires(c, DaemonIsLinux, registry.Hosting, SameHostDaemon)
	s.reg = setupRegistry(c, false, "", "")
	s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
		Experimental: testEnv.DaemonInfo.ExperimentalBuild,
	})
}

func (s *DockerRegistrySuite) TearDownTest(c *check.C) {
	if s.reg != nil {
		s.reg.Close()
	}
	if s.d != nil {
		s.d.Stop(c)
	}
	s.ds.TearDownTest(c)
}

func init() {
	check.Suite(&DockerSchema1RegistrySuite{
		ds: &DockerSuite{},
	})
}

type DockerSchema1RegistrySuite struct {
	ds  *DockerSuite
	reg *registry.V2
	d   *daemon.Daemon
}

func (s *DockerSchema1RegistrySuite) OnTimeout(c *check.C) {
	s.d.DumpStackAndQuit()
}

func (s *DockerSchema1RegistrySuite) SetUpTest(c *check.C) {
	testRequires(c, DaemonIsLinux, registry.Hosting, NotArm64, SameHostDaemon)
	s.reg = setupRegistry(c, true, "", "")
	s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
		Experimental: testEnv.DaemonInfo.ExperimentalBuild,
	})
}

func (s *DockerSchema1RegistrySuite) TearDownTest(c *check.C) {
	if s.reg != nil {
		s.reg.Close()
	}
	if s.d != nil {
		s.d.Stop(c)
	}
	s.ds.TearDownTest(c)
}

func init() {
	check.Suite(&DockerRegistryAuthHtpasswdSuite{
		ds: &DockerSuite{},
	})
}

type DockerRegistryAuthHtpasswdSuite struct {
	ds  *DockerSuite
	reg *registry.V2
	d   *daemon.Daemon
}

func (s *DockerRegistryAuthHtpasswdSuite) OnTimeout(c *check.C) {
	s.d.DumpStackAndQuit()
}

func (s *DockerRegistryAuthHtpasswdSuite) SetUpTest(c *check.C) {
	testRequires(c, DaemonIsLinux, registry.Hosting, SameHostDaemon)
	s.reg = setupRegistry(c, false, "htpasswd", "")
	s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
		Experimental: testEnv.DaemonInfo.ExperimentalBuild,
	})
}

func (s *DockerRegistryAuthHtpasswdSuite) TearDownTest(c *check.C) {
	if s.reg != nil {
		out, err := s.d.Cmd("logout", privateRegistryURL)
		c.Assert(err, check.IsNil, check.Commentf(out))
		s.reg.Close()
	}
	if s.d != nil {
		s.d.Stop(c)
	}
	s.ds.TearDownTest(c)
}

func init() {
	check.Suite(&DockerRegistryAuthTokenSuite{
		ds: &DockerSuite{},
	})
}

type DockerRegistryAuthTokenSuite struct {
	ds  *DockerSuite
	reg *registry.V2
	d   *daemon.Daemon
}

func (s *DockerRegistryAuthTokenSuite) OnTimeout(c *check.C) {
	s.d.DumpStackAndQuit()
}

func (s *DockerRegistryAuthTokenSuite) SetUpTest(c *check.C) {
	testRequires(c, DaemonIsLinux, registry.Hosting, SameHostDaemon)
	s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
		Experimental: testEnv.DaemonInfo.ExperimentalBuild,
	})
}

func (s *DockerRegistryAuthTokenSuite) TearDownTest(c *check.C) {
	if s.reg != nil {
		out, err := s.d.Cmd("logout", privateRegistryURL)
		c.Assert(err, check.IsNil, check.Commentf(out))
		s.reg.Close()
	}
	if s.d != nil {
		s.d.Stop(c)
	}
	s.ds.TearDownTest(c)
}

func (s *DockerRegistryAuthTokenSuite) setupRegistryWithTokenService(c *check.C, tokenURL string) {
	if s == nil {
		c.Fatal("registry suite isn't initialized")
	}
	s.reg = setupRegistry(c, false, "token", tokenURL)
}

func init() {
	check.Suite(&DockerDaemonSuite{
		ds: &DockerSuite{},
	})
}

type DockerDaemonSuite struct {
	ds *DockerSuite
	d  *daemon.Daemon
}

func (s *DockerDaemonSuite) OnTimeout(c *check.C) {
	s.d.DumpStackAndQuit()
}

func (s *DockerDaemonSuite) SetUpTest(c *check.C) {
	testRequires(c, DaemonIsLinux, SameHostDaemon)
	s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
		Experimental: testEnv.DaemonInfo.ExperimentalBuild,
	})
}

func (s *DockerDaemonSuite) TearDownTest(c *check.C) {
	testRequires(c, DaemonIsLinux, SameHostDaemon)
	if s.d != nil {
		s.d.Stop(c)
	}
	s.ds.TearDownTest(c)
}

func (s *DockerDaemonSuite) TearDownSuite(c *check.C) {
	filepath.Walk(daemon.SockRoot, func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			// ignore errors here
			// not cleaning up sockets is not really an error
			return nil
		}
		if fi.Mode() == os.ModeSocket {
			syscall.Unlink(path)
		}
		return nil
	})
	os.RemoveAll(daemon.SockRoot)
}

const defaultSwarmPort = 2477

func init() {
	check.Suite(&DockerSwarmSuite{
		ds: &DockerSuite{},
	})
}

type DockerSwarmSuite struct {
	server      *httptest.Server
	ds          *DockerSuite
	daemons     []*daemon.Swarm
	daemonsLock sync.Mutex // protect access to daemons
	portIndex   int
}

func (s *DockerSwarmSuite) OnTimeout(c *check.C) {
	s.daemonsLock.Lock()
	defer s.daemonsLock.Unlock()
	for _, d := range s.daemons {
		d.DumpStackAndQuit()
	}
}

func (s *DockerSwarmSuite) SetUpTest(c *check.C) {
	testRequires(c, DaemonIsLinux, SameHostDaemon)
}

func (s *DockerSwarmSuite) AddDaemon(c *check.C, joinSwarm, manager bool) *daemon.Swarm {
	d := &daemon.Swarm{
		Daemon: daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
			Experimental: testEnv.DaemonInfo.ExperimentalBuild,
		}),
		Port: defaultSwarmPort + s.portIndex,
	}
	d.ListenAddr = fmt.Sprintf("0.0.0.0:%d", d.Port)
	args := []string{"--iptables=false", "--swarm-default-advertise-addr=lo"} // avoid networking conflicts
	d.StartWithBusybox(c, args...)

	if joinSwarm {
		if len(s.daemons) > 0 {
			tokens := s.daemons[0].JoinTokens(c)
			token := tokens.Worker
			if manager {
				token = tokens.Manager
			}
			c.Assert(d.Join(swarm.JoinRequest{
				RemoteAddrs: []string{s.daemons[0].ListenAddr},
				JoinToken:   token,
			}), check.IsNil)
		} else {
			c.Assert(d.Init(swarm.InitRequest{}), check.IsNil)
		}
	}

	s.portIndex++
	s.daemonsLock.Lock()
	s.daemons = append(s.daemons, d)
	s.daemonsLock.Unlock()

	return d
}

func (s *DockerSwarmSuite) TearDownTest(c *check.C) {
	testRequires(c, DaemonIsLinux)
	s.daemonsLock.Lock()
	for _, d := range s.daemons {
		if d != nil {
			d.Stop(c)
			// FIXME(vdemeester) should be handled by SwarmDaemon ?
			// raft state file is quite big (64MB) so remove it after every test
			walDir := filepath.Join(d.Root, "swarm/raft/wal")
			if err := os.RemoveAll(walDir); err != nil {
				c.Logf("error removing %v: %v", walDir, err)
			}

			d.CleanupExecRoot(c)
		}
	}
	s.daemons = nil
	s.daemonsLock.Unlock()

	s.portIndex = 0
	s.ds.TearDownTest(c)
}

func init() {
	check.Suite(&DockerPluginSuite{
		ds: &DockerSuite{},
	})
}

type DockerPluginSuite struct {
	ds       *DockerSuite
	registry *registry.V2
}

func (ps *DockerPluginSuite) registryHost() string {
	return privateRegistryURL
}

func (ps *DockerPluginSuite) getPluginRepo() string {
	return path.Join(ps.registryHost(), "plugin", "basic")
}
func (ps *DockerPluginSuite) getPluginRepoWithTag() string {
	return ps.getPluginRepo() + ":" + "latest"
}

func (ps *DockerPluginSuite) SetUpSuite(c *check.C) {
	testRequires(c, DaemonIsLinux, registry.Hosting)
	ps.registry = setupRegistry(c, false, "", "")

	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	err := plugin.CreateInRegistry(ctx, ps.getPluginRepo(), nil)
	c.Assert(err, checker.IsNil, check.Commentf("failed to create plugin"))
}

func (ps *DockerPluginSuite) TearDownSuite(c *check.C) {
	if ps.registry != nil {
		ps.registry.Close()
	}
}

func (ps *DockerPluginSuite) TearDownTest(c *check.C) {
	ps.ds.TearDownTest(c)
}

func (ps *DockerPluginSuite) OnTimeout(c *check.C) {
	ps.ds.OnTimeout(c)
}


text:
@protocol LeftViewControllerDelegate <NSObject>

- (void)didTableView:(UITableView *)tableView clickIndexPath:(NSIndexPath *)indexPath;

@end
@interface LeftViewController : SelectedAdressViewController

@property (nonatomic, weak) id<LeftViewControllerDelegate>delegate;

@end


text:
/*
 * WinJS Contrib v2.1.0.6
 * licensed under MIT license (see http://opensource.org/licenses/MIT)
 * sources available at https://github.com/gleborgne/winjscontrib
 */

//example of expected signature for data container

(function () {
    'use strict';
    WinJS.Namespace.define("WinJSContrib.DataContainer", {
        CordovaDatabaseContainer: WinJS.Class.define(function ctor(key, options, parent) {
            this.key = key || 'mcndatacontainer';
            this.options = options;
            this.parent = parent;
            if (parent) {
                this.storageKey = parent.storageKey + '.' + this.key;
            } else {
                this.storageKey = this.key;
            }

            var container = this;
        }, {
            read: function (itemkey) {
                var container = this;
                var db = openDatabase('survey', '1.0', 'database', 2000000);
                //tx.executeSql('CREATE TABLE IF NOT EXISTS ' + encodeURIComponent(container.key) + ' (id unique, data)');

                console.log('trying to read ' + itemkey);
                return new WinJS.Promise(function (readComplete, readError) {
                    db.transaction(function (tx) {
                        tx.executeSql('SELECT * FROM ' + toValidName(container.key) + ' WHERE itemkey=?', [itemkey], function (tx, results) {
                            if (results.rows && results.rows.length) {
                                var res = JSON.parse(results.rows.item(0).data);
                                readComplete(res);
                            }
                            else
                                readComplete(null);
                        }, function (tx, e) {
                            readComplete(null);
                        });

                    }, function (tx, e) {
                        readComplete(null);
                    });
                });
            },

            save: function (itemkey, obj) {
                var container = this;
                var db = openDatabase('survey', '1.0', 'database', 2000000);
                return new WinJS.Promise(function (saveComplete, saveError) {
                    if (obj) {
                        var tmp = JSON.stringify(obj);

                        db.transaction(function (tx) {
                            tx.executeSql('CREATE TABLE IF NOT EXISTS ' + toValidName(container.key) + '(itemkey TEXT PRIMARY KEY, data)');
                        }, function (t, e) {
                            saveError();
                        }, function (t, e) {
                            db.transaction(function (tx) {
                                tx.executeSql('INSERT OR REPLACE INTO ' + toValidName(container.key) + '(itemkey, data) VALUES (?,?)', [itemkey, tmp], function (te, ee) {
                                    saveComplete();
                                }, function (te, ee) {
                                    saveError()
                                });
                            }, function (te, ee) {
                                saveError()
                            });
                        });
                    }
                });
            },

            remove: function (itemkey) {
                var container = this;
                var db = openDatabase('survey', '1.0', 'database', 2000000);
                return new WinJS.Promise(function (deleteComplete, deleteError) {
                    db.transaction(function (tx) {
                        tx.executeSql("DELETE FROM " + toValidName(container.key) + " WHERE itemkey=?", [itemkey],
                            function () {
                                deleteComplete();
                            },
                            function () {
                                deleteError();
                            });
                    });
                });

            },

            list: function () {
                var container = this;

                var db = openDatabase('survey', '1.0', 'database', 2000000);
                return new WinJS.Promise(function (readComplete, readError) {
                    db.transaction(function (tx) {
                        tx.executeSql('SELECT * FROM ' + toValidName(container.key), [], function (tx, results) {
                            if (results.rows && results.rows.length) {
                                var res = [];
                                for (var i = 0; i < results.rows.length; i++) {
                                    var row = results.rows.item(i);
                                    res.push({ displayName: row.itemkey });
                                }
                                readComplete(res);
                            }
                            else
                                readComplete([]);
                        }, function () { readComplete([]); });
                    });
                });

            },

            child: function (key) {
                if (this[key])
                    return this[key];
                console.log('getting child');
                var res = new WinJSContrib.DataContainer.CordovaDatabaseContainer(key, this.options, this);
                this[key] = res;
                return res;
            }
        })
    });

    function toJSONFileName(fileName) {
        return encodeURIComponent(fileName) + ".json";
    }

    function toValidName(str) {
        //if (str.length > 5) {
        //    str = str.substring(0, 4);
        //}
        str = str.replace(/[^\w\s]/gi, '');
        if (/^\d/.test(str)) {
            str = str.replace(/\s+/g, '');
            str = "mcn" + str;
        }

        return str;
    }
})();


text: export * from './sectionTable.component';


text:
Linear Projection
=================

.. figure:: icons/linear-projection.png

A linear projection method with explorative data analysis.

Signals
-------

**Inputs**:

-  **Data**

Input data set.

-  **Data Subset**

A subset of data instances.

**Outputs**:

-  **Selected Data**

A data subset that user has manually selected in the projection.

Description
-----------

This widget displays `linear
projections <https://en.wikipedia.org/wiki/Projection_(linear_algebra)>`__
of class-labeled data. Consider, for a start, a projection of an *Iris*
data set shown below. Notice that it is sepal width and sepal length
that already separates *Iris setosa* from the other two, while petal
length is the attribute best separating *Iris versicolor* from *Iris
virginica*.

.. figure:: images/linear-projection-stamped.png

1. Axes in the projection that are displayed and other available axes.
2. Set `jittering <https://en.wikipedia.org/wiki/Jitter>`__ to prevent
   the dots from overlapping (especially for discrete attributes).
3. Set color of the dots displayed (you will get colored dots for
   discrete values and grey-scale dots for continuous). Set opacity,
   shape and size to differentiate between instances.
4. *Select*, *zoom*, *pan* and *zoom to fit* options for exploring the
   graph. Manual selection of data instances works as a
   non-angular/free-hand selection tool. Double click to move the
   projection. Scroll in or out for zoom.
5. When the box is ticked (*Auto commit is on*), the widget will
   communicate the changes automatically. Alternatively, click *Commit*.
6. *Save graph* saves the graph to the computer in a .svg or .png
   format.

Example
-------

**Linear Projection** works just like other visualization widgets. Below
we connected it to the :doc:`File<../data/file>` widget to see the set projected on a 2-D
plane. Then we selected the data for further analysis and connected it
to the :doc:`Data Table<../data/datatable>` widget to see the details of the selected subset.

.. figure:: images/LinearProjection-example2.png

References
----------

Koren Y., Carmel L. (2003). Visualization of labeled data using linear
transformations. In Proceedings of IEEE Information Visualization 2003,
(InfoVis'03). Available
`here <http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=3DDF0DB68D8AB9949820A19B0344C1F3?doi=10.1.1.13.8657&rep=rep1&type=pdf>`__.

Boulesteix A.-L., Strimmer K. (2006). Partial least squares: a versatile
tool for the analysis of high-dimensional genomic data. Briefings in
Bioinformatics, 8(1), 32-44. Abstract
`here <http://bib.oxfordjournals.org/content/8/1/32.abstract>`__.


text:
<?php

/**
 * Filter for XHtml header elements, including grouping all following siblings
 * on the same header level in a section.
 *
 * @package Document
 * @version //autogen//
 * @access private
 */
class ezcDocumentXhtmlHeaderElementFilter extends ezcDocumentXhtmlElementBaseFilter
{
    /**
     * Filter a single element
     *
     * @param DOMElement $element
     * @return void
     */
    public function filterElement( DOMElement $element )
    {
        // Create new parent node if we found a header and aggregate everything
        // below the actual header into this node.
        $section = new ezcDocumentPropertyContainerDomElement( 'div' );

        $parent = $element->parentNode;

        // Replace header with new section node
        $parent->replaceChild( $section, $element );
        $section->setProperty( 'type', 'section' );
        $section->setProperty( 'level', $level = $this->getHeaderLevel( $element ) );

        $section->appendChild( $element );
        $element->setProperty( 'type', 'title' );

        // Skip all preceeding child elements, until we reach the current node.
        $children = $parent->childNodes;
        $childCount = $children->length;
        for ( $i = 0; $i < $childCount; ++$i )
        {
            if ( $section->isSameNode( $children->item( $i ) ) )
            {
                break;
            }
        }
        ++$i;

        while ( ( $node = $children->item( $i ) ) !== null )
        {
            if ( ( $node->nodeType === XML_ELEMENT_NODE ) &&
                 ( $node->tagName === 'div' ) &&
                 ( $node->getProperty( 'type' ) === 'section' ) &&
                 ( $node->getProperty( 'level' ) <= $level ) )
            {
                break;
            }
            else
            {
                $new = $node->cloneNode( true );
                $section->appendChild( $new );
                $parent->removeChild( $node );
            }
        }
    }

    /**
     * Get header level
     *
     * Get the header level of a HTML heading. Additionally to the default
     * levels h1-6 we repect a level specified in the class attribute, which is
     * for example used by the RST to XHtml conversion to specify header levels
     * higher then 6.
     *
     * @param DOMElement $element
     * @return int
     */
    protected function getHeaderLevel( DOMElement $element )
    {
        $headerLevel = (int) $element->tagName[1];
        if ( $headerLevel === 6 )
        {
            if ( $element->hasAttribute( 'class' ) &&
                 preg_match( '((?:\s|^)h(?P<level>\d+)(?:\s|$))', $element->getAttribute( 'class' ), $match ) )
            {
                $headerLevel = (int) $match['level'];
            }
        }

        return $headerLevel;
    }

    /**
     * Check if filter handles the current element
     *
     * Returns a boolean value, indicating weather this filter can handle
     * the current element.
     *
     * @param DOMElement $element
     * @return void
     */
    public function handles( DOMElement $element )
    {
        return (bool) preg_match( '(^[hH][1-6]$)', $element->tagName );
    }
}

?>


text:
const pStr=require('pico/str')

return {
    setup(context,cb){ cb() },
    route(req,next){
        switch(req.method){
        case 'POST': return next()
        case 'GET': this.setOutput(this.time)
        default: return next(null, this.sigslot.abort())
        }
    },
	randomStr(key,size,next){
		let str=''
		while(1){
			str+=pStr.rand()
			if (str.length >= size) break
		}
		this.set(key,str.substr(0,size))
		next()
	},
	have(input,fields,next){
		for(let i=0,f; f=fields[i]; i++){
			if (undefined===input[f]) return next(this.error(400))
		}
		next()
	},
    sep(msg,next){console.log(msg); return next()},
    logParams(next){this.log(this.params); return next()},
    delay(period,next){ setTimeout(next,period) },
    help(next){ next(`api ${this.api} is not supported yet`) }
}


text:
var _ = require('highland');
var graph = require('./graph');
var elasticsearch = require('./elasticsearch');
var consolidate = require('./consolidate');

function esParams(query, includeRelated) {
  var prefix = 'related.';
  var params = [];
  Object.keys(query).forEach(function (param) {
    if (param !== 'related') {
      var prefixed = param.indexOf(prefix) === 0;
      if ((includeRelated && prefixed) || (!includeRelated && !prefixed) || param === 'exact') {
        params[param.replace(prefix, '')] = query[param];
      }
    }
  });
  return params;
}

function extractIds(response) {
  return response.map(function (value) {
    return value.id;
  });
}

function related(esParams, relations, direction, callback) {
  // TODO: find better way to stop stream on error
  var error = false;

  _([esParams])
    .nfcall([])
    .series()
    .errors(function (err) { error = true; callback(err); })
    .apply(function (response) {
      if (!error) {
        var ids = extractIds(response);
        graph.related(ids, relations, direction, function (err, ids) {
          if (err) {
            callback(err);
          } else {
            graph.expand(ids, function (err, concepts) { callback(err, concepts); });
          }
        });
      }
    });
}

module.exports = function (query, callback) {
  var error = false;
  var esQueryFrom = elasticsearch.searchQuery(esParams(query, false));
  var esQueryTo = elasticsearch.searchQuery(esParams(query, true));

  // Query types:
  //
  // 1. [q, uri, name, id]:
  //      Elasticsearch -> Expand
  //
  // 2. [q, uri, name, id] && related:
  //      Elasticsearch -> Related -> Expand
  //
  // 3. [q, uri, name, id] && related && [related.q, related.uri, related.name, related.id]:
  //      (Elasticsearch, Elasticsearch) -> Shortest path -> Expand
  //
  // 4.                       related && [related.q, related.uri, related.name, related.id]:
  //      Elasticsearch -> Related -> Expand

  var hasSearchParam = query.q || query.id || query.uri || query.name;
  var hasRelatedParam = query.related;
  var hasRelatedSearchParam = query['related.q'] || query['related.id'] || query['related.uri'] || query['related.name'];

  if (hasSearchParam && hasRelatedParam && hasRelatedSearchParam) {
    _([esQueryFrom, esQueryTo])
      .nfcall([])
      .parallel(2)
      .errors(function (err) { error = true; callback(err); })
      .apply(function (responseFrom, responseTo) {
        var idsFrom = extractIds(responseFrom);
        var idsTo = extractIds(responseTo);

        if (!error) {
          graph.shortestPath(idsFrom, idsTo, query.related, function (err, ids) {
            if (err) {
              callback(err);
            } else {
              graph.expand(ids, function (err, concepts) {
                callback(err, consolidate(concepts));
              });
            }
          });
        }
      });
  } else if (hasSearchParam && hasRelatedParam) {
    related(esQueryFrom, query.related, 'to', callback);
  } else if (hasRelatedParam && hasRelatedSearchParam) {
    related(esQueryTo, query.related, 'from', callback);
  } else if (hasSearchParam) {
    _([esQueryFrom])
      .nfcall([])
      .series()
      .errors(function (err) { error = true; callback(err); })
      .sequence()
      .toArray(function (response) {
        var ids = extractIds(response);
        if (!error) {
          graph.expand(ids, function (err, concepts) {
            callback(err, consolidate(concepts));
          });
        }
      });
  } else {
    callback('Please supply at least one search parameter: `q`, `uri`, `name` or `id`');
  }
};


text:
(function ($){
    "use strict";

    var OlDragNDrop = function ($el,options){
        //vars
        var _ol = this,
            _sor = jQuery().sortable;

        //element
        _ol.$el = $el;
        _ol.options = options;

        //check Drag n drop plugin
        if (!_sor) {
            return;
        }

        //make the magic
        var _sort = $el.sortable(options);

        //bind event when its needed
        if (options.reorder) {
            _sort.bind('sortupdate', $.proxy(_ol.sortItems, _ol));
        }
    };

    OlDragNDrop.prototype.$el = null;
    OlDragNDrop.prototype.options = null;

    OlDragNDrop.prototype.sortItems = function (e,i){
        var _ol = this;

        var $item = $(i.item),
            $list = _ol.$el.closest(_ol.options.reorder.parent).find(_ol.options.reorder.element),
            $targ = $list.find(_ol.options.reorder.items + '[data-id="' + $item.attr('data-id') + '"]'),
            _coun = $list.find(_ol.options.reorder.items).length,
            _indx = $item.index();

        //reorder elements
        if (0 === _indx) {
            $targ.prependTo($list);
        }
        else if ((_coun - 1) == _indx) {
            $targ.appendTo($list);
        }
        else {
            $targ.insertBefore($list.find(_ol.options.reorder.items + ':eq(' + _indx + ')'));
        }

        //fix TinyMCE bug
        $item.click();
    };

    var methods = {
        init: function (options){
            if (!this.length) {
                return false;
            }

            var settings = {
                handle: false,
                items: '.movendrop',
                reorder: false
            };

            return this.each(function (){
                if (options) {
                    $.extend(settings, options);
                }

                new OlDragNDrop($(this), settings);
            });
        },
        update: function (){},
        destroy: function (){}
    };

    $.fn.olDragndrop = function (method){
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
        else {
            $.error('Method '+method+' does not exist on olDragndrop');
            return false;
        }
    };
})(window.jQuery);


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

namespace Microsoft.CodeAnalysis.CodeLens
{
    /// <summary>
    /// Holds information required to display and navigate to individual references
    /// </summary>
    internal sealed class ReferenceLocationDescriptor
    {
        public int LineNumber { get; }

        public int ColumnNumber { get; }

        public DocumentId DocumentId { get; }

        /// <summary>
        /// Language of the reference location
        /// </summary>
        public string Language { get; }

        /// <summary>
        /// Fully qualified name of the symbol containing the reference location
        /// </summary>
        public string LongDescription { get; }

        /// <summary>
        /// The kind of symbol containing the reference location (such as type, method, property, etc.)
        /// </summary>
        public Glyph? Glyph { get; }

        /// <summary>
        /// the full line of source that contained the reference
        /// </summary>
        public string ReferenceLineText { get; }

        /// <summary>
        /// the beginning of the span within reference text that was the use of the reference
        /// </summary>
        public int ReferenceStart { get; }

        /// <summary>
        /// the length of the span of the reference
        /// </summary>
        public int ReferenceLength { get; }

        /// <summary>
        /// Text above the line with the reference
        /// </summary>
        public string BeforeReferenceText1 { get; }

        /// <summary>
        /// Text above the line with the reference
        /// </summary>
        public string BeforeReferenceText2 { get; }

        /// <summary>
        /// Text below the line with the reference
        /// </summary>
        public string AfterReferenceText1 { get; }

        /// <summary>
        /// Text below the line with the reference
        /// </summary>
        public string AfterReferenceText2 { get; }

        public ReferenceLocationDescriptor(string longDescription, string language, Glyph? glyph, Location location, DocumentId documentId, string referenceLineText, int referenceStart, int referenceLength, string beforeReferenceText1, string beforeReferenceText2, string afterReferenceText1, string afterReferenceText2)
        {
            LongDescription = longDescription;
            Language = language;
            Glyph = glyph;
            var sourceText = location.GetLineSpan().StartLinePosition;
            LineNumber = sourceText.Line;
            ColumnNumber = sourceText.Character;
            // We want to keep track of the location's document if it comes from a file in your solution.
            DocumentId = documentId;
            ReferenceLineText = referenceLineText;
            ReferenceStart = referenceStart;
            ReferenceLength = referenceLength;
            BeforeReferenceText1 = beforeReferenceText1;
            BeforeReferenceText2 = beforeReferenceText2;
            AfterReferenceText1 = afterReferenceText1;
            AfterReferenceText2 = afterReferenceText2;
        }
    }
}