text:
require_relative "base"
require_relative "../compose"

module Dip
  module Commands
    module Runners
      class DockerComposeRunner < Base
        def execute
          Commands::Compose.new(
            command[:compose][:method],
            *compose_arguments,
            shell: command[:shell]
          ).execute
        end

        private

        def compose_arguments
          compose_argv = command[:compose][:run_options].dup

          if command[:compose][:method] == "run"
            compose_argv.concat(run_vars)
            compose_argv.concat(published_ports)
            compose_argv << "--rm"
          end

          compose_argv << command.fetch(:service)

          unless (cmd = command[:command]).empty?
            if command[:shell]
              compose_argv << cmd
            else
              compose_argv.concat(cmd.shellsplit)
            end
          end

          compose_argv.concat(command_args)

          compose_argv
        end

        def run_vars
          run_vars = Dip::RunVars.env
          return [] unless run_vars

          run_vars.map { |k, v| ["-e", "#{k}=#{Shellwords.escape(v)}"] }.flatten
        end

        def published_ports
          publish = options[:publish]

          if publish.respond_to?(:each)
            publish.map { |p| "--publish=#{p}" }
          else
            []
          end
        end
      end
    end
  end
end


text:
package com.mosn.asyncmockwebserver.example.domain.model;

import android.os.Parcel;
import android.support.annotation.NonNull;

import com.mosn.asyncmockwebserver.example.domain.core.Entity;
import com.mosn.asyncmockwebserver.example.domain.core.Id;

public class Content extends Entity {

    public String wrapperType;

    public String kind;

    public int artistId;

    public int collectionId;

    public int trackId;

    public String artistName;

    public String collectionName;

    public String trackName;

    public String artworkUrl100;

    public String primaryGenreName;

    protected Content(@NonNull Id id) {
        super(id);
    }

    protected Content(Parcel in) {
        super(in);
        wrapperType = in.readString();
        kind = in.readString();
        artistId = in.readInt();
        collectionId = in.readInt();
        trackId = in.readInt();
        artistName = in.readString();
        collectionName = in.readString();
        trackName = in.readString();
        artworkUrl100 = in.readString();
        primaryGenreName = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        dest.writeString(wrapperType);
        dest.writeString(kind);
        dest.writeInt(artistId);
        dest.writeInt(collectionId);
        dest.writeInt(trackId);
        dest.writeString(artistName);
        dest.writeString(collectionName);
        dest.writeString(trackName);
        dest.writeString(artworkUrl100);
        dest.writeString(primaryGenreName);
    }

    public static Content create(int artistId, int collectionId, int trackId) {
        return new Content(new Id(artistId + "/" + collectionId + "/" + trackId));
    }

    public static final Creator<Content> CREATOR = new Creator<Content>() {
        @Override
        public Content createFromParcel(Parcel in) {
            return new Content(in);
        }

        @Override
        public Content[] newArray(int size) {
            return new Content[size];
        }
    };
}

redpajama_set_name: RedPajamaGithub


text:
namespace NetBinance.MarketDataEndpoints
{
    public class Interval
    {
        private readonly string _value;

        public static readonly Interval OneMinute = new Interval("1m");
        public static readonly Interval ThreeMinutes = new Interval("3m");
        public static readonly Interval FiveMinutes = new Interval("5m");
        public static readonly Interval FifteenMinutes = new Interval("15m");
        public static readonly Interval ThirtyMinutes = new Interval("30m");
        public static readonly Interval OneHour = new Interval("1h");
        public static readonly Interval TwoHours = new Interval("2h");
        public static readonly Interval FourHours = new Interval("4h");
        public static readonly Interval SixHours = new Interval("6h");
        public static readonly Interval EightHours = new Interval("8h");
        public static readonly Interval TwelveHours = new Interval("12h");
        public static readonly Interval OneDay = new Interval("1d");
        public static readonly Interval ThreeDays = new Interval("3d");
        public static readonly Interval OneWeek = new Interval("1w");
        public static readonly Interval OneMonth = new Interval("1M");

        private Interval(string value)
        {
            _value = value;
        }

        public override string ToString()
        {
            return _value;
        }
    }
}


text:
Sample web parts allowing to add sections navigation to the SharePoint page.

![Navigation configuration](./assets/page-nav.gif)

## Compatibility

![SPFx 1.8](https://img.shields.io/badge/SPFx-1.8.0-green.svg)
![Node.js v8](https://img.shields.io/badge/Node.js-v8-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg)
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Local Workbench Compatible](https://img.shields.io/badge/Local%20Workbench-Compatible-green.svg)
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)

## Applies to

* [SharePoint Framework](https://docs.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Office 365 developer tenant](https://docs.microsoft.com/sharepoint/dev/spfx/set-up-your-developer-tenant)

## Solution

Solution|Author(s)
--------|---------
page-sections-navigation|[Alex Terentiev](https://github.com/AJIXuMuK) (MVP, [Sharepointalist Inc.](http://www.sharepointalist.com), [@alexaterentiev](https://twitter.com/alexaterentiev))

## Version history

Version|Date|Comments
-------|----|--------
1.0|February 27, 2019|Initial release
1.1|March 22, 2019| Update to SPFx 1.8, additional theme, comments

## Minimal Path to Awesome

* clone this repo
* move to right folder
* in the command line run:
  * `npm install`
  * `gulp bundle --ship`
  * `gulp package-solution --ship`
* from the _sharepoint/solution_ folder, deploy the .sppkg file to the App catalog in your tenant
* in the site where you want to test this solution
  * add the app named _page-sections-navigation-client-side-solution_
  * edit a page
  * add _Page Sections Navigation_ web part
  * add as much _Page Sections Navigation Anchor_ web parts as you want - each anchor adds an item to the navigation
  * configure web parts

>  This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit https://aka.ms/spfx-devcontainer for further instructions.

## Features

This sample illustrates how to use SharePoint Framework Dynamic Data features to connect web parts on the page.
It also can be used as ready-to-go solution to add page sections navigation to SharePoint pages.

## Custom CSS
The web parts in the sample allow to use custom CSS to override the styles. You can set _Custom CSS URL_ property of *Page Sections Navigation* web part and include css classes for both Navigation and Anchor in referenced file.
Please, refer [custom css sample](./assets/psn-custom.css) for the CSS sample.

## Help

We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for  community members to volunteer their time and help resolve issues.

If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.

You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3A%22sample%3A%20react-page-sections-navigation%22) to see if anybody else is having the same issues.

You can also try looking at [discussions related to this sample](https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=react-page-sections-navigation) and see what the community is saying.

If you encounter any issues while using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-page-sections-navigation&template=bug-report.yml&sample=react-page-sections-navigation&authors=@AJIXuMuK&title=react-page-sections-navigation%20-%20).

For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-page-sections-navigation&template=question.yml&sample=react-page-sections-navigation&authors=@AJIXuMuK&title=react-page-sections-navigation%20-%20).

Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-page-sections-navigation&template=suggestion.yml&sample=react-page-sections-navigation&authors=@AJIXuMuK&title=react-page-sections-navigation%20-%20).

## Disclaimer

**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

<img src="https://pnptelemetry.azurewebsites.net/sp-dev-fx-webparts/samples/react-page-sections-navigation" />


text:
import { IAsyncEnumerable } from "../types"
import { BasicAsyncEnumerable } from "./BasicAsyncEnumerable"

/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */

/**
 * Determine if a type is IAsyncEnumerable
 * @param source Any Value
 * @returns Whether or not source is an Async Enumerable
 */
export const isAsyncEnumerable = (source: any): source is IAsyncEnumerable<any> => {
    if (!source) {
        return false
    }

    if (source instanceof BasicAsyncEnumerable) {
        return true
    }

    if (typeof source[Symbol.asyncIterator] !== "function") {
        return false
    }

    const propertyNames = Object.getOwnPropertyNames(BasicAsyncEnumerable.prototype)
        .filter((v) => v !== "constructor")

    const methods = source.prototype || source
    for (const prop of propertyNames) {
        if (typeof methods[prop] !== "function") {
            return false
        }
    }

    return true
}


text:
class SkBitmap;

namespace suggestions {

// From encoded bytes to SkBitmap.
std::unique_ptr<SkBitmap> DecodeJPEGToSkBitmap(const void* encoded_data,
                                               size_t size);

inline std::unique_ptr<SkBitmap> DecodeJPEGToSkBitmap(
    const std::vector<unsigned char>& encoded_data) {
  return DecodeJPEGToSkBitmap(&encoded_data[0], encoded_data.size());
}

// From SkBitmap to a vector of JPEG-encoded bytes, |dst|.
bool EncodeSkBitmapToJPEG(const SkBitmap& bitmap,
                          std::vector<unsigned char>* dest);

}  // namespace suggestions

#endif  // COMPONENTS_SUGGESTIONS_IMAGE_ENCODER_H_


text:
<?php

namespace Rezzza\RestApiBehatExtension\Tests\Units\Rest;

use atoum;

class WrongResponseExpectation extends atoum
{
    public function test_it_display_pretty_response_when_cast_to_string()
    {
        $this
            ->given(
                $uri = new \mock\Psr\Http\Message\UriInterface,
                $this->calling($uri)->__toString = 'http://test.com/foo',
                $request = new \mock\Psr\Http\Message\RequestInterface,
                $this->calling($request)->getMethod = 'GET',
                $this->calling($request)->getUri = $uri,
                $response = new \mock\Psr\Http\Message\ResponseInterface,
                $this->calling($response)->getStatusCode = 200,
                $this->calling($response)->getReasonPhrase = 'OK',
                $this->calling($response)->getHeaders = ['Content-Type' => 'application/json'],
                $this->calling($response)->getBody = '{"status":"ok"}',
                $this->newTestedInstance('Error', $request, $response)
            )
            ->when(
                $result = $this->testedInstance->__toString()
            )
            ->then
                ->string($result)
                    ->contains(<<<EOF
|  GET http://test.com/foo :
|  200 OK
|  Content-Type: application/json
|
|  {"status":"ok"}
EOF
                    )
        ;
    }
}


text:
package org.auraframework.util.type.converter;

import org.auraframework.annotations.Annotations.ServiceComponent;
import org.auraframework.util.type.Converter;
import org.springframework.context.annotation.Lazy;

import java.math.BigDecimal;

/**
 * Used by aura.util.type.TypeUtil
 */
@Lazy
@ServiceComponent
public class StringToBigDecimalConverter implements Converter<String, BigDecimal> {

    @Override
    public BigDecimal convert(String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }

        try {
            return new BigDecimal(value);
        }
        catch (NumberFormatException ex) {
            // fail gracefully, we don't want to bubble an exception here
            return null;
        }
    }

    @Override
    public Class<String> getFrom() {
        return String.class;
    }

    @Override
    public Class<BigDecimal> getTo() {
        return BigDecimal.class;
    }

    @Override
    public Class<?>[] getToParameters() {
        return null;
    }

}


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = mongoose.model('Restaurant', new Schema({
// For using multiple Oauth platforms would create nested attributes of each Oauth domain
// ex. user.google.username ; user.facebook.username ; ect.
  name: { type: String, required: true, unique: true },
  phone: { type: String, required: true, unique: true },
  rating: { type: String, required: true },
  snippetText: { type: String, required: true },
  imageUrl: { type: String, required: true },

}));


text:
package squidpony.squidai;

import squidpony.squidgrid.Radius;
import squidpony.squidmath.Coord;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * An AOE type that has a center Coord only and only affects that single Coord. Useful if you need an AOE implementation
 * for something that does not actually affect an area.
 * This will produce doubles for its findArea() method which are equal to 1.0.
 *
 * This class doesn't use any other SquidLib class to create its area of effect.
 * Created by Tommy Ettinger on 7/13/2015.
 */
public class PointAOE implements AOE {
    private Coord center, origin = null;
    private Radius limitType = null;
    private int minRange = 1, maxRange = 1;
    private Radius metric = Radius.SQUARE;
    public PointAOE(Coord center)
    {
        this.center = center;
    }
    public PointAOE(Coord center, int minRange, int maxRange)
    {
        this.center = center;
        this.minRange = minRange;
        this.maxRange = maxRange;
    }

    public Coord getCenter() {
        return center;
    }

    public void setCenter(Coord center) {
        if(AreaUtils.verifyLimit(limitType, origin, center))
        {
            this.center = center;
        }
    }
    @Override
    public void shift(Coord aim) {
        setCenter(aim);
    }

    @Override
    public boolean mayContainTarget(Set<Coord> targets) {
        for (Coord p : targets)
        {
            if(center.x == p.x && center.y == p.y)
                return true;
        }
        return false;
    }

    @Override
    public LinkedHashMap<Coord, ArrayList<Coord>> idealLocations(Set<Coord> targets, Set<Coord> requiredExclusions) {
        if(targets == null)
            return new LinkedHashMap<Coord, ArrayList<Coord>>();

        int totalTargets = targets.size();
        LinkedHashMap<Coord, ArrayList<Coord>> bestPoints = new LinkedHashMap<Coord, ArrayList<Coord>>(totalTargets);

        if(totalTargets == 0)
            return bestPoints;

        double dist = 0.0;
        for(Coord p : targets) {
            if (AreaUtils.verifyLimit(limitType, origin, p)) {

                dist = metric.radius(origin.x, origin.y, p.x, p.y);
                if (dist <= maxRange && dist >= minRange) {
                    ArrayList<Coord> ap = new ArrayList<Coord>();
                    ap.add(p);
                    bestPoints.put(p, ap);
                }
            }
        }
        return bestPoints;
    }

    @Override
    public LinkedHashMap<Coord, ArrayList<Coord>> idealLocations(Set<Coord> priorityTargets, Set<Coord> lesserTargets, Set<Coord> requiredExclusions) {
        if(priorityTargets == null)
            return idealLocations(lesserTargets, requiredExclusions);
        if(requiredExclusions == null) requiredExclusions = new LinkedHashSet<Coord>();

        int totalTargets = priorityTargets.size() + lesserTargets.size();
        LinkedHashMap<Coord, ArrayList<Coord>> bestPoints = new LinkedHashMap<Coord, ArrayList<Coord>>(totalTargets * 4);

        if(totalTargets == 0)
            return bestPoints;

        double dist = 0.0;

        for(Coord p : priorityTargets) {
            if (AreaUtils.verifyLimit(limitType, origin, p)) {

                dist = metric.radius(origin.x, origin.y, p.x, p.y);
                if (dist <= maxRange && dist >= minRange) {
                    ArrayList<Coord> ap = new ArrayList<Coord>();
                    ap.add(p);
                    ap.add(p);
                    ap.add(p);
                    ap.add(p);
                    bestPoints.put(p, ap);
                }
            }
        }
        if(bestPoints.isEmpty()) {
            for (Coord p : lesserTargets) {
                if (AreaUtils.verifyLimit(limitType, origin, p)) {

                    dist = metric.radius(origin.x, origin.y, p.x, p.y);
                    if (dist <= maxRange && dist >= minRange) {
                        ArrayList<Coord> ap = new ArrayList<Coord>();
                        ap.add(p);
                        bestPoints.put(p, ap);
                    }
                }
            }
        }
        return bestPoints;

    }

    /*
    @Override
    public ArrayList<ArrayList<Coord>> idealLocations(Set<Coord> targets, Set<Coord> requiredExclusions) {
        int totalTargets = targets.size() + 1;
        int maxEffect = (int)radiusType.volume2D(radius);
        ArrayList<ArrayList<Coord>> locs = new ArrayList<ArrayList<Coord>>(totalTargets);

        for(int i = 0; i < totalTargets; i++)
        {
            locs.add(new ArrayList<Coord>(maxEffect));
        }
        if(totalTargets == 1)
            return locs;

        int ctr = 0;
        if(radius < 1)
        {
            locs.get(totalTargets - 2).addAll(targets);
            return locs;
        }

        boolean[][] tested = new boolean[dungeon.length][dungeon[0].length];
        for (int x = 1; x < dungeon.length - 1; x += radius) {
            BY_POINT:
            for (int y = 1; y < dungeon[x].length - 1; y += radius) {
                for(Coord ex : requiredExclusions)
                {
                    if(radiusType.radius(x, y, ex.x, ex.y) <= radius)
                        continue BY_POINT;
                }
                ctr = 0;
                for(Coord tgt : targets)
                {
                    if(radiusType.radius(x, y, tgt.x, tgt.y) <= radius)
                        ctr++;
                }
                if(ctr > 0)
                    locs.get(totalTargets - ctr).add(Coord.get(x, y));
            }
        }
        Coord it;
        for(int t = 0; t < totalTargets - 1; t++)
        {
            if(locs.get(t).size() > 0) {
                int numPoints = locs.get(t).size();
                for (int i = 0; i < numPoints; i++) {
                    it = locs.get(t).get(i);
                    for (int x = Math.max(1, it.x - radius / 2); x < it.x + (radius + 1) / 2 && x < dungeon.length - 1; x++) {
                        BY_POINT:
                        for (int y = Math.max(1, it.y - radius / 2); y <= it.y + (radius - 1) / 2 && y < dungeon[0].length - 1; y++)
                        {
                            if(tested[x][y])
                                continue;
                            tested[x][y] = true;

                            for(Coord ex : requiredExclusions)
                            {
                                if(radiusType.radius(x, y, ex.x, ex.y) <= radius)
                                    continue BY_POINT;
                            }

                            ctr = 0;
                            for(Coord tgt : targets)
                            {
                                if(radiusType.radius(x, y, tgt.x, tgt.y) <= radius)
                                    ctr++;
                            }
                            if(ctr > 0)
                                locs.get(totalTargets - ctr).add(Coord.get(x, y));
                        }
                    }
                }
            }
        }
        return locs;
    }
*/
    @Override
    public void setMap(char[][] map) {
		/*
		 * Nothing do do. smelc's note: previously 'map' was assigned in a field
		 * that was never redd.
		 */
    }

    @Override
    public LinkedHashMap<Coord, Double> findArea() {
        LinkedHashMap<Coord, Double> ret = new LinkedHashMap<Coord, Double>(1);
        ret.put(Coord.get(center.x, center.y), 1.0);
        return ret;
    }

    @Override
    public Coord getOrigin() {
        return origin;
    }

    @Override
    public void setOrigin(Coord origin) {
        this.origin = origin;

    }

    @Override
    public Radius getLimitType() {
        return limitType;
    }

    @Override
    public int getMinRange() {
        return minRange;
    }

    @Override
    public int getMaxRange() {
        return maxRange;
    }

    @Override
    public Radius getMetric() {
        return metric;
    }

    @Override
    public void setLimitType(Radius limitType) {
        this.limitType = limitType;

    }

    @Override
    public void setMinRange(int minRange) {
        this.minRange = minRange;
    }

    @Override
    public void setMaxRange(int maxRange) {
        this.maxRange = maxRange;

    }

    @Override
    public void setMetric(Radius metric) {
        this.metric = metric;
    }

}


text:
using System.ComponentModel.DataAnnotations;

namespace SoftUni.App.Chushka.BindingModels
{
    public class LoginModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        public string Password { get; set; }
    }
}


text:
<?php
// src/AppBundle/Entity/User.php

namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Proxy_controller extends Base_Controller {

    public function __construct() {

        if (isset($_GET['dl']) && $_GET['dl'] != '') {
            $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
        }

        parent::__construct();
    }

    public function index() {

        $i = (string) $this->uri->rsegment(3);

        if (!ctype_digit($i)) {

            set_status_header(404);
            $this->output->set_output('Not found.');

            return;
        }

        $i = (int) $i;

        $this->load->config('logs');
        $items = $this->config->item('logs');

        $item = !empty($items) && is_array($items) && isset($items[$i]) ? $items[$i] : null;

        if (empty($item) || !isset($item['url'])) {

            set_status_header(404);
            $this->output->set_output('Not found.');

            return;
        }

        $base_url = $this->_add_slash($item['url']);

        // If we are viewing the log of the current application,
        // then we are going to skip the proxy and to return
        // the corresponding response directly.

        if ($base_url == $this->_add_slash(default_base_url('admin'))) {

            Modules::run('logs/index');

            return;
        }

        // Use a proxy server to read the logs of the other applications.

        @ob_end_clean();
        @ob_end_flush();

        $url = $base_url.'logs';

        $request = \Proxy\Http\Request::createFromGlobals();
        $proxy = new \Proxy\Proxy();

        $response = $proxy->forward($request, $url);

        $response->send();

        exit;
    }

    protected function _add_slash($string) {

        $string = (string) $string;

        if ($string != '') {
            $string = rtrim($string, '/').'/';
        }

        return $string;
    }

}


text:
#region Using directives

using System;
using System.Management.Automation;
using System.Globalization;

#endregion

namespace Microsoft.Management.Infrastructure.CimCmdlets
{
    #region AsyncResultType
    /// <summary>
    /// <para>
    /// Async result type
    /// </para>
    /// </summary>
    public enum AsyncResultType
    {
        Result,
        Exception,
        Completion
    }
    #endregion

    #region CimResultContext
    /// <summary>
    /// Cim Result Context
    /// </summary>
    internal class CimResultContext
    {
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="ErrorSource"></param>
        internal CimResultContext(object ErrorSource)
        {
            this.errorSource = ErrorSource;
        }

        /// <summary>
        /// ErrorSource property
        /// </summary>
        internal object ErrorSource
        {
            get
            {
                return this.errorSource;
            }
        }
        private object errorSource;
    }
    #endregion

    #region AsyncResultEventArgsBase
    /// <summary>
    /// <para>
    /// Base class of async result event argument
    /// </para>
    /// </summary>
    internal abstract class AsyncResultEventArgsBase : EventArgs
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        /// <param name="resultType"></param>
        public AsyncResultEventArgsBase(
            CimSession session,
            IObservable<object> observable,
            AsyncResultType resultType)
        {
            this.session = session;
            this.observable = observable;
            this.resultType = resultType;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        /// <param name="resultType"></param>
        /// <param name="context"></param>
        public AsyncResultEventArgsBase(
            CimSession session,
            IObservable<object> observable,
            AsyncResultType resultType,
            CimResultContext cimResultContext)
        {
            this.session = session;
            this.observable = observable;
            this.resultType = resultType;
            this.context = cimResultContext;
        }

        public readonly CimSession session;
        public readonly IObservable<object> observable;
        public readonly AsyncResultType resultType;

        // property ErrorSource
        public readonly CimResultContext context;
    }

    #endregion

    #region AsyncResult*Args
    /// <summary>
    /// <para>
    /// operation successfully completed event argument
    /// </para>
    /// </summary>
    internal class AsyncResultCompleteEventArgs : AsyncResultEventArgsBase
    {
        /// <summary>
        /// <para>
        /// Constructor
        /// </para>
        /// </summary>
        /// <param name="session"><see cref="CimSession"/> object</param>
        /// <param name="cancellationDisposable"></param>
        public AsyncResultCompleteEventArgs(
            CimSession session,
            IObservable<object> observable) :
            base(session, observable, AsyncResultType.Completion)
        {
        }
    }

    /// <summary>
    /// <para>
    /// async result argument with object
    /// </para>
    /// </summary>
    internal class AsyncResultObjectEventArgs : AsyncResultEventArgsBase
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        /// <param name="resultObject"></param>
        public AsyncResultObjectEventArgs(
            CimSession session,
            IObservable<object> observable,
            object resultObject) :
            base(session, observable, AsyncResultType.Result)
        {
            this.resultObject = resultObject;
        }

        public readonly object resultObject;
    }

    /// <summary>
    /// <para>
    /// operation completed with exception event argument
    /// </para>
    /// </summary>
    internal class AsyncResultErrorEventArgs : AsyncResultEventArgsBase
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        /// <param name="error"></param>
        public AsyncResultErrorEventArgs(
            CimSession session,
            IObservable<object> observable,
            Exception error) :
            base(session, observable, AsyncResultType.Exception)
        {
            this.error = error;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        /// <param name="error"></param>
        /// <param name="context"></param>
        public AsyncResultErrorEventArgs(
            CimSession session,
            IObservable<object> observable,
            Exception error,
            CimResultContext cimResultContext) :
            base(session, observable, AsyncResultType.Exception, cimResultContext)
        {
            this.error = error;
        }

        public readonly Exception error;
    }
    #endregion

    #region CimResultObserver
    /// <summary>
    /// <para>
    /// Observer to consume results from asynchronous operations, such as,
    /// EnumerateInstancesAsync operation of <see cref="CimSession"/> object.
    /// </para>
    /// <para>
    /// (See http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Contract/)
    /// for the IObserver/IObservable contact
    /// - the only possible sequence is OnNext* (OnCompleted|OnError)?
    /// - callbacks are serialized
    /// - Subscribe never throws
    /// </para>
    /// </summary>
    /// <typeparam name="T">object type</typeparam>
    internal class CimResultObserver<T> : IObserver<T>
    {
        /// <summary>
        /// Define delegate that handles new cmdlet action come from
        /// the operations related to the current CimSession object.
        /// </summary>
        /// <param name="cimSession">cimSession object, which raised the event</param>
        /// <param name="actionArgs">Event args</param>
        public delegate void ResultEventHandler(
            object observer,
            AsyncResultEventArgsBase resultArgs);

        /// <summary>
        /// Define an Event based on the NewActionHandler
        /// </summary>
        public event ResultEventHandler OnNewResult;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="session"><see cref="CimSession"/> object that issued the operation</param>
        /// <param name="observable">Operation that can be observed</param>
        public CimResultObserver(CimSession session, IObservable<object> observable)
        {
            this.session = session;
            this.observable = observable;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="session"><see cref="CimSession"/> object that issued the operation</param>
        /// <param name="observable">Operation that can be observed</param>
        public CimResultObserver(CimSession session,
            IObservable<object> observable,
            CimResultContext cimResultContext)
        {
            this.session = session;
            this.observable = observable;
            this.context = cimResultContext;
        }

        /// <summary>
        /// <para>
        /// Operation completed successfully
        /// </para>
        /// </summary>
        public virtual void OnCompleted()
        {
            // callbacks should never throw any exception to
            // protocol layer, otherwise the client process will be
            // terminated because of unhandled exception, same with
            // OnNext, OnError
            try
            {
                AsyncResultCompleteEventArgs completeArgs = new AsyncResultCompleteEventArgs(
                    this.session, this.observable);
                this.OnNewResult(this, completeArgs);
            }
            catch (Exception ex)
            {
                this.OnError(ex);
                DebugHelper.WriteLogEx("{0}", 0, ex);
            }
        }

        /// <summary>
        /// <para>
        /// Operation completed with an error
        /// </para>
        /// </summary>
        /// <param name="error">error object</param>
        public virtual void OnError(Exception error)
        {
            try
            {
                AsyncResultErrorEventArgs errorArgs = new AsyncResultErrorEventArgs(
                    this.session, this.observable, error, this.context);
                this.OnNewResult(this, errorArgs);
            }
            catch (Exception ex)
            {
                // !!ignore the exception
                DebugHelper.WriteLogEx("{0}", 0, ex);
            }
        }

        /// <summary>
        /// Deliver the result value
        /// </summary>
        /// <param name="value"></param>
        protected void OnNextCore(object value)
        {
            DebugHelper.WriteLogEx("value = {0}.", 1, value);
            try
            {
                AsyncResultObjectEventArgs resultArgs = new AsyncResultObjectEventArgs(
                    this.session, this.observable, value);
                this.OnNewResult(this, resultArgs);
            }
            catch (Exception ex)
            {
                this.OnError(ex);
                DebugHelper.WriteLogEx("{0}", 0, ex);
            }
        }

        /// <summary>
        /// <para>
        /// Operation got a new result object
        /// </para>
        /// </summary>
        /// <param name="value">result object</param>
        public virtual void OnNext(T value)
        {
            DebugHelper.WriteLogEx("value = {0}.", 1, value);
            // do not allow null value
            if (value == null)
            {
                return;
            }
            this.OnNextCore(value);
        }

        #region members

        /// <summary>
        /// Session object of the operation
        /// </summary>
        protected CimSession CurrentSession
        {
            get
            {
                return session;
            }
        }
        private CimSession session;

        /// <summary>
        /// async operation that can be observed
        /// </summary>
        private IObservable<object> observable;

        /// <summary>
        /// <see cref="CimResultContext"/> object used during delivering result.
        /// </summary>
        private CimResultContext context;
        #endregion
    }

    /// <summary>
    /// CimSubscriptionResultObserver class definition
    /// </summary>
    internal class CimSubscriptionResultObserver : CimResultObserver<CimSubscriptionResult>
    {
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        public CimSubscriptionResultObserver(CimSession session, IObservable<object> observable)
            : base(session, observable)
        {
        }

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        public CimSubscriptionResultObserver(
            CimSession session,
            IObservable<object> observable,
            CimResultContext context)
            : base(session, observable, context)
        {
        }

        /// <summary>
        /// Override the OnNext method
        /// </summary>
        /// <param name="value"></param>
        public override void OnNext(CimSubscriptionResult value)
        {
            DebugHelper.WriteLogEx();
            base.OnNextCore(value);
        }
    }

    /// <summary>
    /// CimMethodResultObserver class definition
    /// </summary>
    internal class CimMethodResultObserver : CimResultObserver<CimMethodResultBase>
    {
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        public CimMethodResultObserver(CimSession session, IObservable<object> observable)
            : base(session, observable)
        {
        }

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        /// <param name="context"></param>
        public CimMethodResultObserver(
            CimSession session,
            IObservable<object> observable,
            CimResultContext context)
            : base(session, observable, context)
        {
        }

        /// <summary>
        /// Override the OnNext method
        /// </summary>
        /// <param name="value"></param>
        public override void OnNext(CimMethodResultBase value)
        {
            DebugHelper.WriteLogEx();
            const string PSTypeCimMethodResult = @"Microsoft.Management.Infrastructure.CimMethodResult";
            const string PSTypeCimMethodStreamedResult = @"Microsoft.Management.Infrastructure.CimMethodStreamedResult";
            const string PSTypeCimMethodResultTemplate = @"{0}#{1}#{2}";

            string resultObjectPSType = null;
            PSObject resultObject = null;
            CimMethodResult methodResult = value as CimMethodResult;
            if (methodResult != null)
            {
                resultObjectPSType = PSTypeCimMethodResult;
                resultObject = new PSObject();
                foreach (CimMethodParameter param in methodResult.OutParameters)
                {
                    resultObject.Properties.Add(new PSNoteProperty(param.Name, param.Value));
                }
            }
            else
            {
                CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult;
                if (methodStreamedResult != null)
                {
                    resultObjectPSType = PSTypeCimMethodStreamedResult;
                    resultObject = new PSObject();
                    resultObject.Properties.Add(new PSNoteProperty(@"ParameterName", methodStreamedResult.ParameterName));
                    resultObject.Properties.Add(new PSNoteProperty(@"ItemType", methodStreamedResult.ItemType));
                    resultObject.Properties.Add(new PSNoteProperty(@"ItemValue", methodStreamedResult.ItemValue));
                }
            }
            if (resultObject != null)
            {
                resultObject.Properties.Add(new PSNoteProperty(@"PSComputerName", this.CurrentSession.ComputerName));
                resultObject.TypeNames.Insert(0, resultObjectPSType);
                resultObject.TypeNames.Insert(0, String.Format(CultureInfo.InvariantCulture, PSTypeCimMethodResultTemplate, resultObjectPSType, ClassName, MethodName));
                base.OnNextCore(resultObject);
            }
        }

        /// <summary>
        /// methodname
        /// </summary>
        internal String MethodName
        {
            get;
            set;
        }

        /// <summary>
        /// classname
        /// </summary>
        internal String ClassName
        {
            get;
            set;
        }
    }

    /// <summary>
    /// IgnoreResultObserver class definition
    /// </summary>
    internal class IgnoreResultObserver : CimResultObserver<CimInstance>
    {
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="session"></param>
        /// <param name="observable"></param>
        public IgnoreResultObserver(CimSession session, IObservable<object> observable)
            : base(session, observable)
        {
        }

        /// <summary>
        /// Override the OnNext method
        /// </summary>
        /// <param name="value"></param>
        public override void OnNext(CimInstance value)
        {
            DebugHelper.WriteLogEx();
        }
    }
    #endregion
}


text:
layout: post
title: "Azure Tips and Tricks Part 14 - Generate SSH public key to log into Linux VM with Cloud Shell"
excerpt: "Learn how to generate SSH keys to log into a Linux VM with Cloud Shell and BASH on Windows 10"
tags: [azure, windows, portal, cloud, developers, tipsandtricks]
share: true
comments: true
---

## Intro

Most folks aren't aware of how powerful the [Azure](http://www.azure.com) platform really is. As I've been presenting topics on Azure, I've had many people say, "How did you do that?" So I'll be documenting my tips and tricks for Azure in these posts.

## The Complete List

[Click here to view the complete list of Azure Tips and Tricks ](https://michaelcrump.net/azure-tips-and-tricks-complete-list/)

## Generate SSH keys to log into Linux VM with Cloud Shell

We will take what we just learned about [Azure Cloud Shell and Storage accounts](https://michaelcrump.net/azure-tips-and-tricks13/) to connect to create and store a SSH key pair that we'll use to automatically log into a Linux VM. In my case, we'll work with a Ubuntu 16.0.4 LTS VM that I originally setup a password for. Instead of typing in a password every time that I wish to connect, I'd prefer to use Cloud Shell storage to generate a public key that I can use to automatically log into the Linux VM without ever typing a password again.

For these instructions, I'll assume you have a Linux VM already setup and connecting via Cloud Shell.

1.) Log into Azure Cloud Shell and type `ssh-keygen -t rsa -b 2048`. Accept all default by pressing enter. It has generated a public key that is stored in `/home/michael/.ssh/id_rsa.pub.` as shown below.

```
michael@Azure:~/clouddrive$ ssh-keygen -t rsa -b 2048
Generating public/private rsa key pair.
Enter file in which to save the key (/home/michael/.ssh/id_rsa):
Created directory '/home/michael/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/michael/.ssh/id_rsa.
Your public key has been saved in /home/michael/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:FHZVjZfU0zZaXoEvbg37/YUW+02VMIXl6UtUIumpHs0 michael@cc-72f9-63c154d-32136390-qk3bs
The key's randomart image is:
+---[RSA 2048]----+
|        o ..ooBB*|
|       . o  .++*X|
|        .  . +=*+|
|       .    o+=o.|
|        S  +. *+.|
|          o E+.=o|
|         . .. =.+|
|          .  . ++|
|                =|
+----[SHA256]-----+
michael@Azure:~/clouddrive$

```

2.) Ensure the key was generated by typing `ls -a`.

```
michael@Azure:~$ ls -a
.  ..  .azure  .bash_history  .bash_logout  .bashrc  clouddrive  .profile  .ssh

```

3.) Looks good (we see `.ssh`), we'll go ahead and copy it to our server with `scp ~/.ssh/id_rsa.pub user@ipaddy:`

```
michael@Azure:~$ scp ~/.ssh/id_rsa.pub user@ipaddy:
mbcrump@52.161.31.243's password:
id_rsa.pub                                                                                100%  420     0.4KB/s   00:00
```

4.) SSH to the Linux server with `ssh user@ipaddy`.

5.) Append the public key to authorized_keys `cat id_rsa.pub >> ~/.ssh/authorized_keys` and then remove the file with `rm id_rsa.pub`.

6.) Edit the ssh server configuration file with `sudo nano /etc/ssh/sshd_config`.

6.1) These entries must be set to yes and they should already be that way by default:
	RSAAuthentication yes
	PubkeyAuthentication yes

7.) Reload the configuration with `sudo service ssh reload`.

8.) Disconnect and try to connect without the need to give the password to the ssh-client `ssh user@ipaddy`.

9.) If everything goes as planned, you should see:

```
michael@Azure:~$ ssh user@ipaddy
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-92-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

15 packages can be updated.
0 updates are security updates.

*** System restart required ***
Last login: Sun Sep 10 23:49:35 2017 from 40.83.147.69
```

## BONUS: If you want to disable the password you previously set on the Linux machine

If you want to disable the password on the Linux machine that you previously set:

1.) SSH back into the machine with `ssh user@ipaddy`.

2.) Disable password authentication with `sudo nano /etc/ssh/sshd_config`.

2.1) Ensure the following settings should are set to no:

	ChallengeResponseAuthentication no
	PasswordAuthentication no
	UsePAM no

2.2.) Reload the configuration with `sudo service ssh reload`

3.) You can see if the password authentication is disabled by logging out and then trying to connect with key file authentication disabled with `ssh user@ipaddress -o PubkeyAuthentication=no`. You should get "Permission denied".

## BONUS #2: You can easily do the same with BASH on Windows 10

You can have the same goodness that you have with Azure Cloud Shell on your local machine. In my case, I'm using BASH on Windows and can just run steps 1-5 listed above. Boom!

## Want more Azure Tips and Tricks?

If you'd like to learn more Azure Tips and Tricks, then follow me on [twitter](http://twitter.com/mbcrump) or stay tuned to this blog! I'd also love to hear your tips and tricks for working in Azure, just leave a comment below.


text:
var handlebars = require('handlebars');
var labjack = require('labjack-nodejs');
var q = require('q');

var framework_standalone_ui = require('./framework_standalone_ui');
var fs_facade = require('./fs_facade');
var presenter_framework = require('./presenter_framework');

var JS_LOC_TEMPLATE = handlebars.compile('/{{ . }}/controller');

/**
 * Fire an event listener and resolve a given deferred after it returns.
 *
 * @param {String} event The name of the event to fire.
 * @param {Object} environment Environment information object. The framework for
 *      this environment will be passed to the event listener.
 * @param {q.defer} deferred Deferred to resolve after the event listeners
 *      finish or to reject if the event listeners encounter an error.
**/
function fireAndResolve (event, environment, deferred) {
    environment.framework.fire(event, environment.framework).then(
        function () { deferred.resolve(environment); },
        deferred.reject
    );
}

/**
 * Add a presenter framework to the given environment.
 *
 * @param {Object} environment The environemnt to add the framework to
 * @return {q.promise} Promise that resolves after the framework has been added
 *      to the presenter. Resolves to the environment.
**/
function prepareFramework (environment) {
    var deferred = q.defer();
    environment.framework = new presenter_framework.Framework();
    deferred.resolve(environment);
    return deferred.promise;
}

/**
 * Add information about the selected module to the environemtn.
 *
 * @param {Object} environment The environment information object to add the
 *      module information to.
 * @return {q.promise} Promise that resolves after the module information has
 *      been added to the environment.
**/
function loadModuleInfo (environment) {
    var deferred = q.defer();

    fs_facade.getModuleInfo(
        environment.moduleName,
        deferred.reject,
        function (info) {
            environment.moduleInfo = info;
            deferred.resolve(environment);
        }
    );

    return deferred.promise;
}

/**
 * Load the controller for a module.
 *
 * @param {Object} environment The environment information object to add the
 *      loaded module controller to.
 * @return {q.promise} Promise that resolves to the modified environment after
 *      the controller has been loaded.
**/
function loadModuleLogic (environment) {
    var deferred = q.defer();

    var moduleName = environment.moduleInfo['name'];
    var controllerLocalLoc = JS_LOC_TEMPLATE(moduleName);
    var controllerGlobalLoc = fs_facade.getExternalURI(controllerLocalLoc)
    var controller = require(controllerGlobalLoc);

    environment.module = controller;
    deferred.resolve(environment);

    return deferred.promise;
}

/**
 * Examine the module controller for standard event callbacks.
 *
 * Examine the loaded module's exports for standard event callbacks namely:
 *  - moduleLoad
 *  - loadTemplate
 *  - deviceSelection
 *  - configureDevice
 *  - deviceConfigured
 *  - refresh
 *  - closeDevice
 *  - unloadModule
 *  - loadError
 *  - configError
 *  - refreshError
 *
 * @param {Object} environment The environment infromation object with the
 *      module controller to examine.
 * @return {q.promise} Promise that resolves after the target module controller
 *      has been examined. Resolves to the environment.
**/
function loadModuleCallbacks (environment) {
    var deferred = q.defer();
    var module = environment.module;
    var onModuleLoad = module.moduleLoad;
    var onLoadTemplate = module.loadTemplate;
    var onDeviceSelection = module.deviceSelection;
    var onConfigureDevice = module.configureDevice;
    var onDeviceConfigured = module.deviceConfigured;
    var onRefresh = module.refresh;
    var onCloseDevice = module.closeDevice;
    var onUnloadModule = module.unloadModule;
    var onLoadError = module.loadError;
    var onConfigError = module.configError;
    var onRefreshError = module.refreshError;

    if (onModuleLoad) {
        environment.framework.on('moduleLoad', onModuleLoad);
    }

    if (onLoadTemplate) {
        environment.framework.on('loadTemplate', onLoadTemplate);
    }

    if (onDeviceSelection) {
        environment.framework.on('deviceSelection', onDeviceSelection);
    }

    if (onConfigureDevice) {
        environment.framework.on('configureDevice', onConfigureDevice);
    }

    if (onDeviceConfigured) {
        environment.framework.on('deviceConfigured', onDeviceConfigured);
    }

    if (onRefresh) {
        environment.framework.on('refresh', onRefresh);
    }

    if (onCloseDevice) {
        environment.framework.on('closeDevice', onCloseDevice);
    }

    if (onUnloadModule) {
        environment.framework.on('unloadModule', onUnloadModule);
    }

    if (onLoadError) {
        environment.framework.on('loadError', onLoadError);
    }

    if (onConfigError) {
        environment.framework.on('configError', onConfigError);
    }

    if (onRefreshError) {
        environment.framework.on('refreshError', onRefreshError);
    }

    fireAndResolve('onModuleLoad', environment, deferred);
    return deferred.promise;
}

/**
 * Open the first found device.
 *
 * @param {Object} environment The standalone framework environment information
 *      object to save the device to.
 * @return {q.promise} Promise that resolves after the device is open and
 *      rejects if the device cannot be opened.
**/
function loadDevice (environment) {
    var deferred = q.defer();

    var newDevice = labjack.device();
    newDevice.open(
        deferred.reject,
        function (newDevice) {
            environment.device = newDevice;
            fireAndResolve('onDeviceSelection', environment, deferred);
        }
    );

    return deferred.promise;
}

/**
 * Creates the standalone command line interface.
 *
 * @param {Object} environment The environment infromation object that the UI
 *      should be attached to.
 * @return {q.promise} Promise that resolves after the target module controller
 *      has been examined. Resolves to the environment.
**/
function createInterface (environment) {
    var deferred = q.defer();
    var newInterface = new framework_standalone_ui.CLInterface(environment);
    environment.cli = newInterface;

    var interfaceCreatePromise = newInterface.create();
    interfaceCreatePromise.then(
        deferred.reject,
        function () { fireAndResolve('onLoadTemplate', environment, deferred); }
    );

    return deferred.promise;
}

/**
 * Starts the refresh loop for the framework.
 *
 * @param {Object} environment The environment with the framework to start the
 *      refresh loop for.
 * @return {q.promise} Promise that resolves after the framework loop has
 *      started.
**/
function startFrameworkLoop (environment) {
    var deferred = q.defer();
    environment.framework.startLoop();
    return deferred.promise;
}

/**
 * Callback that should be called by the UI when the user exits the app.
 *
 * Callback that should be called by the UI when the user exists the stand alone
 * framework run utility.
 *
 * @param {Object} environment The environment that is being closed.
 * @return {q.promise} Promise that resolvse after the on exit logic has
 *      finished running.
**/
function onUserExit (environment) {
    var deferred = q.defer;

    var alertDeviceClosing = function () {
        var innerDeferred = q.defer();

        environment.framework.fire(
            'onCloseDevice',
            environment.framework,
            innerDeferred.reject,
            innerDeferred.resolve
        );

        return innerDeferred.promise;
    };

    var stopFrameworkLoop = function () {
        var innerDeferred = q.defer();
        environment.framework.stopLoop();
        innerDeferred.resolve();
        return innerDeferred.promise;
    };

    var alertUnload = function () {
        var innerDeferred = q.defer();

        environment.framework.fire(
            'onCloseDevice',
            environment.framework,
            innerDeferred.reject,
            innerDeferred.resolve
        );

        return innerDeferred.promise;
    };

    alertDeviceClosing()
    .then(alertUnload, deferred.reject)
    .then(deferred.resolve, deferred.reject);

    return deferred.promise;
}

exports.fireAndResolve = fireAndResolve;
exports.prepareFramework = prepareFramework;
exports.loadModuleInfo = loadModuleInfo;
exports.loadModuleLogic = loadModuleLogic;
exports.loadModuleCallbacks = loadModuleCallbacks;
exports.loadDevice = loadDevice;
exports.createInterface = createInterface;
exports.startFrameworkLoop = startFrameworkLoop;
exports.onUserExit = onUserExit;


text:
*technology*: **Python** with **Keras** (using **Theanos** as backend)

## Team members
* **SW3/2013** Stefan Ristanović
* **SW8/2013** Stefan Bratić

## Project goal
An application that predicts probability of characters death in popular book/TV show franchise Game of Thrones.

## Project specifics
...

## Data Sources
* *battles.csv*, *characters-deaths.csv* and *characters-predictions.csv* are retrieved from **Kaggle dataset post** (https://www.kaggle.com/mylesoneill/game-of-thrones)
* *houses.json*, *cultures.json* and *characters.json* are retrieved from **GOT API** (https://api.got.show/doc/)

## IDE
* IntelliJ PyCharm

## Valar Morghulis
![Valar Morghulis](http://i.imgur.com/dHdZdPp.jpg)


text:
title: Columns gap
layout: documentation
doc-tab: columns
doc-subtab: gap
---

{% capture columns_default_gap %}

      Default gap

      Default gap

      Default gap

      Default gap

{% endcapture %}

{% capture columns_gapless %}

    No gap

    No gap

    No gap

    No gap

{% endcapture %}

{% capture columns_gapless_multiline %}

    is-one-quarter

    is-one-quarter

    is-one-quarter

    is-one-quarter

    is-half

    is-one-quarter

    is-one-quarter

    is-one-quarter

    Auto

{% endcapture %}

{% include subnav/subnav-columns.html %}

Columns gap

      Customize the gap between the columns

    {% include anchor.html name="Default gap" %}

        Each column has a gap equal to the variable $column-gap, which has a default value of 0.75rem.

        Since the gap is on each side of a column, the gap between two adjacent columns will be twice the value of $column-gap, or 1.5rem by default.

    {{ columns_default_gap }}

    {% include anchor.html name="Gapless" %}

        If you want to remove the space between the columns, add the is-gapless modifier on the columns container:

First column

Second column

Third column

Fourth column

      {% highlight html %}{{ columns_gapless }}{% endhighlight %}

You can combine it with the is-multiline modifier:

is-one-quarter

is-one-quarter

is-one-quarter

is-one-quarter

is-half

is-one-quarter

is-one-quarter

is-one-quarter

Auto

      {% highlight html %}{{ columns_gapless_multiline }}{% endhighlight %}

    {% include anchor.html name="Variable gap" %}

          Experimental

          New
          0.5.2

         You can specify a custom column gap by appending one of 9 modifiers on the .columns container.

          is-0 will remove any gap (similar to is-gapless)

          is-3 is the default value, equivalent to the 0.75rem value

          is-8 is the maximum gap of 2rem

        Additionally, .is-variable should be added on the .columns container.

    {% include klmn.html %}

          This feature is only available in browsers that support CSS Variables:

          If your Sass setup doesn't support CSS Variables, you can disable this feature by setting $variable-columns to false.


text:
<idea-plugin version="2">
    <id>com.github.shiraji.breakpointsmanager</id>
    <name>Breakpoints Manager</name>
    <vendor email="isogai.shiraji@gmail.com" url="https://github.com/shiraji">Shiraji</vendor>

    <description><![CDATA[
    The IntelliJ plugin that helps share/save breakpoints
    ]]></description>

    <change-notes><![CDATA[

1.0.1

Fix problem with applying multiple breakpoints

Add disable breakpoints feature

Add enable breakpoints feature

Older version changes are listed on CHANGELOG.md

    ]]>
    </change-notes>

    <idea-version since-build="143.381.42"/>

    <depends>com.intellij.modules.lang</depends>

    <extensions defaultExtensionNs="com.intellij">
        <projectService serviceImplementation="com.github.shiraji.breakpointsmanager.model.BreakpointsManagerConfig"/>
        <projectService
                serviceImplementation="com.github.shiraji.breakpointsmanager.model.BreakpointsManagerConfigForWorkspace"/>
        <toolWindow id="Breakpoints Manager" anchor="bottom"
                    factoryClass="com.github.shiraji.breakpointsmanager.view.BreakpointsToolWindow"/>
    </extensions>

    <application-components>
    </application-components>

    <project-components>
    </project-components>

    <actions>
    </actions>

</idea-plugin>


text:
[![CI Status](http://img.shields.io/travis/Jon Vogel/TUView.svg?style=flat)](https://travis-ci.org/Jon Vogel/TUView)
[![Version](https://img.shields.io/cocoapods/v/TUView.svg?style=flat)](http://cocoapods.org/pods/TUView)
[![License](https://img.shields.io/cocoapods/l/TUView.svg?style=flat)](http://cocoapods.org/pods/TUView)
[![Platform](https://img.shields.io/cocoapods/p/TUView.svg?style=flat)](http://cocoapods.org/pods/TUView)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

TUView is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "TUView"
```

## Author

Jon Vogel, joninsky@gmail.com

## License

TUView is available under the MIT license. See the LICENSE file for more info.


text:
class AddSlugToCategories < ActiveRecord::Migration
  def self.up
    add_column :categories, :slug, :string, :after => :name
  end

  def self.down
    remove_column :categories, :slug
  end
end


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="simple_php_easy_plus.number_collection_builder.class">SimplePHPEasyPlus\Number\NumberCollectionBuilder</parameter>
        <parameter key="simple_php_easy_plus.parser.simple_number_string_parser_factory.class">SimplePHPEasyPlus\Parser\SimpleNumberStringParserFactory</parameter>
        <parameter key="simple_php_easy_plus.number.number_factory.class">SimplePHPEasyPlus\Number\SimpleNumberFactory</parameter>
        <parameter key="simple_php_easy_plus.number.collection_item_number_proxy_factory.class">SimplePHPEasyPlus\Number\CollectionItemNumberProxyFactory</parameter>

        <parameter key="simple_php_easy_plus.engine.class">SimplePHPEasyPlus\Engine</parameter>
        <parameter key="simple_php_easy_plus.operation.class">SimplePHPEasyPlus\Operation\ArithmeticOperation</parameter>
        <parameter key="simple_php_easy_plus.operator.addition.class">SimplePHPEasyPlus\Operator\AdditionOperator</parameter>
        <parameter key="simple_php_easy_plus.operator.number.class">SimplePHPEasyPlus\Number\SimpleNumber</parameter>

        <parameter key="simple_php_easy_plus.runner.class">SimplePHPEasyPlus\Calcul\CalculRunner</parameter>
    </parameters>

    <services>
        <service id="simple_php_easy_plus.number_collection_builder" class="%simple_php_easy_plus.number_collection_builder.class%" scope="prototype">
            <argument type="service" id="simple_php_easy_plus.parser.simple_number_string_parser_factory"/>
            <argument type="service" id="simple_php_easy_plus.number.number_factory"/>
            <argument type="service" id="simple_php_easy_plus.number.collection_item_number_proxy_factory"/>
        </service>

        <service id="simple_php_easy_plus.engine" class="%simple_php_easy_plus.engine.class%">
            <argument type="service" id="simple_php_easy_plus.operation"/>
        </service>

        <service id="simple_php_easy_plus.runner" class="%simple_php_easy_plus.runner.class%"></service>

        <service id="simple_php_easy_plus.parser.simple_number_string_parser_factory" class="%simple_php_easy_plus.parser.simple_number_string_parser_factory.class%" public="false"></service>
        <service id="simple_php_easy_plus.number.number_factory" class="%simple_php_easy_plus.number.number_factory.class%" public="false"></service>
        <service id="simple_php_easy_plus.number.collection_item_number_proxy_factory" class="%simple_php_easy_plus.number.collection_item_number_proxy_factory.class%" public="false"></service>

        <service id="simple_php_easy_plus.operation" class="%simple_php_easy_plus.operation.class%" public="false">
            <argument type="service" id="simple_php_easy_plus.operator.addition"/>
        </service>

        <service id="simple_php_easy_plus.operator.addition" class="%simple_php_easy_plus.operator.addition.class%" public="false">
            <argument>%simple_php_easy_plus.operator.number.class%</argument>
        </service>
    </services>
</container>


text:
<?php

namespace Google\Cloud\Tests\BigQuery;

use Google\Cloud\BigQuery\Connection\ConnectionInterface;
use Google\Cloud\BigQuery\QueryResults;
use Google\Cloud\BigQuery\ValueMapper;
use Prophecy\Argument;

/**
 * @group bigquery
 */
class QueryResultsTest extends \PHPUnit_Framework_TestCase
{
    public $connection;
    public $projectId = 'myProjectId';
    public $jobId = 'myJobId';
    public $queryData = [
        'jobComplete' => true,
        'rows' => [
            ['f' => [['v' => 'Alton']]]
        ],
        'schema' => [
            'fields' => [
                [
                    'name' => 'first_name',
                    'type' => 'STRING'
                ]
            ]
        ]
    ];

    public function setUp()
    {
        $this->connection = $this->prophesize(ConnectionInterface::class);
    }

    public function getQueryResults($connection, array $data = [])
    {
        return new QueryResults(
            $connection->reveal(),
            $this->jobId,
            $this->projectId,
            $data,
            [],
            new ValueMapper(false)
        );
    }

    /**
     * @expectedException \Google\Cloud\Exception\GoogleException
     */
    public function testGetsRowsThrowsExceptionWhenQueryNotComplete()
    {
        $this->queryData['jobComplete'] = false;
        unset($this->queryData['rows']);
        $this->connection->getQueryResults()->shouldNotBeCalled();
        $queryResults = $this->getQueryResults($this->connection, $this->queryData);
        $queryResults->rows()->next();
    }

    public function testGetsRowsWithNoResults()
    {
        $this->connection->getQueryResults()->shouldNotBeCalled();
        unset($this->queryData['rows']);
        $queryResults = $this->getQueryResults($this->connection, $this->queryData);
        $rows = iterator_to_array($queryResults->rows());

        $this->assertEmpty($rows);
    }

    public function testGetsRowsWithoutToken()
    {
        $this->connection->getQueryResults()->shouldNotBeCalled();
        $queryResults = $this->getQueryResults($this->connection, $this->queryData);
        $rows = iterator_to_array($queryResults->rows());

        $this->assertEquals('Alton', $rows[0]['first_name']);
    }

    public function testGetsRowsWithToken()
    {
        $this->connection->getQueryResults(Argument::any())
            ->willReturn($this->queryData)
            ->shouldBeCalledTimes(1);
        $queryResults = $this->getQueryResults(
            $this->connection,
            $this->queryData + ['pageToken' => 'abcd']
        );
        $rows = iterator_to_array($queryResults->rows());

        $this->assertEquals('Alton', $rows[1]['first_name']);
    }

    public function testIsCompleteTrue()
    {
        $queryResults = $this->getQueryResults($this->connection, $this->queryData);

        $this->assertTrue($queryResults->isComplete());
    }

    public function testIsCompleteFalse()
    {
        $this->queryData['jobComplete'] = false;
        $queryResults = $this->getQueryResults($this->connection, $this->queryData);

        $this->assertFalse($queryResults->isComplete());
    }

    public function testGetsInfo()
    {
        $queryResults = $this->getQueryResults($this->connection, $this->queryData);

        $this->assertEquals($this->queryData, $queryResults->info());
    }

    public function testReloadsInfo()
    {
        $this->connection->getQueryResults(Argument::any())
            ->willReturn(['jobComplete' => true])
            ->shouldBeCalledTimes(1);
        $queryResults = $this->getQueryResults($this->connection, $this->queryData);

        $this->assertEquals(['jobComplete' => true], $queryResults->reload());
    }

    public function testGetsIdentity()
    {
        $queryResults = $this->getQueryResults($this->connection);

        $this->assertEquals($this->jobId, $queryResults->identity()['jobId']);
        $this->assertEquals($this->projectId, $queryResults->identity()['projectId']);
    }
}


text:
<?php
class PDP_Integration_Block_Customerdesign extends Mage_Core_Block_Template
{
	public function __construct()
    {
        parent::__construct();
        $collection = Mage::getModel('integration/customerdesigns')->getCollection();
        //Filter by customer ID
        $customer = Mage::getSingleton("customer/session")->getCustomer();
        $collection->addFieldToFilter("customer_id", $customer->getId());
		$collection->setOrder("integration_id", "desc");
        $this->setCollection($collection);
    }
    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        $pager = $this->getLayout()->createBlock('page/html_pager', 'custom.pager');
        $pager->setAvailableLimit(array(5=>5,10=>10,20=>20,'all'=>'All'));
        $pager->setCollection($this->getCollection());
        $this->setChild('pager', $pager);
        $this->getCollection()->load();
        return $this;
    }
    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }
	function getMageProductById($productId)
	{
		return Mage::getModel('catalog/product')->load($productId);
	}
	/**
	* get all design completed
	* @param int $customId
	* @return array
	**/
	function getAllCompleteDesigns()
	{
		$designIds = array();
		if(Mage::getSingleton('customer/session')->isLoggedIn()) {
			$customer = Mage::getSingleton('customer/session')->getCustomer();
			if($customer->getId() && $customer->getId() > 0)
			{
				$orderCollection = Mage::getResourceModel('sales/order_collection')
				->addFieldToSelect('*')
				->addFieldToFilter('customer_id', $customer->getId())
				->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
				->setOrder('created_at', 'desc');
				foreach($orderCollection as $order)
				{
					$items = $order->getAllItems();

					if($order->getStatus() == 'complete')
					{
						foreach($items as $item)
						{
							$request = $item->getBuyRequest()->getData();
							$pdpOptions = isset($request['pdp_option']) ? $request['pdp_option'] : array();
							if(count($pdpOptions))
							{
								$designId = isset($pdpOptions['design_id']) ? (int)$pdpOptions['design_id'] : 0;
								if($designId > 0)
								{
									$designIds[$designId] = $item->getRowTotal();
								}
							}
						}
					}

				}
			}
		}
		return $designIds;
	}
}


text:
<?php

namespace Google\Service\ChromePolicy;

class GoogleChromePolicyV1PolicySchemaFieldDescription extends \Google\Collection
{
  protected $collection_key = 'requiredItems';
  /**
   * @var string
   */
  public $description;
  /**
   * @var string
   */
  public $field;
  protected $fieldDependenciesType = GoogleChromePolicyV1PolicySchemaFieldDependencies::class;
  protected $fieldDependenciesDataType = 'array';
  /**
   * @var string
   */
  public $fieldDescription;
  /**
   * @var string
   */
  public $inputConstraint;
  protected $knownValueDescriptionsType = GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription::class;
  protected $knownValueDescriptionsDataType = 'array';
  /**
   * @var string
   */
  public $name;
  protected $nestedFieldDescriptionsType = GoogleChromePolicyV1PolicySchemaFieldDescription::class;
  protected $nestedFieldDescriptionsDataType = 'array';
  protected $requiredItemsType = GoogleChromePolicyV1PolicySchemaRequiredItems::class;
  protected $requiredItemsDataType = 'array';

  /**
   * @param string
   */
  public function setDescription($description)
  {
    $this->description = $description;
  }
  /**
   * @return string
   */
  public function getDescription()
  {
    return $this->description;
  }
  /**
   * @param string
   */
  public function setField($field)
  {
    $this->field = $field;
  }
  /**
   * @return string
   */
  public function getField()
  {
    return $this->field;
  }
  /**
   * @param GoogleChromePolicyV1PolicySchemaFieldDependencies[]
   */
  public function setFieldDependencies($fieldDependencies)
  {
    $this->fieldDependencies = $fieldDependencies;
  }
  /**
   * @return GoogleChromePolicyV1PolicySchemaFieldDependencies[]
   */
  public function getFieldDependencies()
  {
    return $this->fieldDependencies;
  }
  /**
   * @param string
   */
  public function setFieldDescription($fieldDescription)
  {
    $this->fieldDescription = $fieldDescription;
  }
  /**
   * @return string
   */
  public function getFieldDescription()
  {
    return $this->fieldDescription;
  }
  /**
   * @param string
   */
  public function setInputConstraint($inputConstraint)
  {
    $this->inputConstraint = $inputConstraint;
  }
  /**
   * @return string
   */
  public function getInputConstraint()
  {
    return $this->inputConstraint;
  }
  /**
   * @param GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription[]
   */
  public function setKnownValueDescriptions($knownValueDescriptions)
  {
    $this->knownValueDescriptions = $knownValueDescriptions;
  }
  /**
   * @return GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription[]
   */
  public function getKnownValueDescriptions()
  {
    return $this->knownValueDescriptions;
  }
  /**
   * @param string
   */
  public function setName($name)
  {
    $this->name = $name;
  }
  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param GoogleChromePolicyV1PolicySchemaFieldDescription[]
   */
  public function setNestedFieldDescriptions($nestedFieldDescriptions)
  {
    $this->nestedFieldDescriptions = $nestedFieldDescriptions;
  }
  /**
   * @return GoogleChromePolicyV1PolicySchemaFieldDescription[]
   */
  public function getNestedFieldDescriptions()
  {
    return $this->nestedFieldDescriptions;
  }
  /**
   * @param GoogleChromePolicyV1PolicySchemaRequiredItems[]
   */
  public function setRequiredItems($requiredItems)
  {
    $this->requiredItems = $requiredItems;
  }
  /**
   * @return GoogleChromePolicyV1PolicySchemaRequiredItems[]
   */
  public function getRequiredItems()
  {
    return $this->requiredItems;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleChromePolicyV1PolicySchemaFieldDescription::class, 'Google_Service_ChromePolicy_GoogleChromePolicyV1PolicySchemaFieldDescription');


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

<title>UserSessionRegistry (Spring Framework 4.3.3.RELEASE API)</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.springframework.messaging.simp.user

Interface UserSessionRegistry

All Known Implementing Classes:

DefaultUserSessionRegistry

Deprecated.

in favor of SimpUserRegistry in combination with
 ApplicationListener listening for
 AbstractSubProtocolEvent events.

@Deprecated
public interface UserSessionRegistry

A contract for adding and removing user sessions.

As of 4.2, this interface is replaced by SimpUserRegistry,
 exposing methods to return all registered users as well as to provide
 more extensive information for each user.

Since:

4.0

Author:

Rossen Stoyanchev

Method Summary

All Methods Instance Methods Abstract Methods Deprecated Methods

Modifier and Type
Method and Description

Set<String>
getSessionIds(String userName)

Deprecated.

Return the active session ids for the user.

void
registerSessionId(String userName,
                 String sessionId)

Deprecated.

Register an active session id for a user.

void
unregisterSessionId(String userName,
                   String sessionId)

Deprecated.

Unregister an active session id for a user.

Method Detail

getSessionIds

Set<String> getSessionIds(String userName)

Deprecated.

Return the active session ids for the user.
 The returned set is a snapshot that will never be modified.

Parameters:

userName - the user to look up

Returns:

a set with 0 or more session ids, never null.

registerSessionId

void registerSessionId(String userName,
                       String sessionId)

Deprecated.

Register an active session id for a user.

Parameters:

userName - the user name

sessionId - the session id

unregisterSessionId

void unregisterSessionId(String userName,
                         String sessionId)

Deprecated.

Unregister an active session id for a user.

Parameters:

userName - the user name

sessionId - the session id

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
function initialize(){

	var mapLocation = new google.maps.LatLng(-36.906946, 174.713391);
	var mapStyles = [{
		stylers:[
			{hue: "#468C00"},
			{saturation: -50}
			]
	}];

	var markerStyles =[{
		stylers:[
		{hue: "#00205F"},
		{saturation: -50}
		]
	}]

	var mapOptions ={
		zoom: 17,
		center: mapLocation,
		styles: mapStyles

	}

	var map = new google.maps.Map(document.getElementById('flex-google'), mapOptions);

//geo position

var request = {address: "Laser Mt Eden Swimming, Kelston Squad"};
var geocoder = new google.maps.Geocoder();

geocoder.geocode(request,function(results,status){

	console.log(results);
	console.log(status);

	if(status == 'OK'){

		var destination = results[0].geometry.location;
		map.setCenter(destination);

		//desitination marker
		var destinationMarker = new google.maps.Marker({map:map});
		destinationMarker.setPosition(destination);

}

});

	// var logoMarker = 'img/Laser-Mt-Eden.png';

	var marker = new google.maps.Marker({
		position: mapLocation,
		map: map,
		styles: markerStyles,
		animation: google.maps.Animation.DROP,
		position: mapLocation,
		// icon: logoMarker
		// title: 'Laser Mt Eden Swim Club'

	});
	google.maps.event.addListener(marker,'click',toggleBounce);
}

//animate the marker

function toggleBounce(){

	if(marker.getAnimation() != null){
		marker.setAnimation(null);
	}else{
		marker.setAnimation(google.maps.Animation.BOUNCE);
	}
}

google.maps.event.addDomListener(window,'load',initialize);


text:
using ppapi::proxy::SerializedHandle;
using ppapi::thunk::EnterResourceNoLock;
using ppapi::thunk::PPB_VideoEncoder_API;

namespace ppapi {
namespace proxy {

namespace {

void RunCallback(scoped_refptr<TrackedCallback>* callback, int32_t error) {
  if (!TrackedCallback::IsPending(*callback))
    return;

  scoped_refptr<TrackedCallback> temp;
  callback->swap(temp);
  temp->Run(error);
}

}  // namespace

VideoEncoderResource::ShmBuffer::ShmBuffer(uint32_t id,
                                           scoped_ptr<base::SharedMemory> shm)
    : id(id), shm(shm.Pass()) {
}

VideoEncoderResource::ShmBuffer::~ShmBuffer() {
}

VideoEncoderResource::BitstreamBuffer::BitstreamBuffer(uint32_t id,
                                                       uint32_t size,
                                                       bool key_frame)
    : id(id), size(size), key_frame(key_frame) {
}

VideoEncoderResource::BitstreamBuffer::~BitstreamBuffer() {
}

VideoEncoderResource::VideoEncoderResource(Connection connection,
                                           PP_Instance instance)
    : PluginResource(connection, instance),
      initialized_(false),
      closed_(false),
      // Set |encoder_last_error_| to PP_OK after successful initialization.
      // This makes error checking a little more concise, since we can check
      // that the encoder has been initialized and hasn't returned an error by
      // just testing |encoder_last_error_|.
      encoder_last_error_(PP_ERROR_FAILED),
      input_frame_count_(0),
      input_coded_size_(PP_MakeSize(0, 0)),
      buffer_manager_(this),
      get_video_frame_data_(nullptr),
      get_bitstream_buffer_data_(nullptr) {
  SendCreate(RENDERER, PpapiHostMsg_VideoEncoder_Create());
}

VideoEncoderResource::~VideoEncoderResource() {
  Close();
}

PPB_VideoEncoder_API* VideoEncoderResource::AsPPB_VideoEncoder_API() {
  return this;
}

int32_t VideoEncoderResource::GetSupportedProfiles(
    const PP_ArrayOutput& output,
    const scoped_refptr<TrackedCallback>& callback) {
  if (TrackedCallback::IsPending(get_supported_profiles_callback_))
    return PP_ERROR_INPROGRESS;

  get_supported_profiles_callback_ = callback;
  Call<PpapiPluginMsg_VideoEncoder_GetSupportedProfilesReply>(
      RENDERER, PpapiHostMsg_VideoEncoder_GetSupportedProfiles(),
      base::Bind(&VideoEncoderResource::OnPluginMsgGetSupportedProfilesReply,
                 this, output));
  return PP_OK_COMPLETIONPENDING;
}

int32_t VideoEncoderResource::GetFramesRequired() {
  if (encoder_last_error_)
    return encoder_last_error_;
  return input_frame_count_;
}

int32_t VideoEncoderResource::GetFrameCodedSize(PP_Size* size) {
  if (encoder_last_error_)
    return encoder_last_error_;
  *size = input_coded_size_;
  return PP_OK;
}

int32_t VideoEncoderResource::Initialize(
    PP_VideoFrame_Format input_format,
    const PP_Size* input_visible_size,
    PP_VideoProfile output_profile,
    uint32_t initial_bitrate,
    PP_HardwareAcceleration acceleration,
    const scoped_refptr<TrackedCallback>& callback) {
  if (initialized_)
    return PP_ERROR_FAILED;
  if (TrackedCallback::IsPending(initialize_callback_))
    return PP_ERROR_INPROGRESS;

  initialize_callback_ = callback;
  Call<PpapiPluginMsg_VideoEncoder_InitializeReply>(
      RENDERER, PpapiHostMsg_VideoEncoder_Initialize(
                    input_format, *input_visible_size, output_profile,
                    initial_bitrate, acceleration),
      base::Bind(&VideoEncoderResource::OnPluginMsgInitializeReply, this));
  return PP_OK_COMPLETIONPENDING;
}

int32_t VideoEncoderResource::GetVideoFrame(
    PP_Resource* video_frame,
    const scoped_refptr<TrackedCallback>& callback) {
  if (encoder_last_error_)
    return encoder_last_error_;

  if (TrackedCallback::IsPending(get_video_frame_callback_))
    return PP_ERROR_INPROGRESS;

  get_video_frame_data_ = video_frame;
  get_video_frame_callback_ = callback;

  // Lazily ask for a shared memory buffer in which video frames are allocated.
  if (buffer_manager_.number_of_buffers() == 0) {
    Call<PpapiPluginMsg_VideoEncoder_GetVideoFramesReply>(
        RENDERER, PpapiHostMsg_VideoEncoder_GetVideoFrames(),
        base::Bind(&VideoEncoderResource::OnPluginMsgGetVideoFramesReply,
                   this));
  } else {
    TryWriteVideoFrame();
  }

  return PP_OK_COMPLETIONPENDING;
}

int32_t VideoEncoderResource::Encode(
    PP_Resource video_frame,
    PP_Bool force_keyframe,
    const scoped_refptr<TrackedCallback>& callback) {
  if (encoder_last_error_)
    return encoder_last_error_;

  VideoFrameMap::iterator it = video_frames_.find(video_frame);
  if (it == video_frames_.end())
    // TODO(llandwerlin): accept MediaStreamVideoTrack's video frames.
    return PP_ERROR_BADRESOURCE;

  scoped_refptr<VideoFrameResource> frame_resource = it->second;

  encode_callbacks_.insert(std::make_pair(video_frame, callback));

  Call<PpapiPluginMsg_VideoEncoder_EncodeReply>(
      RENDERER,
      PpapiHostMsg_VideoEncoder_Encode(frame_resource->GetBufferIndex(),
                                       PP_ToBool(force_keyframe)),
      base::Bind(&VideoEncoderResource::OnPluginMsgEncodeReply, this,
                 video_frame));

  // Invalidate the frame to prevent the plugin from modifying it.
  it->second->Invalidate();
  video_frames_.erase(it);

  return PP_OK_COMPLETIONPENDING;
}

int32_t VideoEncoderResource::GetBitstreamBuffer(
    PP_BitstreamBuffer* bitstream_buffer,
    const scoped_refptr<TrackedCallback>& callback) {
  if (encoder_last_error_)
    return encoder_last_error_;
  if (TrackedCallback::IsPending(get_bitstream_buffer_callback_))
    return PP_ERROR_INPROGRESS;

  get_bitstream_buffer_callback_ = callback;
  get_bitstream_buffer_data_ = bitstream_buffer;

  if (!available_bitstream_buffers_.empty()) {
    BitstreamBuffer buffer(available_bitstream_buffers_.front());
    available_bitstream_buffers_.pop_front();
    WriteBitstreamBuffer(buffer);
  }

  return PP_OK_COMPLETIONPENDING;
}

void VideoEncoderResource::RecycleBitstreamBuffer(
    const PP_BitstreamBuffer* bitstream_buffer) {
  if (encoder_last_error_)
    return;
  BitstreamBufferMap::const_iterator iter =
      bitstream_buffer_map_.find(bitstream_buffer->buffer);
  if (iter != bitstream_buffer_map_.end()) {
    Post(RENDERER,
         PpapiHostMsg_VideoEncoder_RecycleBitstreamBuffer(iter->second));
  }
}

void VideoEncoderResource::RequestEncodingParametersChange(uint32_t bitrate,
                                                           uint32_t framerate) {
  if (encoder_last_error_)
    return;
  Post(RENDERER, PpapiHostMsg_VideoEncoder_RequestEncodingParametersChange(
                     bitrate, framerate));
}

void VideoEncoderResource::Close() {
  if (closed_)
    return;
  Post(RENDERER, PpapiHostMsg_VideoEncoder_Close());
  closed_ = true;
  if (!encoder_last_error_ || !initialized_)
    NotifyError(PP_ERROR_ABORTED);
  ReleaseFrames();
}

void VideoEncoderResource::OnReplyReceived(
    const ResourceMessageReplyParams& params,
    const IPC::Message& msg) {
  PPAPI_BEGIN_MESSAGE_MAP(VideoEncoderResource, msg)
    PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL(
        PpapiPluginMsg_VideoEncoder_BitstreamBuffers,
        OnPluginMsgBitstreamBuffers)
    PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL(
        PpapiPluginMsg_VideoEncoder_BitstreamBufferReady,
        OnPluginMsgBitstreamBufferReady)
    PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL(PpapiPluginMsg_VideoEncoder_NotifyError,
                                        OnPluginMsgNotifyError)
    PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL_UNHANDLED(
        PluginResource::OnReplyReceived(params, msg))
  PPAPI_END_MESSAGE_MAP()
}

void VideoEncoderResource::OnPluginMsgGetSupportedProfilesReply(
    const PP_ArrayOutput& output,
    const ResourceMessageReplyParams& params,
    const std::vector<PP_VideoProfileDescription>& profiles) {
  int32_t error = params.result();
  if (error) {
    NotifyError(error);
    return;
  }

  ArrayWriter writer(output);
  if (!writer.is_valid()) {
    RunCallback(&get_supported_profiles_callback_, PP_ERROR_BADARGUMENT);
    return;
  }

  if (!writer.StoreVector(profiles)) {
    RunCallback(&get_supported_profiles_callback_, PP_ERROR_FAILED);
    return;
  }

  RunCallback(&get_supported_profiles_callback_, PP_OK);
}

void VideoEncoderResource::OnPluginMsgInitializeReply(
    const ResourceMessageReplyParams& params,
    uint32_t input_frame_count,
    const PP_Size& input_coded_size) {
  DCHECK(!initialized_);

  encoder_last_error_ = params.result();
  if (!encoder_last_error_)
    initialized_ = true;

  input_frame_count_ = input_frame_count;
  input_coded_size_ = input_coded_size;

  RunCallback(&initialize_callback_, encoder_last_error_);
}

void VideoEncoderResource::OnPluginMsgGetVideoFramesReply(
    const ResourceMessageReplyParams& params,
    uint32_t frame_count,
    uint32_t frame_length,
    const PP_Size& frame_size) {
  int32_t error = params.result();
  if (error) {
    NotifyError(error);
    return;
  }

  base::SharedMemoryHandle buffer_handle;
  params.TakeSharedMemoryHandleAtIndex(0, &buffer_handle);

  if (!buffer_manager_.SetBuffers(
          frame_count, frame_length,
          make_scoped_ptr(new base::SharedMemory(buffer_handle, false)),
          true)) {
    NotifyError(PP_ERROR_FAILED);
    return;
  }

  if (TrackedCallback::IsPending(get_video_frame_callback_))
    TryWriteVideoFrame();
}

void VideoEncoderResource::OnPluginMsgEncodeReply(
    PP_Resource video_frame,
    const ResourceMessageReplyParams& params,
    uint32_t frame_id) {
  DCHECK_NE(encode_callbacks_.size(), 0U);
  encoder_last_error_ = params.result();

  EncodeMap::iterator it = encode_callbacks_.find(video_frame);
  DCHECK(encode_callbacks_.end() != it);

  scoped_refptr<TrackedCallback> callback = it->second;
  encode_callbacks_.erase(it);
  RunCallback(&callback, encoder_last_error_);

  buffer_manager_.EnqueueBuffer(frame_id);
  // If the plugin is waiting for a video frame, we can give the one
  // that just became available again.
  if (TrackedCallback::IsPending(get_video_frame_callback_))
    TryWriteVideoFrame();
}

void VideoEncoderResource::OnPluginMsgBitstreamBuffers(
    const ResourceMessageReplyParams& params,
    uint32_t buffer_length) {
  std::vector<base::SharedMemoryHandle> shm_handles;
  params.TakeAllSharedMemoryHandles(&shm_handles);
  if (shm_handles.size() == 0) {
    NotifyError(PP_ERROR_FAILED);
    return;
  }

  for (uint32_t i = 0; i < shm_handles.size(); ++i) {
    scoped_ptr<base::SharedMemory> shm(
        new base::SharedMemory(shm_handles[i], true));
    CHECK(shm->Map(buffer_length));

    ShmBuffer* buffer = new ShmBuffer(i, shm.Pass());
    shm_buffers_.push_back(buffer);
    bitstream_buffer_map_.insert(
        std::make_pair(buffer->shm->memory(), buffer->id));
  }
}

void VideoEncoderResource::OnPluginMsgBitstreamBufferReady(
    const ResourceMessageReplyParams& params,
    uint32_t buffer_id,
    uint32_t buffer_size,
    bool key_frame) {
  available_bitstream_buffers_.push_back(
      BitstreamBuffer(buffer_id, buffer_size, key_frame));

  if (TrackedCallback::IsPending(get_bitstream_buffer_callback_)) {
    BitstreamBuffer buffer(available_bitstream_buffers_.front());
    available_bitstream_buffers_.pop_front();
    WriteBitstreamBuffer(buffer);
  }
}

void VideoEncoderResource::OnPluginMsgNotifyError(
    const ResourceMessageReplyParams& params,
    int32_t error) {
  NotifyError(error);
}

void VideoEncoderResource::NotifyError(int32_t error) {
  encoder_last_error_ = error;
  RunCallback(&get_supported_profiles_callback_, error);
  RunCallback(&initialize_callback_, error);
  RunCallback(&get_video_frame_callback_, error);
  get_video_frame_data_ = nullptr;
  RunCallback(&get_bitstream_buffer_callback_, error);
  get_bitstream_buffer_data_ = nullptr;
  for (EncodeMap::iterator it = encode_callbacks_.begin();
       it != encode_callbacks_.end(); ++it) {
    scoped_refptr<TrackedCallback> callback = it->second;
    RunCallback(&callback, error);
  }
  encode_callbacks_.clear();
}

void VideoEncoderResource::TryWriteVideoFrame() {
  DCHECK(TrackedCallback::IsPending(get_video_frame_callback_));

  int32_t frame_id = buffer_manager_.DequeueBuffer();
  if (frame_id < 0)
    return;

  scoped_refptr<VideoFrameResource> resource = new VideoFrameResource(
      pp_instance(), frame_id, buffer_manager_.GetBufferPointer(frame_id));
  video_frames_.insert(
      VideoFrameMap::value_type(resource->pp_resource(), resource));

  *get_video_frame_data_ = resource->GetReference();
  get_video_frame_data_ = nullptr;
  RunCallback(&get_video_frame_callback_, PP_OK);
}

void VideoEncoderResource::WriteBitstreamBuffer(const BitstreamBuffer& buffer) {
  DCHECK_LT(buffer.id, shm_buffers_.size());

  get_bitstream_buffer_data_->size = buffer.size;
  get_bitstream_buffer_data_->buffer = shm_buffers_[buffer.id]->shm->memory();
  get_bitstream_buffer_data_->key_frame = PP_FromBool(buffer.key_frame);
  get_bitstream_buffer_data_ = nullptr;
  RunCallback(&get_bitstream_buffer_callback_, PP_OK);
}

void VideoEncoderResource::ReleaseFrames() {
  for (VideoFrameMap::iterator it = video_frames_.begin();
       it != video_frames_.end(); ++it) {
    it->second->Invalidate();
    it->second = nullptr;
  }
  video_frames_.clear();
}

}  // namespace proxy
}  // namespace ppapi


text:
using ProgrammersSpot.Business.MVP.Args;
using ProgrammersSpot.Business.MVP.ViewModels;
using System;
using WebFormsMvp;

namespace ProgrammersSpot.Business.MVP.Views
{
    public interface IUserUploadImageView : IView<UploadImageViewModel>
    {
        event EventHandler<UserUploadImageEventArgs> UploadImageWithUrl;
    }
}


text:
(function () {
    'use strict';

    angular
        .module('app')
        .controller('MainController', MainController);

    function MainController($scope, MainService, _) {
        $scope.name = "";

        $scope.greetings = [];

        $scope.greet = function () {
            var msg = MainService.greet($scope.name);
            $scope.greetings.push(_.replace(msg, "Hello", "Goodbye"));
        };

    }
})();


text:
<!DOCTYPE html>

    <title>submergence:Agent#setIdle~summary documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../../../highlight.css" />

            spare

                :submergence:Agent#setIdle~summary

Set the user's login status to idle. If the user was a guest, they will receive credentials
for an expired session. If the user was active they will be downgraded to idle.

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
'use strict';

const path = require(`path`);
const test = require(`ava`);
const tools = require(`@google-cloud/nodejs-repo-tools`);
const translate = require(`@google-cloud/translate`)();

const cwd = path.join(__dirname, `..`);
const cmd = `node translate.js`;
const text = `Hello world!`;
const text2 = `Goodbye!`;
const model = `nmt`;
const toLang = `ru`;

test.before(tools.checkCredentials);

test(`should detect language of a single string`, async (t) => {
  const output = await tools.runAsync(`${cmd} detect "${text}"`, cwd);
  const [detection] = await translate.detect(text);
  const expected = `Detections:\n${text} => ${detection.language}`;
  t.is(output, expected);
});

test(`should detect language of multiple strings`, async (t) => {
  const output = await tools.runAsync(`${cmd} detect "${text}" "${text2}"`, cwd);
  const [detections] = await translate.detect([text, text2]);
  const expected = `Detections:\n${text} => ${detections[0].language}\n${text2} => ${detections[1].language}`;
  t.is(output, expected);
});

test(`should list languages`, async (t) => {
  const output = await tools.runAsync(`${cmd} list`, cwd);
  t.true(output.includes(`Languages:`));
  t.true(output.includes(`{ code: 'af', name: 'Afrikaans' }`));
});

test(`should list languages with a target`, async (t) => {
  const output = await tools.runAsync(`${cmd} list es`, cwd);
  t.true(output.includes(`Languages:`));
  t.true(output.includes(`{ code: 'af', name: 'afrikáans' }`));
});

test(`should translate a single string`, async (t) => {
  const output = await tools.runAsync(`${cmd} translate ${toLang} "${text}"`, cwd);
  const [translation] = await translate.translate(text, toLang);
  const expected = `Translations:\n${text} => (${toLang}) ${translation}`;
  t.is(output, expected);
});

test(`should translate multiple strings`, async (t) => {
  const output = await tools.runAsync(`${cmd} translate ${toLang} "${text}" "${text2}"`, cwd);
  const [translations] = await translate.translate([text, text2], toLang);
  const expected = `Translations:\n${text} => (${toLang}) ${translations[0]}\n${text2} => (${toLang}) ${translations[1]}`;
  t.is(output, expected);
});

test(`should translate a single string with a model`, async (t) => {
  const output = await tools.runAsync(`${cmd} translate-with-model ${toLang} ${model} "${text}"`, cwd);
  const [translation] = await translate.translate(text, toLang);
  const expected = `Translations:\n${text} => (${toLang}) ${translation}`;
  t.is(output, expected);
});

test(`should translate multiple strings with a model`, async (t) => {
  const output = await tools.runAsync(`${cmd} translate-with-model ${toLang} ${model} "${text}" "${text2}"`, cwd);
  const [translations] = await translate.translate([text, text2], toLang);
  const expected = `Translations:\n${text} => (${toLang}) ${translations[0]}\n${text2} => (${toLang}) ${translations[1]}`;
  t.is(output, expected);
});