text:
// Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Directive for the jobs tab in the admin panel.
 */

require('domain/utilities/url-interpolation.service.ts');
require('pages/admin-page/services/admin-data.service.ts');

require('pages/admin-page/admin-page.constants.ajs.ts');

angular.module('oppia').directive('adminJobsTab', [
  '$http', '$rootScope', '$timeout', 'AdminDataService',
  'UrlInterpolationService', 'ADMIN_HANDLER_URL',
  'ADMIN_JOB_OUTPUT_URL_TEMPLATE',
  function(
      $http, $rootScope, $timeout, AdminDataService,
      UrlInterpolationService, ADMIN_HANDLER_URL,
      ADMIN_JOB_OUTPUT_URL_TEMPLATE) {
    return {
      restrict: 'E',
      scope: {},
      bindToController: {
        setStatusMessage: '='
      },
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/pages/admin-page/jobs-tab/admin-jobs-tab.directive.html'),
      controllerAs: '$ctrl',
      controller: [function() {
        var ctrl = this;
        ctrl.showJobOutput = function(jobId) {
          var adminJobOutputUrl = UrlInterpolationService.interpolateUrl(
            ADMIN_JOB_OUTPUT_URL_TEMPLATE, {
              jobId: jobId
            });
          $http.get(adminJobOutputUrl).then(function(response) {
            ctrl.showingJobOutput = true;
            ctrl.jobOutput = response.data.output || [];
            ctrl.jobOutput.sort();
            $timeout(function() {
              document.querySelector('#job-output').scrollIntoView();
            });
          });
        };

        ctrl.startNewJob = function(jobType) {
          ctrl.setStatusMessage('Starting new job...');

          $http.post(ADMIN_HANDLER_URL, {
            action: 'start_new_job',
            job_type: jobType
          }).then(function() {
            ctrl.setStatusMessage('Job started successfully.');
            window.location.reload();
          }, function(errorResponse) {
            ctrl.setStatusMessage(
              'Server error: ' + errorResponse.data.error);
          });
        };

        ctrl.cancelJob = function(jobId, jobType) {
          ctrl.setStatusMessage('Cancelling job...');

          $http.post(ADMIN_HANDLER_URL, {
            action: 'cancel_job',
            job_id: jobId,
            job_type: jobType
          }).then(function() {
            ctrl.setStatusMessage('Abort signal sent to job.');
            window.location.reload();
          }, function(errorResponse) {
            ctrl.setStatusMessage(
              'Server error: ' + errorResponse.data.error);
          });
        };

        ctrl.startComputation = function(computationType) {
          ctrl.setStatusMessage('Starting computation...');

          $http.post(ADMIN_HANDLER_URL, {
            action: 'start_computation',
            computation_type: computationType
          }).then(function() {
            ctrl.setStatusMessage('Computation started successfully.');
            window.location.reload();
          }, function(errorResponse) {
            ctrl.setStatusMessage(
              'Server error: ' + errorResponse.data.error);
          });
        };

        ctrl.stopComputation = function(computationType) {
          ctrl.setStatusMessage('Stopping computation...');

          $http.post(ADMIN_HANDLER_URL, {
            action: 'stop_computation',
            computation_type: computationType
          }).then(function() {
            ctrl.setStatusMessage('Abort signal sent to computation.');
            window.location.reload();
          }, function(errorResponse) {
            ctrl.setStatusMessage(
              'Server error: ' + errorResponse.data.error);
          });
        };
        ctrl.$onInit = function() {
          ctrl.HUMAN_READABLE_CURRENT_TIME = '';
          ctrl.CONTINUOUS_COMPUTATIONS_DATA = {};
          ctrl.ONE_OFF_JOB_SPECS = {};
          ctrl.UNFINISHED_JOB_DATA = {};
          ctrl.AUDIT_JOB_SPECS = {};
          ctrl.RECENT_JOB_DATA = {};
          AdminDataService.getDataAsync().then(function(adminDataObject) {
            ctrl.HUMAN_READABLE_CURRENT_TIME = (
              adminDataObject.humanReadeableCurrentTime);
            ctrl.CONTINUOUS_COMPUTATIONS_DATA = (
              adminDataObject.continuousComputationsData);
            ctrl.ONE_OFF_JOB_SPECS = adminDataObject.oneOffJobStatusSummaries;
            ctrl.UNFINISHED_JOB_DATA = adminDataObject.unfinishedJobData;
            ctrl.AUDIT_JOB_SPECS = adminDataObject.auditJobStatusSummaries;
            ctrl.RECENT_JOB_DATA = adminDataObject.recentJobData;
            // TODO(#8521): Remove the use of $rootScope.$apply()
            // once the directive is migrated to angular.
            $rootScope.$apply();
          });

          ctrl.showingJobOutput = false;
        };
      }]
    };
  }
]);


text:
package org.apache.flink.test.optimizer.examples;

import java.util.Arrays;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.Plan;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.operators.GenericDataSourceBase;
import org.apache.flink.api.common.operators.util.FieldList;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.optimizer.plan.Channel;
import org.apache.flink.optimizer.plan.OptimizedPlan;
import org.apache.flink.optimizer.plan.SingleInputPlanNode;
import org.apache.flink.optimizer.plan.SinkPlanNode;
import org.apache.flink.runtime.operators.DriverStrategy;
import org.apache.flink.runtime.operators.shipping.ShipStrategyType;
import org.apache.flink.runtime.operators.util.LocalStrategy;
import org.apache.flink.optimizer.util.CompilerTestBase;
import org.junit.Assert;
import org.junit.Test;

public class WordCountCompilerTest extends CompilerTestBase {

	private static final long serialVersionUID = 8988304231385358228L;

	/**
	 * This method tests the simple word count.
	 */
	@Test
	public void testWordCount() {
		checkWordCount(true);
		checkWordCount(false);
	}

	private void checkWordCount(boolean estimates) {

		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
		env.setParallelism(DEFAULT_PARALLELISM);

		// get input data
		DataSet<String> lines = env.readTextFile(IN_FILE).name("Input Lines");

		lines
			// dummy map
			.map(new MapFunction<String, Tuple2<String, Integer>>() {
				private static final long serialVersionUID = -3952739820618875030L;
				@Override
				public Tuple2<String, Integer> map(String v) throws Exception {
					return new Tuple2<>(v, 1);
				}
			}).name("Tokenize Lines")
			// count
				.groupBy(0).sum(1).name("Count Words")
			// discard
				.output(new DiscardingOutputFormat<Tuple2<String, Integer>>()).name("Word Counts");

		// get the plan and compile it
		Plan p = env.createProgramPlan();
		p.setExecutionConfig(new ExecutionConfig());

		OptimizedPlan plan;
		if (estimates) {
			GenericDataSourceBase<?,?> source = getContractResolver(p).getNode("Input Lines");
			setSourceStatistics(source, 1024*1024*1024*1024L, 24f);
			plan = compileWithStats(p);
		} else {
			plan = compileNoStats(p);
		}

		// get the optimizer plan nodes
		OptimizerPlanNodeResolver resolver = getOptimizerPlanNodeResolver(plan);
		SinkPlanNode sink = resolver.getNode("Word Counts");
		SingleInputPlanNode reducer = resolver.getNode("Count Words");
		SingleInputPlanNode mapper = resolver.getNode("Tokenize Lines");

		// verify the strategies
		Assert.assertEquals(ShipStrategyType.FORWARD, mapper.getInput().getShipStrategy());
		Assert.assertEquals(ShipStrategyType.PARTITION_HASH, reducer.getInput().getShipStrategy());
		Assert.assertEquals(ShipStrategyType.FORWARD, sink.getInput().getShipStrategy());

		Channel c = reducer.getInput();
		Assert.assertEquals(LocalStrategy.COMBININGSORT, c.getLocalStrategy());
		FieldList l = new FieldList(0);
		Assert.assertEquals(l, c.getShipStrategyKeys());
		Assert.assertEquals(l, c.getLocalStrategyKeys());
		Assert.assertTrue(Arrays.equals(c.getLocalStrategySortOrder(), reducer.getSortOrders(0)));

		// check the combiner
		SingleInputPlanNode combiner = (SingleInputPlanNode) reducer.getPredecessor();
		Assert.assertEquals(DriverStrategy.SORTED_GROUP_COMBINE, combiner.getDriverStrategy());
		Assert.assertEquals(l, combiner.getKeys(0));
		Assert.assertEquals(ShipStrategyType.FORWARD, combiner.getInput().getShipStrategy());

	}

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace Whathecode.System
{
	/// <summary>
	///   A helper class to do common <see cref = "Action" /> operations.
	/// </summary>
	/// <author>Steven Jeuris</author>
	public class ActionHelper
	{
		/// <summary>
		///   Lists all the possible <see cref = "Action">Action</see> delegates, link to the amount of parameters the action has.
		/// </summary>
		static readonly Dictionary<int, Type> ActionTypes = new Dictionary<int, Type>
		{
			{ 0, typeof( Action ) },
			{ 1, typeof( Action<> ) },
			{ 2, typeof( Action<,> ) },
			{ 3, typeof( Action<,,> ) },
			{ 4, typeof( Action<,,,> ) },
			{ 5, typeof( Action<,,,,> ) },
			{ 6, typeof( Action<,,,,,> ) },
			{ 7, typeof( Action<,,,,,,> ) },
			{ 8, typeof( Action<,,,,,,,> ) },
			{ 9, typeof( Action<,,,,,,,,> ) },
			{ 10, typeof( Action<,,,,,,,,,> ) },
			{ 11, typeof( Action<,,,,,,,,,,> ) },
			{ 12, typeof( Action<,,,,,,,,,,,> ) },
			{ 13, typeof( Action<,,,,,,,,,,,,> ) },
			{ 14, typeof( Action<,,,,,,,,,,,,,> ) },
			{ 15, typeof( Action<,,,,,,,,,,,,,,> ) },
			{ 16, typeof( Action<,,,,,,,,,,,,,,,> ) }
		};

		/// <summary>
		///   Returns the type of an Action delegate with the given amount of parameters.
		/// </summary>
		/// <param name = "numberOfParameters">The amount of parameters.</param>
		/// <returns>Type of the Action delegate with the given amount of parameters.</returns>
		public static Type GetActionType( int numberOfParameters )
		{
			Contract.Requires( numberOfParameters >= 0 && numberOfParameters <= 16 );

			return ActionTypes[ numberOfParameters ];
		}
	}
}


text:
var gulp = require('gulp');
var {spawn} = require('child_process');

gulp.task('foreman', function(callback) {
  spawn('nf', ['start', '-j', 'Procfile'], {stdio: 'inherit', env: process.env})
    .on('close', callback);
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>SpriteBatch - pixi.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 1.5.3

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AbstractFilter

AjaxRequest

AlphaMaskFilter

AssetLoader

AtlasLoader

autoDetectRenderer

BaseTexture

BitmapFontLoader

BitmapText

BlurFilter

CanvasGraphics

CanvasMaskManager

CanvasRenderer

CanvasTinter

Circle

ColorMatrixFilter

ColorStepFilter

DisplacementFilter

DisplayObject

DisplayObjectContainer

DotScreenFilter

Ellipse

EventTarget

FilterTexture

getRecommendedRenderer

Graphics

GrayFilter

ImageLoader

InteractionData

InteractionManager

InvertFilter

JsonLoader

MovieClip

NormalMapFilter

PixelateFilter

PixiFastShader

PixiShader

Point

Polygon

PolyK

PrimitiveShader

Rectangle

Rope

SepiaFilter

Spine

Sprite

SpriteBatch

SpriteSheetLoader

Stage

Strip

Text

Texture

TilingSprite

TwistFilter

WebGLFilterManager

WebGLGraphics

WebGLMaskManager

WebGLRenderer

WebGLShaderManager

WebGLSpriteBatch

PIXI

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

SpriteBatch Class

            Defined in: src/pixi/display/SpriteBatch.js:5

            Module: PIXI

The SpriteBatch class is a really fast version of the DisplayObjectContainer
built solely for speed, so use when you need a lot of sprites or particles.
And it's extremely easy to use :

   var container = new PIXI.SpriteBatch();

   stage.addChild(container);

   for(var i  = 0; i < 100; i++)
   {
       var sprite = new PIXI.Sprite.fromImage("myImage.png");
       container.addChild(sprite);
   }
And here you have a hundred sprites that will be renderer at the speed of light

Constructor

SpriteBatch

            (

                        texture

)

                Defined in

        src/pixi/display/SpriteBatch.js:5

Parameters:

                        texture
                        Texture

Index

Methods

Item Index

Methods

                                _renderCanvas

                                _renderWebGL

Methods

_renderCanvas

            (

                        renderSession

)

        private

                Defined in

        src/pixi/display/SpriteBatch.js:90

Renders the object using the Canvas renderer

Parameters:

                        renderSession
                        RenderSession

_renderWebGL

            (

                        renderSession

)

        private

                Defined in

        src/pixi/display/SpriteBatch.js:64

Renders the object using the WebGL renderer

Parameters:

                        renderSession
                        RenderSession


text:
package org.apache.ibatis.scripting.defaults;

import java.util.HashMap;

import org.apache.ibatis.builder.SqlSourceBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.session.Configuration;

/**
 * Static SqlSource. It is faster than {@link DynamicSqlSource} because mappings are
 * calculated during startup.
 *
 * @since 3.2.0
 * @author Eduardo Macarron
 */
public class RawSqlSource implements SqlSource {

  private final SqlSource sqlSource;

  public RawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?> parameterType) {
    this(configuration, getSql(configuration, rootSqlNode), parameterType);
  }

  public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
    Class<?> clazz = parameterType == null ? Object.class : parameterType;
    sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<String, Object>());
  }

  private static String getSql(Configuration configuration, SqlNode rootSqlNode) {
    DynamicContext context = new DynamicContext(configuration, null);
    rootSqlNode.apply(context);
    return context.getSql();
  }

  @Override
  public BoundSql getBoundSql(Object parameterObject) {
    return sqlSource.getBoundSql(parameterObject);
  }

}


text:
package io.dropwizard.jdbi.args;

import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.ArgumentFactory;

import java.time.LocalDate;

/**
 * An {@link ArgumentFactory} for {@link LocalDate} arguments.
 */
public class LocalDateArgumentFactory implements ArgumentFactory<LocalDate> {

    @Override
    public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) {
        return value instanceof LocalDate;
    }

    @Override
    public Argument build(Class<?> expectedType, LocalDate value, StatementContext ctx) {
        return new LocalDateArgument(value);
    }
}


text:
=begin

  Build Graph
  ===========

  Data:

  * observations (CSV)
  * variable definitions
  * priors (hash with prior values in the same order as the variable definitions)
  * graph

  Primary Course:

  User provides variable definitions and observations
  System updates the frequencies from observations
  System replaces zeroes with the default probability (1 / 3 orders of magnitude greater than the observation size)
  System normalizes the frequency table into a probability table
  System returns a factor

=end

require File.expand_path('../action_object', __FILE__)

module Fathom
  class BuildGraph < ActionObject

    attr_reader :variables, :observations, :priors

    def initialize(variables, observations, opts={})
      @variables    = variables
      @observations = observations
      @opts         = opts.with_indifferent_access
      @priors       = infer_priors
    end

    def variable_labels
      @variable_labels ||= variables.map(&:label)
    end

    def dependent_variable_labels
      @dependent_variable_labels ||= adjacency_list.map {|array| array[1]}.uniq
    end

    def independent_variable_labels
      @independent_variable_labels ||= variable_labels - dependent_variable_labels
    end

    def independent_variables
      @independent_variables ||= variables.select { |variable| independent_variable_labels.include?(variable.label) }
    end

    def dependent_variables
      @dependent_variables ||= variables - independent_variables
    end

    def adjacency_list
      @adjacency_list ||= variables.inject([]) do |array, variable|
        child_label = variable.label
        variable.parents.each do |parent_label|
          array << [parent_label, child_label]
        end
        array
      end.uniq
    end

    def factors
      @factors ||= priors + dependent_variables.map do |variable|
        parents = variables.select { |parent| variable.parents.include?(parent.label) }
        BuildDiscreteFactor.execute!([variable] + parents, parents.map(&:label), observations)
      end
    end

    def graph
      @graph ||= Graph.new({
        priors:         priors,
        factors:        factors,
        adjacency_list: adjacency_list
      })
    end
    alias_method :execute!, :graph

    def inspect
      @inspect ||= "BuildGraph (#{data.size}) #{header.inspect}"
    end

    protected

    def infer_priors
      independent_variables.map { |variable| build_prior_factor(variable) }
    end

    def build_prior_factor(variable)
      Factor.new(label: variable.label, table: build_prior_table(variable))
    end

    def default_prior_table(variable)
      @opts.fetch(:priors, {}).inject({}) do |hash, (label, array)|
        array = Array(array)
        array.each_with_index do |prior_value, i|
          hash[{label => variable.domain[i]}] = prior_value
        end
        hash
      end
    end

    def build_prior_table(variable)
      size = variable.domain.size
      keys = variable.domain.inject(default_prior_table(variable)) do |hash, value|
        hash[{variable.label => value}] ||= Rational(1,size)
        hash
      end
    end
    public :build_prior_table

  end
end


text:
CI test for use with Vagrant

Runs API test scripts on a Centos vm with rundeck build coming from bintray CI repo


text:
:root {
  --background-color: #000;
  --color: #fff;
  --timing: 150ms;
}

[data-tippy] {
  position: relative;
}

[data-tippy]::before,
[data-tippy]::after {
  position: absolute;
  display: block;
  opacity: 0;
  font-family: sans-serif;
  transform: translate(-50%, 0);
  transform-origin: top;
  top: 100%;
  left: 50%;
  pointer-events: none;
}

[data-tippy]::before {
  content: attr(data-tippy);
  color: var(--color);
  font-size: 14px;
  background-color: var(--background-color);
  z-index: 1;
  padding: 3px 6px;
  border-radius: 3px;
  white-space: nowrap;
  margin-top: 10px;
  font-weight: normal;
}

[data-tippy]::after {
  content: '';
  border: 5px solid transparent;
  border-bottom-color: var(--background-color);
}

[data-tippy]:hover::before,
[data-tippy]:hover::after {
  transform: translate(-50%, 0);
}

/* reset for other positions */

[data-tippy][data-tippy-pos]::before {
  top: auto;
  left: auto;
  margin-top: auto;
  transform: none;
}

[data-tippy][data-tippy-pos]::after {
  top: auto;
  left: auto;
  margin-top: auto;
  border-bottom-color: transparent;
  transform: none;
}

/* end reset */

/* up and down */

[data-tippy][data-tippy-pos='up']::before,
[data-tippy][data-tippy-pos='up']::after,
[data-tippy][data-tippy-pos='down']::before,
[data-tippy][data-tippy-pos='down']::after {
  left: 50%;
}

/* up */

[data-tippy][data-tippy-pos='up']::before,
[data-tippy][data-tippy-pos='up']::after {
  bottom: 100%;
  transform: translate(-50%, 0);
}

[data-tippy][data-tippy-pos='up']::before {
  margin-bottom: 10px;
}

[data-tippy][data-tippy-pos='up']::after {
  border-top-color: var(--background-color);
  border-bottom-color: transparent;
}

/* down */

[data-tippy][data-tippy-pos='down']::before,
[data-tippy][data-tippy-pos='down']::after {
  top: 100%;
  transform: translate(-50%, 0);
}

[data-tippy][data-tippy-pos='down']::before {
  margin-top: 10px;
}

[data-tippy][data-tippy-pos='down']::after {
	border-bottom-color: var(--background-color);
  border-top-color: transparent;
}

/* left and right */

[data-tippy][data-tippy-pos='left']::before,
[data-tippy][data-tippy-pos='left']::after,
[data-tippy][data-tippy-pos='right']::before,
[data-tippy][data-tippy-pos='right']::after {
  top: 50%;
}

/* left */

[data-tippy][data-tippy-pos='left']::before,
[data-tippy][data-tippy-pos='left']::after {
  right: 100%;
  transform: translate(0, -50%);
}

[data-tippy][data-tippy-pos='left']::before {
  margin-right: 10px;
}

[data-tippy][data-tippy-pos='left']::after {
  border-left-color: var(--background-color);
}

/* right */

[data-tippy][data-tippy-pos='right']::before,
[data-tippy][data-tippy-pos='right']::after {
  left: 100%;
  transform: translate(0, -50%);
}

[data-tippy][data-tippy-pos='right']::before {
  margin-left: 10px;
}

[data-tippy][data-tippy-pos='right']::after {
  border-right-color: var(--background-color);
}

/* hover */

[data-tippy]:hover::before,
[data-tippy]:hover::after {
  opacity: 1;
}

/* animated - fade (default) */

[data-tippy][data-tippy-animate]::before,
[data-tippy][data-tippy-animate]::after {
  transition: all var(--timing) ease-out;
  transition-delay: 0s;
}

[data-tippy][data-tippy-animate]:hover::before,
[data-tippy][data-tippy-animate]:hover::after {
  transition-delay: var(--timing);
}

/* animated - slide */

[data-tippy][data-tippy-animate='slide']::before,
[data-tippy][data-tippy-animate='slide']::after {
  transform: translate(-50%, -10px);
}

[data-tippy][data-tippy-animate='slide']:hover::before,
[data-tippy][data-tippy-animate='slide']:hover::after {
  transform: translate(-50%, 0);
}

[data-tippy][data-tippy-pos='up'][data-tippy-animate='slide']::before,
[data-tippy][data-tippy-pos='up'][data-tippy-animate='slide']::after {
  transform: translate(-50%, 10px);
}

[data-tippy][data-tippy-pos='down'][data-tippy-animate='slide']::before,
[data-tippy][data-tippy-pos='down'][data-tippy-animate='slide']::after {
  transform: translate(-50%, -10px);
}

[data-tippy][data-tippy-pos='up'][data-tippy-animate='slide']:hover::before,
[data-tippy][data-tippy-pos='up'][data-tippy-animate='slide']:hover::after,
[data-tippy][data-tippy-pos='down'][data-tippy-animate='slide']:hover::before,
[data-tippy][data-tippy-pos='down'][data-tippy-animate='slide']:hover::after {
  transform: translate(-50%, 0);
}

[data-tippy][data-tippy-pos='left'][data-tippy-animate='slide']::before,
[data-tippy][data-tippy-pos='left'][data-tippy-animate='slide']::after {
  transform: translate(10px, -50%);
}

[data-tippy][data-tippy-pos='right'][data-tippy-animate='slide']::before,
[data-tippy][data-tippy-pos='right'][data-tippy-animate='slide']::after {
  transform: translate(-10px, -50%);
}

[data-tippy][data-tippy-pos='left'][data-tippy-animate='slide']:hover::before,
[data-tippy][data-tippy-pos='left'][data-tippy-animate='slide']:hover::after,
[data-tippy][data-tippy-pos='right'][data-tippy-animate='slide']:hover::before,
[data-tippy][data-tippy-pos='right'][data-tippy-animate='slide']:hover::after {
  transform: translate(0, -50%);
}

/* animated - bubble */

[data-tippy][data-tippy-animate='bubble']::before,
[data-tippy][data-tippy-animate='bubble']::after {
  opacity: 1;
  visibility: hidden;
}

[data-tippy][data-tippy-animate='bubble']:hover::before,
[data-tippy][data-tippy-animate='bubble']:hover::after {
  visibility: visible;
}

[data-tippy][data-tippy-animate='bubble']::before {
  clip-path: circle(10% at 50% 0);
}

[data-tippy][data-tippy-animate='bubble']:hover::before {
  clip-path: circle(100% at 50%);
}

[data-tippy][data-tippy-pos='up'][data-tippy-animate='bubble']::before {
  clip-path: circle(10% at 50% 100%);
}

[data-tippy][data-tippy-pos='up'][data-tippy-animate='bubble']:hover::before {
  clip-path: circle(100% at 50%);
}

[data-tippy][data-tippy-pos='down'][data-tippy-animate='bubble']::before {
  clip-path: circle(10% at 50% 0);
}

[data-tippy][data-tippy-pos='down'][data-tippy-animate='bubble']:hover::before {
  clip-path: circle(100% at 50%);
}

[data-tippy][data-tippy-pos='left'][data-tippy-animate='bubble']::before {
  clip-path: circle(10% at 100% 50%);
}

[data-tippy][data-tippy-pos='left'][data-tippy-animate='bubble']:hover::before {
  clip-path: circle(100% at 50%);
}

[data-tippy][data-tippy-pos='right'][data-tippy-animate='bubble']::before {
  clip-path: circle(10% at 0 50%);
}

[data-tippy][data-tippy-pos='right'][data-tippy-animate='bubble']:hover::before {
  clip-path: circle(100% at 50%);
}

/* force display */

[data-tippy][data-tippy-visible]::before,
[data-tippy][data-tippy-visible]::after {
  opacity: 1;
  visibility: visible;
}

/* sizes */

[data-tippy][data-tippy-size='tiny']::before {
  font-size: 10px;
}

[data-tippy][data-tippy-size='small']::before {
  font-size: 12px;
}

[data-tippy][data-tippy-size='large']::before {
  font-size: 16px;
}

[data-tippy][data-tippy-size='jumbo']::before {
  font-size: 20px;
}


text:
<meta charset="utf-8">
<title>{{ name }} - episodes</title>
<link rel="stylesheet" href="/podcached/podcached.css"/>

{{ name }}

{{ description }}

{% for episode in episodes %}

{{ episode.title }}

    Published: {{ episode.date }}
    {% if episode.duration %}
    (Duration: {{ episode.duration }})
    {% endif %}

{{ episode.description }}

{% endfor %}


text:
<?php
namespace Able\Prototypes;

interface ISettable {

	/**
	 * @param string $name
	 * @param $value
	 * @return void
	 */
	public function __set(string $name, $value);

	/**
	 * @param string $name
	 * @return void
	 */
	public function __unset(string $name);

}


text:
import { createStore,applyMiddleware } from 'redux'
import thunk from 'redux-thunk';
import QuizActions from './reducers/answer'

const createStoreWithMiddleware = applyMiddleware(
  thunk
)(createStore);

export default createStoreWithMiddleware(QuizActions)


text:
import numpy as np

# helper methods for printing scores

def get_score_summary(name, scores, weighted_average):
    summary = '%.3f-%.3f (avg=%.5f mean=%.5f std=%.5f)' % (min(scores), max(scores), weighted_average,
                                                           np.mean(scores), np.std(scores))
    score_list = ['%.3f' % score for score in scores]
    return '%s %s [%s]' % (name, summary, ','.join(score_list))

def print_results(summaries):
    summaries.sort(cmp=lambda x,y: cmp(x[1], y[1]))
    if len(summaries) > 1:
        print 'summaries'
        for s, mean in summaries:
            print s


text:
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Serialization;
using Zenject.Internal;

namespace Zenject
{
    public class SceneDecoratorContext : Context
    {
        [SerializeField]
        List<MonoInstaller> _lateInstallers = new List<MonoInstaller>();

        [SerializeField]
        List<MonoInstaller> _lateInstallerPrefabs = new List<MonoInstaller>();

        [SerializeField]
        List<ScriptableObjectInstaller> _lateScriptableObjectInstallers = new List<ScriptableObjectInstaller>();

        public IEnumerable<MonoInstaller> LateInstallers
        {
            get
            {
                return _lateInstallers;
            }
            set
            {
                _lateInstallers.Clear();
                _lateInstallers.AddRange(value);
            }
        }

        public IEnumerable<MonoInstaller> LateInstallerPrefabs
        {
            get
            {
                return _lateInstallerPrefabs;
            }
            set
            {
                _lateInstallerPrefabs.Clear();
                _lateInstallerPrefabs.AddRange(value);
            }
        }

        public IEnumerable<ScriptableObjectInstaller> LateScriptableObjectInstallers
        {
            get
            {
                return _lateScriptableObjectInstallers;
            }
            set
            {
                _lateScriptableObjectInstallers.Clear();
                _lateScriptableObjectInstallers.AddRange(value);
            }
        }

        [FormerlySerializedAs("SceneName")]
        [SerializeField]
        string _decoratedContractName = null;

        DiContainer _container;

        public string DecoratedContractName
        {
            get { return _decoratedContractName; }
        }

        public override DiContainer Container
        {
            get
            {
                Assert.IsNotNull(_container);
                return _container;
            }
        }

        public override IEnumerable<GameObject> GetRootGameObjects()
        {
            // This method should never be called because SceneDecoratorContext's are not bound
            // to the container
            throw Assert.CreateException();
        }

        public void Initialize(DiContainer container)
        {
            Assert.IsNull(_container);
            _container = container;

            foreach (var instance in GetInjectableMonoBehaviours().Cast<object>())
            {
                container.QueueForInject(instance);
            }
        }

        public void InstallDecoratorSceneBindings()
        {
            _container.Bind<SceneDecoratorContext>().FromInstance(this);
            InstallSceneBindings();
        }

        public void InstallDecoratorInstallers()
        {
            InstallInstallers();
        }

        protected override IEnumerable<MonoBehaviour> GetInjectableMonoBehaviours()
        {
            return ZenUtilInternal.GetInjectableMonoBehaviours(this.gameObject.scene);
        }

        public void InstallLateDecoratorInstallers()
        {
            InstallInstallers(new List<InstallerBase>(), _lateScriptableObjectInstallers, _lateInstallers, _lateInstallerPrefabs);
        }
    }
}

#endif


text:
<?php

namespace App\Models\Entities;

class Productworkingstate extends \Illuminate\Database\Eloquent\Model {

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'description', 'check', 'support'
    ];

    public function products() {
        return $this->belongsToMany('App\Models\Entities\Product', 'product_productworkingstate')->whereNull('product_productworkingstate.deleted_at')->withTimestamps();

    }
}


text:
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using DesktopWidgets.Classes;
using DesktopWidgets.Events;
using DesktopWidgets.Helpers;
using DesktopWidgets.Stores;
using DesktopWidgets.WidgetBase;
using DesktopWidgets.WidgetBase.Settings;
using DesktopWidgets.WidgetBase.ViewModel;
using WpfAppBar;

namespace DesktopWidgets.View
{
    /// <summary>
    ///     Interaction logic for View.xaml
    /// </summary>
    public partial class WidgetView : Window
    {
        private readonly MouseChecker _mouseChecker;
        public readonly WidgetSettingsBase Settings;
        public readonly UserControl UserControl;
        private DispatcherTimer _introTimer;
        private ABEdge _currentAppBarEdge = ABEdge.None;
        private IntroData _lastIntroData;
        public Action CloseAction;

        public WidgetView(WidgetId id, WidgetViewModelBase viewModel, UserControl userControl, bool systemStartup)
        {
            InitializeComponent();

            Opacity = 0;
            Hide();

            Id = id;
            Settings = id.GetSettings();
            ViewModel = viewModel;
            UserControl = userControl;

            SetupWidgetControl();

            SetScrollPosition();

            SetupFrame();

            ViewModel.View = this;

            _mouseChecker = new MouseChecker(this, Settings);

            if (!systemStartup && Settings.ShowIntroOnLaunch)
            {
                _mouseChecker.QueueIntro = new IntroData { ExecuteFinishAction = false };
            }

            DataContext = ViewModel;

            _mouseChecker.Start();

            ViewModel.OnLoad();

            HasLoaded = true;
        }

        public bool HasLoaded { private get; set; }
        public bool HasSourceLoaded { private get; set; }

        public WidgetViewModelBase ViewModel { get; set; }

        public bool IsContextMenuOpen => ViewModel.IsContextMenuOpen;

        public WidgetId Id { get; }
        public bool AnimationRunning { get; set; }

        public new bool IsVisible => Visibility == Visibility.Visible && Opacity > 0.99;

        public bool IsIdle => Settings.DetectIdle && Settings.ActiveTimeEnd <= DateTime.Now;

        public bool IsClosed { get; set; }

        public Win32App ThisApp { get; set; }

        public bool IsRefreshing { get; set; }

        private void SetupWidgetControl()
        {
            UserControl.Style = (Style)Resources["UserControlStyle"];
            MainContentContainer.Content = UserControl;
            var contextMenu = (ContextMenu)
                (UserControl.TryFindResource("WidgetContextMenu") ?? TryFindResource("WidgetContextMenu"));
            contextMenu.DataContext = ViewModel;
            MainContentContainer.ContextMenu = contextMenu;
            UserControl.MouseDown += Widget_OnMouseDown;
        }

        private void SetupFrame()
        {
            if (Settings.Style.ShowLeftFrame)
            {
                if (FrameContainerLeft.Child == null && (UserControl.TryFindResource("FrameLeft") is Grid frameLeft))
                {
                    FrameContainerLeft.Child = frameLeft;
                    FrameContainerLeft.Visibility = Visibility.Visible;
                }
            }
            else
            {
                FrameContainerLeft.Visibility = Visibility.Collapsed;
            }

            if (Settings.Style.ShowRightFrame)
            {
                if (FrameContainerRight.Child == null && (UserControl.TryFindResource("FrameRight") is Grid frameRight))
                {
                    FrameContainerRight.Child = frameRight;
                    FrameContainerRight.Visibility = Visibility.Visible;
                }
            }
            else
            {
                FrameContainerRight.Visibility = Visibility.Collapsed;
            }

            if (Settings.Style.ShowTopFrame)
            {
                if (FrameContainerTop.Child == null && (UserControl.TryFindResource("FrameTop") is Grid frameTop))
                {
                    FrameContainerTop.Child = frameTop;
                    FrameContainerTop.Visibility = Visibility.Visible;
                }
            }
            else
            {
                FrameContainerTop.Visibility = Visibility.Collapsed;
            }

            if (Settings.Style.ShowBottomFrame)
            {
                if (FrameContainerBottom.Child == null && (UserControl.TryFindResource("FrameBottom") is Grid frameBottom))
                {
                    FrameContainerBottom.Child = frameBottom;
                    FrameContainerBottom.Visibility = Visibility.Visible;
                }
            }
            else
            {
                FrameContainerBottom.Visibility = Visibility.Collapsed;
            }
        }

        private void SetScrollPosition()
        {
            MainContentContainer.ScrollToHorizontalOffset(Settings.ScrollHorizontalOffset);
            MainContentContainer.ScrollToVerticalOffset(Settings.ScrollVerticalOffset);
        }

        private void SaveScrollPosition()
        {
            Settings.ScrollHorizontalOffset = MainContentContainer.ContentHorizontalOffset;
            Settings.ScrollVerticalOffset = MainContentContainer.ContentVerticalOffset;
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            if (!HasLoaded)
            {
                return;
            }

            var hwnd = new WindowInteropHelper(this).Handle;
            var widgetSrc = HwndSource.FromHwnd(hwnd);

            widgetSrc?.AddHook(WndProc);

            ThisApp = new Win32App(hwnd);

            if (Settings.Unclickable)
            {
                ThisApp.SetWindowExTransparent();
            }

            UpdateUi(false);

            ViewModel.OnUiLoad();

            HasSourceLoaded = true;
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == SingleInstanceHelper.WM_SHOWAPP)
            {
                ShowIntro();
            }

            return IntPtr.Zero;
        }

        private void HideIntro(bool checkIdleStatus = true)
        {
            _mouseChecker.KeepOpenForIntro = false;
            if (Settings.OpenMode != OpenMode.AlwaysOpen)
            {
                _mouseChecker.Hide(checkIdleStatus: checkIdleStatus);
            }
        }

        public void CancelIntro()
        {
            if (!_introTimer.IsEnabled && !_mouseChecker.KeepOpenForIntro)
            {
                return;
            }
            HideIntro(false);
        }

        public void ShowIntro(IntroData introData = null)
        {
            _mouseChecker.QueueIntro = null;
            if (introData == null)
            {
                introData = new IntroData();
            }
            if (App.IsWorkstationLocked || FullScreenHelper.DoesMonitorHaveFullscreenApp(ViewModel.GetScreenBounds()))
            {
                _mouseChecker.QueueIntro = introData;
                return;
            }
            _lastIntroData = introData;
            if (_introTimer == null)
            {
                _introTimer = new DispatcherTimer();
                _introTimer.Tick += delegate
                {
                    _introTimer.Stop();
                    if (_lastIntroData.HideOnFinish)
                    {
                        HideIntro();
                    }
                    if (_lastIntroData.ExecuteFinishAction)
                    {
                        ViewModel.OnIntroEnd();
                    }
                };
            }

            _introTimer.Stop();
            _introTimer.Interval =
                TimeSpan.FromMilliseconds(introData.Duration == -1 ? Settings.IntroDuration : introData.Duration);
            if (_mouseChecker.KeepOpenForIntro && introData.Reversable)
            {
                HideIntro(false);
            }
            else if (introData.Duration != 0)
            {
                _mouseChecker.KeepOpenForIntro = true;
                _introTimer.Start();
                ViewModel.OnIntro();
                _mouseChecker.Show(activate: introData.Activate);
            }
        }

        public void ShowUi()
        {
            _mouseChecker.Show();
        }

        public void HideUi(bool checkIdleStatus = true, bool checkHideStatus = true)
        {
            if (Settings.OpenMode != OpenMode.AlwaysOpen)
            {
                _mouseChecker.Hide(checkIdleStatus: checkIdleStatus, checkHideStatus: checkHideStatus);
            }
        }

        public void Dismiss()
        {
            HideUi(false, false);
            ViewModel.OnDismiss();
        }

        public void UpdateUi(
            bool resetContext = true,
            bool updateNonUi = true,
            bool updateOpacity = true,
            bool? isDocked = null,
            HorizontalAlignment? dockHorizontalAlignment = null,
            VerticalAlignment? dockVerticalAlignment = null)
        {
            if (!IsVisible)
            {
                Refresh(resetContext, updateNonUi, false, updateOpacity);
            }
            else
            {
                this.Animate(AnimationMode.Hide, false, null,
                    () => Refresh(resetContext, updateNonUi, true, updateOpacity),
                    isDocked,
                    dockHorizontalAlignment,
                    dockVerticalAlignment);
            }
        }

        private void UpdatePositionAndLocation()
        {
            UpdateLayout();
            ViewModel.UpdateSize();
            UpdateLayout();
            ViewModel.UpdatePosition();
            UpdateLayout();
            ViewModel.UpdatePosition();
            UpdateLayout();
        }

        private void SetAsAppBar(ABEdge edge)
        {
            _currentAppBarEdge = edge;
            AppBarFunctions.SetAppBar(this, edge, topMost: Settings.Topmost);
        }

        private ABEdge GetAppBarEdge()
        {
            if (Settings.IsAppBar && Settings.IsDocked)
            {
                switch (Settings.HorizontalAlignment)
                {
                    case HorizontalAlignment.Left:
                        return ABEdge.Left;
                    case HorizontalAlignment.Right:
                        return ABEdge.Right;
                    default:
                        switch (Settings.VerticalAlignment)
                        {
                            case VerticalAlignment.Top:
                                return ABEdge.Top;
                            case VerticalAlignment.Bottom:
                                return ABEdge.Bottom;
                        }
                        break;
                }
            }
            return ABEdge.None;
        }

        private void Refresh(bool resetContext, bool updateNonUi, bool showIntro, bool updateOpacity)
        {
            IsRefreshing = true;
            var isVisible = IsVisible;
            Opacity = 0;
            if (!isVisible)
            {
                Show();
            }

            if (resetContext)
            {
                DataContext = null;
                DataContext = ViewModel;
            }

            Title = Id.GetName();

            SetupFrame();

            var appBarEdge = GetAppBarEdge();
            if (appBarEdge != _currentAppBarEdge)
            {
                SetAsAppBar(appBarEdge);
            }

            if (_currentAppBarEdge == ABEdge.None)
            {
                UpdatePositionAndLocation();
            }

            if (updateNonUi)
            {
                UpdateTimers();
                ViewModel.ReloadTimers();
            }

            ViewModel.OnRefresh();

            if (!isVisible)
            {
                Hide();
            }
            if (updateOpacity)
            {
                Opacity = 1;
            }

            IsRefreshing = false;

            if (showIntro && !_mouseChecker.KeepOpenForIntro)
            {
                ShowIntro();
            }

            foreach (var eventPair in App.WidgetsSettingsStore.EventActionPairs)
            {
                var evnt = eventPair.Event as WidgetRefreshEvent;
                if (evnt == null || eventPair.Disabled)
                {
                    continue;
                }
                eventPair.Action.Execute();
            }
        }

        private void UpdateTimers()
        {
            _mouseChecker.UpdateIntervals();
            if (_mouseChecker.IsRunning)
            {
                _mouseChecker.Stop();
                _mouseChecker.Start();
            }
        }

        private void WidgetView_OnClosing(object sender, CancelEventArgs e)
        {
            try
            {
                IsClosed = true;

                _introTimer?.Stop();
                _introTimer = null;

                _mouseChecker?.Dispose();

                HotkeyStore.RemoveHotkey(Id.Guid);

                ViewModel?.OnClose();
                ViewModel = null;

                SaveScrollPosition();

                if (_currentAppBarEdge != ABEdge.None)
                {
                    SetAsAppBar(ABEdge.None);
                }
            }
            catch
            {
                // ignored
            }

            App.WidgetViews.Remove(this);

            CloseAction?.Invoke();
        }

        private void WidgetView_OnLocationChanged(object sender, EventArgs e)
        {
            if (HasSourceLoaded && !IsRefreshing && Settings.SnapToScreenEdges && !Settings.IsDocked)
            {
                var newLoc = this.Snap(true, Settings.IgnoreAppBars);
                ViewModel.Left = newLoc.X;
                ViewModel.Top = newLoc.Y;
            }
        }

        private void Widget_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (
                Mouse.LeftButton == MouseButtonState.Pressed
                && !Settings.IsDocked
                && Settings.DragToMove)
            {
                DragMove();
            }
        }

        private void ActionBar_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (
                Mouse.LeftButton == MouseButtonState.Pressed
                && !Settings.IsDocked
                && Settings.DragActionBarToMove)
            {
                DragMove();
            }
        }

        private void btnMenu_OnClick(object sender, RoutedEventArgs e)
        {
            MainContentContainer.ContextMenu.IsOpen = true;
        }

        private void btnReload_OnClick(object sender, RoutedEventArgs e)
        {
            Id.Reload();
        }

        public new void Show()
        {
            Visibility = Visibility.Visible;
            ThisApp?.BringToFront();
        }

        public new void Hide()
        {
            Visibility = Visibility.Hidden;
        }

        private void btnDismiss_OnClick(object sender, RoutedEventArgs e)
        {
            Dismiss();
        }

        public void FocusMainElement()
        {
            GetMainElement()?.Focus();
        }

        public UIElement GetMainElement()
        {
            return UserControl.FindName("MainElement") as UIElement;
        }

        public void CloseAnimation()
        {
            this.Animate(AnimationMode.Hide, false, null, Close);
        }

        private void WidgetView_OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (!IsRefreshing && _currentAppBarEdge == ABEdge.None)
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)ViewModel.UpdatePosition);
            }
        }

        public void ExecuteSpecialAction()
        {
            ViewModel.ExecuteSpecialAction();
        }

        private void btnMute_OnClick(object sender, RoutedEventArgs e)
        {
            Id.Mute(Properties.Settings.Default.MuteDuration);
        }
    }
}


text:
FROM mysql:5.7.10

ENV MYSQL_ROOT_PASSWORD=rootPassword
ENV MYSQL_USER=testUser
ENV MYSQL_PASSWORD=password


text:
"""
    SoftLayer.tests.managers.ordering_tests
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :license: MIT, see LICENSE for more details.
"""
import SoftLayer
from SoftLayer import testing
from SoftLayer.testing import fixtures

class OrderingTests(testing.TestCase):

    def set_up(self):
        self.ordering = SoftLayer.OrderingManager(self.client)

    def test_get_package_by_type_returns_no_outlet_packages(self):
        packages = self._get_server_packages()
        filtered_packages = self.ordering.filter_outlet_packages(packages)

        for package_id in [27, 28]:
            self._assert_package_id_not_present(package_id, filtered_packages)

    def _get_server_packages(self):
        return self.ordering.get_packages_of_type(['BARE_METAL_CPU'])

    def _assert_package_id_not_present(self, package_id, packages):
        package_ids = []
        for package in packages:
            package_ids.append(package['id'])

        self.assertNotIn(package_id, package_ids)

    def test_get_active_packages(self):
        packages = self._get_server_packages()
        filtered_packages = self.ordering.get_only_active_packages(packages)

        for package_id in [15]:
            self._assert_package_id_not_present(package_id, filtered_packages)

    def test_get_package_by_type_returns_if_found(self):
        package_type = "BARE_METAL_CORE"
        mask = "mask[id, name]"
        package = self.ordering.get_package_by_type(package_type, mask)
        self.assertIsNotNone(package)

    def test_get_package_by_type_returns_none_if_not_found(self):
        mock = self.set_mock('SoftLayer_Product_Package', 'getAllObjects')
        mock.return_value = []

        package = self.ordering.get_package_by_type("PIZZA_FLAVORED_SERVERS")

        self.assertIsNone(package)

    def test_get_package_id_by_type_returns_valid_id(self):
        mock = self.set_mock('SoftLayer_Product_Package', 'getAllObjects')
        mock.return_value = [
            {'id': 46, 'name': 'Virtual Servers',
             'description': 'Virtual Server Instances',
             'type': {'keyName': 'VIRTUAL_SERVER_INSTANCE'}, 'isActive': 1},
        ]

        package_type = "VIRTUAL_SERVER_INSTANCE"
        package_id = self.ordering.get_package_id_by_type(package_type)

        self.assertEqual(46, package_id)

    def test_get_package_id_by_type_fails_for_nonexistent_package_type(self):
        mock = self.set_mock('SoftLayer_Product_Package', 'getAllObjects')
        mock.return_value = []

        with self.assertRaises(ValueError):
            self.ordering.get_package_id_by_type("STRAWBERRY_FLAVORED_SERVERS")

    def test_get_order_container(self):
        container = self.ordering.get_order_container(1234)
        quote = self.ordering.client['Billing_Order_Quote']
        container_fixture = quote.getRecalculatedOrderContainer(id=1234)
        self.assertEqual(container, container_fixture['orderContainers'][0])

    def test_get_quotes(self):
        quotes = self.ordering.get_quotes()
        quotes_fixture = self.ordering.client['Account'].getActiveQuotes()
        self.assertEqual(quotes, quotes_fixture)

    def test_get_quote_details(self):
        quote = self.ordering.get_quote_details(1234)
        quote_service = self.ordering.client['Billing_Order_Quote']
        quote_fixture = quote_service.getObject(id=1234)
        self.assertEqual(quote, quote_fixture)

    def test_verify_quote(self):
        result = self.ordering.verify_quote(1234,
                                            [{'hostname': 'test1',
                                              'domain': 'example.com'}],
                                            quantity=1)

        self.assertEqual(result, fixtures.SoftLayer_Product_Order.verifyOrder)
        self.assert_called_with('SoftLayer_Product_Order', 'verifyOrder')

    def test_order_quote(self):
        result = self.ordering.order_quote(1234,
                                           [{'hostname': 'test1',
                                             'domain': 'example.com'}],
                                           quantity=1)

        self.assertEqual(result, fixtures.SoftLayer_Product_Order.placeOrder)
        self.assert_called_with('SoftLayer_Product_Order', 'placeOrder')

    def test_generate_order_template(self):
        result = self.ordering.generate_order_template(
            1234, [{'hostname': 'test1', 'domain': 'example.com'}], quantity=1)
        self.assertEqual(result, {'presetId': None,
                                  'hardware': [{'domain': 'example.com',
                                                'hostname': 'test1'}],
                                  'useHourlyPricing': '',
                                  'packageId': 50,
                                  'prices': [{'id': 1921}],
                                  'quantity': 1})

    def test_generate_order_template_extra_quantity(self):
        with self.assertRaises(ValueError):
            self.ordering.generate_order_template(1234, [], quantity=1)


text:
using System;

using Windows.Foundation.Diagnostics;

using EnergonSoftware.BackpackPlanner.Core.Logging;

namespace EnergonSoftware.BackpackPlanner.Windows.Logging
{
    internal sealed class WindowsLogger : ILogger, IDisposable
    {
        private readonly ILoggingChannel _channel;
        private readonly ILoggingSession _session;

        public WindowsLogger()
        {
            _channel = new LoggingChannel("BackpackPlannerChannel", null);
            _session = new LoggingSession("BackpackPlannerSession");

            _session.AddLoggingChannel(_channel);
        }

        ~WindowsLogger()
        {
            Dispose(false);
        }

#region Dispose
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if(disposing) {
                _channel.Dispose();
                _session.Dispose();
            }
        }
#endregion

        public void Debug(string message)
        {
            _channel.LogMessage(message, LoggingLevel.Verbose);
        }

        public void Debug(string message, Exception ex)
        {
            // TODO
            _channel.LogMessage(message, LoggingLevel.Verbose);
        }

        public void Info(string message)
        {
            _channel.LogMessage(message, LoggingLevel.Information);
        }

        public void Info(string message, Exception ex)
        {
            // TODO
            _channel.LogMessage(message, LoggingLevel.Information);
        }

        public void Warn(string message)
        {
            _channel.LogMessage(message, LoggingLevel.Warning);
        }

        public void Warn(string message, Exception ex)
        {
            // TODO
            _channel.LogMessage(message, LoggingLevel.Warning);
        }

        public void Error(string message)
        {
            _channel.LogMessage(message, LoggingLevel.Error);
        }

        public void Error(string message, Exception ex)
        {
            // TODO
            _channel.LogMessage(message, LoggingLevel.Error);
        }
    }
}


text:
This tutorial is a walkthrough of Deployment Manager best practices. As you complete this guide, you will learn techniques to build complex deployments:

+   Creating a deployment configuration
+   Deploying resources
+   Using templates
+   Using helper scripts

After completing this tutorial, you can apply these techniques to carry out tasks such as:

+   Creating and managing Google Cloud resources using templates
+   Harnessing templates to reuse deployment paradigms
+   Deploying multiple resources at once
+   Configuring Google Cloud resources such as Cloud Storage, Compute Engine, and Cloud SQL to work together

This tutorial assumes that you are familiar with YAML syntax and are comfortable running commands in a Linux terminal.

### Select a project

Select a Google Cloud project to use for this tutorial.

<walkthrough-project-setup></walkthrough-project-setup>

## Setup

Every command requires a project ID. Set a default project ID so you do not need to provide it every time.

```sh
gcloud config set project {{project-id}}
```

Enable the Compute Engine and Deployment Manager APIs, which you will need for this tutorial.

```sh
gcloud services enable compute.googleapis.com deploymentmanager.googleapis.com
```

## Understanding configurations

A **configuration** defines the structure of a deployment. You must specify a configuration to create a deployment.

In this step, you will access a configuration that creates a deployment with two instances. An **instance** is one of several kinds of resources you can deploy with Deployment Manager.

## Access a configuration

To access the configuration, first use the following command:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/step2_create_a_configuration
```

Next, open the file `two-vms.yaml`:

```sh
cloudshell edit two-vms.yaml
```

You will now be able to view your configuration file, which has two resources: `the-first-vm` and `the-second-vm`.  Note that each resource has a `name`, `type`, and `properties` field.

### Update your project ID

Replace all instances of "MY_PROJECT" in the file with your project ID:

```sh
sed -i -e 's/MY_PROJECT/{{project-id}}/g' two-vms.yaml
```

### Looking ahead: deploying resources

You can use this configuration file to create a deployment. To learn how to deploy the resources in your configuration, continue to the next step.

## Deploying your resources

A **deployment** creates a set of resources defined in a configuration. Since a deployment contains the resources defined in the configuration, your deployment in this tutorial will have two virtual machine instances.

## Deploy the configuration

Run this command to deploy your configuration:

```sh
gcloud deployment-manager deployments create deployment-with-2-vms --config two-vms.yaml
```

Wait for the indication that you successfully created the deployment (note that your actual operation IDs will differ):

```
Waiting for create operation-1432319707382-516afeb5d00f1-b864f0e7-b7103978...done.
Create operation operation-1432319707382-516afeb5d00f1-b864f0e7-b7103978 completed successfully.
NAME           TYPE                 STATE      ERRORS  INTENT
the-first-vm   compute.v1.instance  COMPLETED  []
the-second-vm  compute.v1.instance  COMPLETED  []
```

## View the deployment

Run the following command to view the deployment. You will see a list of each resource in the deployment, along with the resource type, unique resource ID, resource name, and resource creation status:

```sh
gcloud deployment-manager deployments describe deployment-with-2-vms
```

### View deployment resources

You can view a list of resources to quickly see which resource might be causing the issue.

To get a list of deployment resources, run:

```sh
gcloud deployment-manager resources list --deployment deployment-with-2-vms
```

## Delete your deployment

You won't use this deployment for the remainder of the tutorial. Since Compute Engine resources incur charges, you should delete this deployment. Deleting a deployment also deletes all the resources in a deployment.

**If you don't delete the deployment, you will run into conflicts with future examples.**

To delete this deployment:

```sh
gcloud deployment-manager deployments delete deployment-with-2-vms
```

### Looking ahead: references

Next, use references to improve troubleshooting and to access properties of other resources in your deployment.

## Understanding the benefits of references

You can use **references** to define the properties of your configuration or templates instead of directly providing values.

With references, you can access properties that are not defined until the resource is created. For example, when you define a virtual machine in your configuration, you do not know its IP address. However, you can create a reference to the IP address.

Next, you will examine an updated `two-vms.yaml` that contains a network, as well as virtual machine instances that reference the network.

## Exploring the new `two-vms.yaml`

First, run the following command to open your home directory:

```sh
cd
```

To open the new `two-vms.yaml` file with the network and references, first use the following command:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/step4_use_references
```

Then, open the `two-vms.yaml` file:

```sh
cloudshell edit two-vms.yaml
```

### Viewing the reference to a network

In the properties section of both of your virtual machine instances, the value of `network` is replaced with a reference to the new network's `selfLink` property.

## Deploy your new configuration

### Update your project ID

Replace all instances of "MY_PROJECT" in `two-vms.yaml` with your project ID:

```sh
sed -i -e 's/MY_PROJECT/{{project-id}}/g' two-vms.yaml
```

### Deploy your configuration

Deploy your configuration with the following command:

```sh
gcloud deployment-manager deployments create deployment-with-references --config two-vms.yaml
```

To view your deployment, use the following command:

```sh
gcloud deployment-manager deployments describe deployment-with-references
```

## Delete Your Deployment

Once again, you will want to delete the deployment to avoid charges. Run the following command to delete the deployment:

```sh
gcloud deployment-manager deployments delete deployment-with-references
```

### Looking ahead

To maximize efficiency while building large configurations, follow best practices such as using variables and templates.

In the next step, you will learn about templates and how they enable flexible, dynamic configurations.

## Exploring the power of templates

While developing an application, you will most likely require complex architectures. Therefore, we recommend that you break your configuration into templates.

A **template** is a separate file that defines a set of resources. You can reuse templates across different deployments, which creates consistency across complex deployments.

You can use Python or Jinja2 to create templates for Deployment Manager. We recommend that you use Python templates, because Python allows for greater flexibility and more features as you scale your application.

Your next task is to create a Python template using the contents of the configuration you created earlier in this tutorial.

## Examining a template

First, run the following command to open your home directory:

```sh
cd
```

Next, change directories with the following command:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/step5_create_a_template/python
```

Then, open the `vm-template.py` file:

```sh
cloudshell edit vm-template.py
```

Replace all instances of "MY_PROJECT" in the file with your project ID:

```sh
sed -i -e 's/MY_PROJECT/{{project-id}}/g' vm-template.py
```

## Editing a second template

There is a second template in this directory called `vm-template-2.py`. Like `vm-template.py`, `vm-template-2.py` creates a virtual machine.

To view `vm-template-2.py`, run the following command:

```sh
cloudshell edit vm-template-2.py
```

Replace all instances of "MY_PROJECT" in the file with your project ID:

```sh
sed -i -e 's/MY_PROJECT/{{project-id}}/g' vm-template-2.py
```

## Importing templates

Open the `two-vms.yaml` file in this directory with the following command:

```sh
cloudshell edit two-vms.yaml
```

In this updated file, the templates are imported at the top of the file. The properties of the resources are replaced with the names of the templates.

## Naming resources

When you use a template, your resource names are defined using the `name` field provided in the template, not the name in the configuration file.

For example, in this case, the virtual machine instances are created using the names in the templates you created, "the-first-vm" and "the-second-vm." The values "vm-1" and "vm-2," defined in the configuration, are used to name an instantiation of the template, but are not resource names, unless you decide to use environment variables to set both names to be the same.

## View the deployment

Save your configuration and deploy it:

```sh
 gcloud deployment-manager deployments create deployment-with-templates --config two-vms.yaml
```

To view your deployment, run the following command:

```sh
 gcloud deployment-manager deployments describe deployment-with-templates
```

## Delete the deployment

Once again, you will want to delete the deployment to avoid charges. Run the following command to delete the deployment:

```sh
gcloud deployment-manager deployments delete deployment-with-templates
```

### Looking ahead: using multiple templates

Next, combine templates so that your configuration only calls one template to deploy all your resources.

## Using multiple templates

Next, you will explore a template that imports other templates.

After incorporating these templates, your configuration only needs to call a single template to create a deployment with all of these resources.

## Exploring a template that uses multiple templates

The template in this example creates a Compute Engine with a network and a firewall.

### Access the template

First, use the following command to open your home directory:

```sh
cd
```

Next, use the following command:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/step6_use_multiple_templates/python
```

To view this template, run the following command:

```sh
cloudshell edit compute-engine-template.py
```

### Viewing the template's resources

The template's resources include `vm-template.py`, `vm-template-2.py`, `network-template.py`, and `firewall-template.py`. You can view these templates using the `cloudshell edit {file-name}` command.

## Importing many templates into a configuration

Now, you will explore a configuration that uses the template you previously viewed.

To see this file, run the following command:

 ```sh
cloudshell edit config-with-many-templates.yaml
```

Notice that the configuration did not directly call the other templates. However, the other templates are imported because `compute-engine-template.py` depends on the other templates to be valid.

## Deploy your configuration

Save your configuration and deploy it:

```sh
gcloud deployment-manager deployments create deployment-with-many-templates --config config-with-many-templates.yaml
```

To view your deployment, run the following command:

```sh
gcloud deployment-manager deployments describe deployment-with-many-templates
```

## Delete your deployment

Once again, you will want to delete the deployment to avoid charges. Run the following command to delete the deployment:

```sh
gcloud deployment-manager deployments delete deployment-with-many-templates
```

### Looking ahead: exploring template potential

Next, you will learn how to maximize template features such as custom properties to benefit your application development.

## Learning about template properties

An advantage of using templates is the ability to create and define custom properties, which enable the reuse of templates across zones, regions, and projects.

Template properties are arbitrary variables. Any configuration file or template file can provide a value for a template property without modifying the template. Therefore, you can change a property's value for various configurations without changing the template itself.

To reference an arbitrary value, use this syntax in a template:

```sh
    context.properties["property-name"]
```

## Learning about environment variables

Environment variables are predefined variables that populate particular pieces of information from your deployment. Use environment variables in templates to get unique information about your deployment.

Reference an environment variable using this syntax:

```sh
    context.env['variable-name']
```

## Using template properties and environment variables in a template

In this step, `vm-template.py` shows the benefits of template properties and environment variables.

To view the new `vm-template.py`, first use the following command to open your home directory:

```sh
cd
```

Next, run the following command:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/step7_use_environment_variables/python
```

Then, open the `vm-template.py` file:

```sh
cloudshell edit vm-template.py
```

### Exploring the changes

Various parts of the file have been replaced with template properties and environment variables. For example, the project ID is replaced with `context.env[`project`]`. Read the file comments to learn about other changes in the file.

## Deploy your configuration

To view the configuration file for this deployment, run the following command:

```sh
cloudshell edit config-with-many-templates.yaml
```

Save your changes and redeploy your configuration to confirm the variables work.

```sh
    gcloud deployment-manager deployments create deployment-with-template-properties --config config-with-many-templates.yaml
```

## Delete the deployment

Once again, you will want to delete the deployment to avoid charges. Run the following command to delete the deployment:

```sh
gcloud deployment-manager deployments delete deployment-with-template-properties
```

### Looking ahead: helper scripts

Next, you will learn how to use helper scripts to efficiently perform repeated tasks.

## Exploring helper scripts

**Helper scripts** are helper files that make your templates more efficient by performing specific functions. Helper scripts can be used to interpret resource metadata, create files, and launch services.

You will now explore a Python helper script that names a virtual machine, given a prefix and a suffix.

## Viewing the helper script

The helper script in this example generates the name for a virtual machine. To view the helper script, first run the following command to open your home directory:

```sh
cd
```

Next, change to this directory:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/create_a_helper_script
```

Then, open `common.py`:

```sh
cloudshell edit common.py
```

## Using helper scripts in templates

To use `common.py` in `vm-template.py`, several changes must be made to the template.

To view the changes, open the `vm-template.py` file:

```sh
cloudshell edit vm-template.py
```

The template contains code comments highlighting the changes made.

### Exploring the changes

Notice that `common.py` is imported at the top of the file. Also, the `name` listing in the `resources` section is changed to use the script.

## Changing your configuration

The configuration must also be changed to import the helper script. To view this change, open `two-vms.yaml`:

```sh
cloudshell edit two-vms.yaml
```

Deploy your configuration to confirm the changes work:

```sh
gcloud deployment-manager deployments create deployment-with-helper-script --config two-vms.yaml
```

## View your deployment

View your deployment with the following command:

```sh
 gcloud deployment-manager deployments describe deployment-with-helper-script
```

## Delete the deployment

Once again, you will want to delete the deployment to avoid charges. Run the following command to delete the deployment:

```sh
gcloud deployment-manager deployments delete deployment-with-helper-script
```

### Looking forward: updating deployments

Next, learn to add, delete, and change the properties of resources of a deployment as your application evolves.

## Updating a deployment

Once you have created a deployment, you can update it as your application changes. You can use Deployment Manager to update a deployment by:

+   Adding or removing resources from a deployment
+   Updating the properties of existing resources in a deployment

You will now update a deployment by changing the metadata in `vm-template.py`.

## Deploy the original configuration

In this step, deploy the configuration that you will later update.

First, run the following command to open your home directory:

```sh
cd
```

Next, change to this directory:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/step8_metadata_and_startup_scripts/python
```

Deploy your configuration:

```sh
gcloud deployment-manager deployments create deployment-to-update --config config-with-many-templates.yaml
```

## Viewing the updated template

In this example, the metadata is changed in `vm-template.py`.

To view these changes, first run the following command to open your home directory:

```sh
cd
```

Next, change to this directory:

```sh
cd cloudshell_open/deploymentmanager-samples/examples/v2/step_by_step_guide/step9_update_a_deployment/python
```

Then, open `vm-template.py`:

```sh
cloudshell edit vm-template.py
```

Notice that the metadata section is changed in the file.

## Commit the update

### Preview the configuration

To preview your updated configuration before committing changes, run the following command:

```sh
gcloud deployment-manager deployments update deployment-to-update --config config-with-many-templates.yaml --preview
```

### Update the configuration

To commit the update, run the following command:

```sh
gcloud deployment-manager deployments update deployment-to-update
```

## Delete the deployment

You will want to delete the deployment to avoid charges. Run the following command to delete the deployment:

```sh
gcloud deployment-manager deployments delete deployment-to-update
```

### Next: Wrapping up

## Wrapping up

<walkthrough-conclusion-trophy/>

Congratulations! You've completed the Step-by-Step Walkthrough of Deployment Manager!

You learned skills such as:

+   Deploying resources
+   Creating templates
+   Setting template properties
+   Setting environment variables
+   Creating helper scripts
+   Updating deployments

### What's Next

Here are some areas to explore as you learn more details about specific Deployment Manager functions:

+   [Explore more complex tutorials](https://cloud.google.com/deployment-manager/docs/tutorials)
+   Page on metadata and startup scripts
+   [Learn about available resource types](https://cloud.google.com/deployment-manager/docs/configuration/supported-resource-types)
+   [Read the environment variables documentation](https://cloud.google.com/deployment-manager/docs/configuration/templates/use-environment-variables)
+   [Read about importing Python libraries](https://cloud.google.com/deployment-manager/docs/configuration/templates/import-python-libraries)
+   [Understand guidelines for preparing updates](https://cloud.google.com/deployment-manager/docs/deployments/updating-deployments)


text:
using System;
using System.Drawing;
using OpenLiveWriter.Api;

namespace OpenLiveWriter.InternalWriterPlugin
{
	internal class MapOptions
	{
		public MapOptions(IProperties mapOptions)
		{
			_mapOptions = mapOptions ;
		}

		public string PushpinUrl
		{
			get { return _mapOptions.GetString(PUSHPIN_URL, String.Empty); }
			set { _mapOptions.SetString(PUSHPIN_URL, value); }
		}
		private const string PUSHPIN_URL = "PushpinUrl" ;

		public string MoreAboutPushpinsUrl
		{
			get { return _mapOptions.GetString(MORE_ABOUT_PUSHPINS_URL, String.Empty); }
		}
		private const string MORE_ABOUT_PUSHPINS_URL = "MoreAboutPushpinsUrl" ;

		public string CaptionHtmlFormat
		{
			get { return _mapOptions.GetString(CAPTION_HTML_FORMAT, "
{0}"); }
			set { _mapOptions.SetString(CAPTION_HTML_FORMAT, value); }
		}
		private const string CAPTION_HTML_FORMAT = "CaptionFormat" ;

		public Size GetDefaultMapSize(string blogId)
		{
			IProperties blogProps = GetBlogSettings(blogId);
			int defaultWidth = blogProps.GetInt(DEFAULT_MAP_WIDTH, DefaultMapSize.Width);
			int defaultHeight = blogProps.GetInt(DEFAULT_MAP_HEIGHT, DefaultMapSize.Height);
			return MapSettings.EnsurePositiveSize(new Size(defaultWidth, defaultHeight), DefaultMapSize);
		}

		public void SetDefaultMapSize(string blogId, Size size)
		{
			IProperties blogProps = GetBlogSettings(blogId);
			blogProps.SetInt(DEFAULT_MAP_WIDTH, size.Width);
			blogProps.SetInt(DEFAULT_MAP_HEIGHT, size.Height);
		}
		private const string DEFAULT_MAP_WIDTH = "DefaultMapWidth" ;
		private const string DEFAULT_MAP_HEIGHT = "DefaultMapHeight" ;

		private IProperties GetBlogSettings(string blogId)
		{
			return _mapOptions.GetSubProperties(BLOG_SETTINGS).GetSubProperties(blogId);
		}

		private const string BLOG_SETTINGS = "BlogSettings" ;

		public Size DefaultDialogSize
		{
			get
			{
				int defaultWidth = _mapOptions.GetInt(DEFAULT_DIALOG_WIDTH, 640);
				int defaultHeight = _mapOptions.GetInt(DEFAULT_DIALOG_HEIGHT, 480);
				return new Size(defaultWidth, defaultHeight);
			}
			set
			{
				_mapOptions.SetInt(DEFAULT_DIALOG_WIDTH, value.Width);
				_mapOptions.SetInt(DEFAULT_DIALOG_HEIGHT, value.Height);
			}
		}
		private const string DEFAULT_DIALOG_WIDTH = "DefaultDialogWidth" ;
		private const string DEFAULT_DIALOG_HEIGHT = "DefaultDialogHeight" ;

		private IProperties _mapOptions ;

		public static Size DefaultMapSize
		{
			get
			{
				return new Size(320, 240);
			}
		}
	}
}


text:
'use strict';

/**
 * AuthController
 *
 * @description     Server-side logic for managing Auths
 * @module          api/models/Auth
 * @see             http://sailsjs.org/#!documentation/concepts/controllers
 */

module.exports = {
    /**
     * @description     Create a third-party authentication endpoint.
     * @param           {Request} req       Request object
     * @param           {Response} res      Response object
     */
    provider: function (req, res){
        PassportService.endpoint(req, res);
    },

    /**
     * @description     Render the login page with a list of available providers.
     * @param           {Request} req       Request object
     * @param           {Response} res      Response object
     *
     * The login form itself is just a simple HTML form:
     *
     * <form role="form" action="/auth/local" method="post">
     *     <input type="text" name="identifier" placeholder="Username or Email">
     *     <input type="password" name="password" placeholder="Password">
     *     <button type="submit">Sign in</button>
     * </form>
     *
     * You could optionally add CSRF-protection as outlined in the documentation:
     * http://sailsjs.org/#!documentation/config.csrf
     *
     * A simple example of automatically listing all available providers in a
     * Handlebars template would look like this:
     *
     * {{#each providers}}
     *     {{name}}
     * {{/each}}
     */
    login: function (req, res){
        var strategies = sails.config.passport,
            providers = {};

        // Get a list of available providers for use in your templates.
        Object.keys(strategies).forEach(function (key){
            if ('local' === key) {
                return;
            }

            providers[key] = {
                name: strategies[key].name,
                slug: key
            };
        });

        // Render the `auth/login.ext` view
        res.view({
            providers: providers,
            errors: req.flash('error')
        });
    },

    /**
     * @description     Log out a user and return them to the homepage.
     * @param           {Request} req       Request object
     * @param           {Response} res      Response object
     *
     * Passport exposes a logout() function on request (also aliased as logOut()) that can be
     * called from any route handler which needs to terminate a login session. Invoking logout()
     * will remove the request.user property and clear the login session (if any).
     *
     * For more information on logging out users in Passport.js, check out:
     * http://passportjs.org/guide/logout/
     */
    logout: function (req, res){
        req.logout();
        req.session.authenticated = false;
        res.json(200, true);
        //res.redirect('/');
    },

    /**
     * @description     Render the registration page.
     * @param           {Request} req       Request object
     * @param           {Response} res      Response object
     *
     * Just like the login form, the registration form is just simple HTML:
     *
     * <form role="form" action="/auth/local/register" method="post">
     *     <input type="text" name="username" placeholder="Username">
     *     <input type="text" name="email" placeholder="Email">
     *     <input type="password" name="password" placeholder="Password">
     *     <button type="submit">Sign up</button>
     * </form>
     */
    register: function (req, res){
        res.view({
            errors: req.flash('error')
        });
    },

    /**
     * @description     Disconnect a passport from a user.
     * @param           {Request} req       Request object
     * @param           {Response} res      Response object
     */
    disconnect: function (req, res){
        PassportService.disconnect(req, res);
    },

    /**
     * @description     Create a authentication callback endpoint.
     * @param           {Request} req       Request object
     * @param           {Response} res      Response object
     *
     * This endpoint handles everything related to creating and verifying Pass-
     * ports and users, both locally and from third-aprty providers.
     *
     * Passport exposes a login() function on req (also aliased as logIn()) that
     * can be used to establish a login session. When the login operation
     * completes, user will be assigned to req.user.
     *
     * For more information on logging in users in Passport.js, check out:
     * http://passportjs.org/guide/login/
     */
    callback: function (req, res){
        var tryAgain = function (err){
            // Only certain error messages are returned via req.flash('error', someError)
            // because we shouldn't expose internal authorization errors to the user.
            // We do return a generic error and the original request body.
            var flashError = req.flash('error')[0];

            if (err && !flashError ) {
                req.flash('error', res.i18n('c.auth.passport.generic.authorization'));
            }
            else if (flashError) {
                req.flash('error', flashError);
            }

            req.flash('form', req.body);

            // If an error was thrown, redirect the user to the
            // login, register or disconnect action initiator view.
            // These views should take care of rendering the error messages.
            var action = req.param('action');

            if ('register' === action) {
                res.redirect('/register');
            }
            else if ('disconnect' === action) {
                res.redirect('back');
            }
            else {
                res.redirect('/login');
            }
        };

        PassportService.callback(req, res, function (err, user, challenges, statuses){
            if (err || !user) {
                return tryAgain(challenges);
            }

            req.login(user, function (err){
                if (err) {
                    return tryAgain(err);
                }

                // Mark the session as authenticated to work with default Sails sessionAuth.js policy
                req.session.authenticated = true

                // Upon successful login, send the user to the homepage were req.user
                // will be available.
                res.redirect('/');
            });
        });
    }
};


text:
package com.sedc.collectors.yahoo.sector;

/**
 * Created by SuperOleg on 01.03.2017.
 */
public class YahooSectorApplication {

    public static void main(String[] args) {

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verrucaria persicina Hepp

### Remarks
null


text:
import numpy as np
import gym
from gym.spaces import Discrete, MultiDiscrete
from typing import Dict, List

from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.policy.rnn_sequencing import add_time_dimension
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.policy.view_requirement import ViewRequirement
from ray.rllib.utils.annotations import override, DeveloperAPI
from ray.rllib.utils.framework import try_import_tf
from ray.rllib.utils.tf_ops import one_hot
from ray.rllib.utils.typing import ModelConfigDict, TensorType

tf1, tf, tfv = try_import_tf()

@DeveloperAPI
class RecurrentNetwork(TFModelV2):
    """Helper class to simplify implementing RNN models with TFModelV2.

    Instead of implementing forward(), you can implement forward_rnn() which
    takes batches with the time dimension added already.

    Here is an example implementation for a subclass
    ``MyRNNClass(RecurrentNetwork)``::

        def __init__(self, *args, **kwargs):
            super(MyModelClass, self).__init__(*args, **kwargs)
            cell_size = 256

            # Define input layers
            input_layer = tf.keras.layers.Input(
                shape=(None, obs_space.shape[0]))
            state_in_h = tf.keras.layers.Input(shape=(256, ))
            state_in_c = tf.keras.layers.Input(shape=(256, ))
            seq_in = tf.keras.layers.Input(shape=(), dtype=tf.int32)

            # Send to LSTM cell
            lstm_out, state_h, state_c = tf.keras.layers.LSTM(
                cell_size, return_sequences=True, return_state=True,
                name="lstm")(
                    inputs=input_layer,
                    mask=tf.sequence_mask(seq_in),
                    initial_state=[state_in_h, state_in_c])
            output_layer = tf.keras.layers.Dense(...)(lstm_out)

            # Create the RNN model
            self.rnn_model = tf.keras.Model(
                inputs=[input_layer, seq_in, state_in_h, state_in_c],
                outputs=[output_layer, state_h, state_c])
            self.register_variables(self.rnn_model.variables)
            self.rnn_model.summary()
    """

    @override(ModelV2)
    def forward(self, input_dict: Dict[str, TensorType],
                state: List[TensorType],
                seq_lens: TensorType) -> (TensorType, List[TensorType]):
        """Adds time dimension to batch before sending inputs to forward_rnn().

        You should implement forward_rnn() in your subclass."""
        assert seq_lens is not None
        padded_inputs = input_dict["obs_flat"]
        max_seq_len = tf.shape(padded_inputs)[0] // tf.shape(seq_lens)[0]
        output, new_state = self.forward_rnn(
            add_time_dimension(
                padded_inputs, max_seq_len=max_seq_len, framework="tf"), state,
            seq_lens)
        return tf.reshape(output, [-1, self.num_outputs]), new_state

    def forward_rnn(self, inputs: TensorType, state: List[TensorType],
                    seq_lens: TensorType) -> (TensorType, List[TensorType]):
        """Call the model with the given input tensors and state.

        Args:
            inputs (dict): observation tensor with shape [B, T, obs_size].
            state (list): list of state tensors, each with shape [B, T, size].
            seq_lens (Tensor): 1d tensor holding input sequence lengths.

        Returns:
            (outputs, new_state): The model output tensor of shape
                [B, T, num_outputs] and the list of new state tensors each with
                shape [B, size].

        Sample implementation for the ``MyRNNClass`` example::

            def forward_rnn(self, inputs, state, seq_lens):
                model_out, h, c = self.rnn_model([inputs, seq_lens] + state)
                return model_out, [h, c]
        """
        raise NotImplementedError("You must implement this for a RNN model")

    def get_initial_state(self) -> List[TensorType]:
        """Get the initial recurrent state values for the model.

        Returns:
            list of np.array objects, if any

        Sample implementation for the ``MyRNNClass`` example::

            def get_initial_state(self):
                return [
                    np.zeros(self.cell_size, np.float32),
                    np.zeros(self.cell_size, np.float32),
                ]
        """
        raise NotImplementedError("You must implement this for a RNN model")

class LSTMWrapper(RecurrentNetwork):
    """An LSTM wrapper serving as an interface for ModelV2s that set use_lstm.
    """

    def __init__(self, obs_space: gym.spaces.Space,
                 action_space: gym.spaces.Space, num_outputs: int,
                 model_config: ModelConfigDict, name: str):

        super(LSTMWrapper, self).__init__(obs_space, action_space, None,
                                          model_config, name)

        self.cell_size = model_config["lstm_cell_size"]
        self.use_prev_action = model_config["lstm_use_prev_action"]
        self.use_prev_reward = model_config["lstm_use_prev_reward"]

        if isinstance(action_space, Discrete):
            self.action_dim = action_space.n
        elif isinstance(action_space, MultiDiscrete):
            self.action_dim = np.product(action_space.nvec)
        elif action_space.shape is not None:
            self.action_dim = int(np.product(action_space.shape))
        else:
            self.action_dim = int(len(action_space))

        # Add prev-action/reward nodes to input to LSTM.
        if self.use_prev_action:
            self.num_outputs += self.action_dim
        if self.use_prev_reward:
            self.num_outputs += 1

        # Define input layers.
        input_layer = tf.keras.layers.Input(
            shape=(None, self.num_outputs), name="inputs")

        self.num_outputs = num_outputs

        state_in_h = tf.keras.layers.Input(shape=(self.cell_size, ), name="h")
        state_in_c = tf.keras.layers.Input(shape=(self.cell_size, ), name="c")
        seq_in = tf.keras.layers.Input(shape=(), name="seq_in", dtype=tf.int32)

        # Preprocess observation with a hidden layer and send to LSTM cell
        lstm_out, state_h, state_c = tf.keras.layers.LSTM(
            self.cell_size,
            return_sequences=True,
            return_state=True,
            name="lstm")(
                inputs=input_layer,
                mask=tf.sequence_mask(seq_in),
                initial_state=[state_in_h, state_in_c])

        # Postprocess LSTM output with another hidden layer and compute values
        logits = tf.keras.layers.Dense(
            self.num_outputs,
            activation=tf.keras.activations.linear,
            name="logits")(lstm_out)
        values = tf.keras.layers.Dense(
            1, activation=None, name="values")(lstm_out)

        # Create the RNN model
        self._rnn_model = tf.keras.Model(
            inputs=[input_layer, seq_in, state_in_h, state_in_c],
            outputs=[logits, values, state_h, state_c])
        self.register_variables(self._rnn_model.variables)
        self._rnn_model.summary()

        # Add prev-a/r to this model's view, if required.
        if model_config["lstm_use_prev_action"]:
            self.inference_view_requirements[SampleBatch.PREV_ACTIONS] = \
                ViewRequirement(SampleBatch.ACTIONS, space=self.action_space,
                                data_rel_pos=-1)
        if model_config["lstm_use_prev_reward"]:
            self.inference_view_requirements[SampleBatch.PREV_REWARDS] = \
                ViewRequirement(SampleBatch.REWARDS, data_rel_pos=-1)

    @override(RecurrentNetwork)
    def forward(self, input_dict: Dict[str, TensorType],
                state: List[TensorType],
                seq_lens: TensorType) -> (TensorType, List[TensorType]):
        assert seq_lens is not None
        # Push obs through "unwrapped" net's `forward()` first.
        wrapped_out, _ = self._wrapped_forward(input_dict, [], None)

        # Concat. prev-action/reward if required.
        prev_a_r = []
        if self.model_config["lstm_use_prev_action"]:
            prev_a = input_dict[SampleBatch.PREV_ACTIONS]
            if isinstance(self.action_space, (Discrete, MultiDiscrete)):
                prev_a = one_hot(prev_a, self.action_space)
            prev_a_r.append(
                tf.reshape(tf.cast(prev_a, tf.float32), [-1, self.action_dim]))
        if self.model_config["lstm_use_prev_reward"]:
            prev_a_r.append(
                tf.reshape(
                    tf.cast(input_dict[SampleBatch.PREV_REWARDS], tf.float32),
                    [-1, 1]))

        if prev_a_r:
            wrapped_out = tf.concat([wrapped_out] + prev_a_r, axis=1)

        # Then through our LSTM.
        input_dict["obs_flat"] = wrapped_out
        return super().forward(input_dict, state, seq_lens)

    @override(RecurrentNetwork)
    def forward_rnn(self, inputs: TensorType, state: List[TensorType],
                    seq_lens: TensorType) -> (TensorType, List[TensorType]):
        model_out, self._value_out, h, c = self._rnn_model([inputs, seq_lens] +
                                                           state)
        return model_out, [h, c]

    @override(ModelV2)
    def get_initial_state(self) -> List[np.ndarray]:
        return [
            np.zeros(self.cell_size, np.float32),
            np.zeros(self.cell_size, np.float32),
        ]

    @override(ModelV2)
    def value_function(self) -> TensorType:
        return tf.reshape(self._value_out, [-1])


text:
app
  .service('socketService', function($q, $http, $interval, authService, Observable) {
    this.socket = io('http://localhost:8089');
    this.action = function(action, data) {
      data.token = authService.token.get();
      if (data.token) {
        this.socket.emit(action, data);
      } else {
        console.log('Action called, but token is undefined');
      }
    };
  })


text:
// This module is shared between NodeJS and babelled ES5
const isClient = Boolean(process.env.NODE_ENV);

module.exports = {
  '/': {
    SyncComponent: isClient && require('./pages/home').default
  },
  '/community': {
    Component: () => import(/* webpackChunkName: "community/index" */ './pages/community'),
    title: 'Community'
  },
  '/404': {
    SyncComponent: isClient && require('@patternfly/documentation-framework/pages/404/index').default,
    title: '404 Error'
  }
};


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

	<title>Insertar Pedido</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../../../css/bootstrap.min.css">

<form method="post" action="Guardar.php">

Datos Generales

						Numero de pedido
						<input type="text" class="form-control" name="numpedido" id="Pedido" onkeyup="loadPedido()" placeholder="N° de Pedido" required>

						Vendedor
						<select class="form-control" name="vendedor" id="Vendedor">
						<?php
						include("../../../clases/conexion.php");
						$selecinarVendedor="SELECT * FROM PERSONAL WHERE Categoria=1";
						$querySeleccionar=mysqli_query($conn,$selecinarVendedor);
						while ($fila=mysqli_fetch_array($querySeleccionar))
						{
							echo '<option value='.$fila['idPERSONAL'].'>'.$fila['ApellidoPaterno'].' '.$fila['ApellidoMaterno'].' '.$fila['Nombre'].'</option>';
						}
						mysqli_close($conn);
						?>
					    </select>

						Fecha Inicial
						<input type="date" class="form-control" name="fechaIngreso" id="FechaInicial" required>

						Fecha Entrega
						<input type="date" class="form-control" name="fechaEntrega" id="FechaEntrega" required>

					Prioridad
					<select class="form-control" name="prioridad" id="Prio">
						<option>Normal</option>
						<option>Media</option>
						<option>Urgente</option>
					</select>

						Tipo de Pedido
						<select name="tipo" id="Tipo" class="form-control">
							<option>Produccion Interna</option>
							<option>Rijaya Comercial</option>
							<option>Cliente Especial</option>
						</select>

						Referencia del Pedido
						<input type="text" class="form-control" name="referencia" maxlength="100" required>

		Agregar Producto

					Cantidad
					Tipo
					Clave
					Nombre Producto
					Color
					Descripcion

		<button type="submit" class="btn btn-success">Enviar</button>
</form>


text:
---
uid: SolidEdgeAssembly.AssemblyFeaturesRevolvedCutout.SetReferenceAxis(System.Object)
summary:
remarks:
---