text:
package de.germanspacebuild.plugins.fasttravel.data;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

/**
 * Created by oneill011990 on 29.04.2016
 * for FastTravelReborn
 *
 * @author oneill011990
 */
public abstract class Database {

    private static final HashMap<DBType, Database> dbSystems;

    static {
        dbSystems = new HashMap<>();
    }

    protected Connection dbConn;
    protected Statement dbStatement;

    //Static Stuff
    public static void registerDatabaseSystem(DBType systemName, Database dbSystem) {
        dbSystems.put(systemName, dbSystem);
    }

    public static Database getDatabaseBySystem(DBType systemName) {
        return dbSystems.get(systemName);
    }

    protected abstract void connect() throws ClassNotFoundException, SQLException;

    private void setupTables() {
        createTable("FastTravelSigns", "name TEXT, creator TEXT, signloc_World TEXT, signloc_X INTEGER," +
                " signloc_Y INTEGER, signloc_Z INTEGER, signloc_Yaw REAL, " +
                "tploc_World TEXT, tploc_X INTEGER, tploc_Y INTEGER, tploc_Z INTEGER, tploc_Yaw REAL," +
                "automatic BOOLEAN, price REAL, range INTEGER, players LONGBLOB");
    }

    public void init() {
        try {
            dbConn = null;
            connect();
            dbStatement = dbConn.createStatement();
            setupTables();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void shutdown() {
        try {
            dbStatement.close();
            dbConn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private boolean createTable(String tableName, String columns) {
        if (dbStatement != null) {
            try {
                dbStatement.executeUpdate(
                        "CREATE TABLE IF NOT EXISTS  FastTravelSigns (" +
                                "name TEXT, " +
                                "creator TEXT, " +
                                "signloc_World TEXT, " +
                                "signloc_X INTEGER," +
                                "signloc_Y INTEGER, " +
                                "signloc_Z INTEGER, " +
                                "signloc_Yaw REAL, " +
                                "tploc_World TEXT, " +
                                "tploc_X INTEGER, " +
                                "tploc_Y INTEGER, " +
                                "tploc_Z INTEGER, " +
                                "tploc_Yaw REAL, " +
                                "automatic BOOLEAN, " +
                                "marker BOOLEAN, " +
                                "price REAL, " +
                                "range INTEGER, " +
                                "players TEXT" +
                                ");"
                );
                return true;
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        } else return false;
    }

    public boolean tableContains(String column, String value) {
        try {
            ResultSet rs = dbStatement.executeQuery("SELECT COUNT(" + column + ") AS " + column +
                    "Count FROM FastTravelSigns WHERE " + column + "='" + value + "'");
            if (rs == null) return false;
            if (rs.isAfterLast()) return false;
            if (rs.isBeforeFirst()) rs.next();
            return rs.getInt(1) != 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean parseBoolean(int bool) {
        return bool == 1;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import i18n from 'app/utils/i18n'
import {Tip} from 'app/components'

function maybe_submit(ev){
  if (ev.charCode==13){
    $('#project_name_submit').click()
  }
}

export function make_projectname(props){
  return {
    tip: (
      <Tip
        subtitle={i18n("Create projects to categorize clients, jobs, etc.")}
        description={i18n("Projects allows to have related services, rules and issues together.")}
        />
    ),
    work: (

{i18n("Choose a name for your project")}

          <input type="text" placeholder={i18n("Name your project")} id="project_name" onKeyPress={maybe_submit}/>
          <button
            className="ui basic teal button"
            style={{marginTop: 30}}
            onClick={() => props.handleCreateProject($('input#project_name').val())}
            id="project_name_submit"
            >{i18n("Create and continue")}</button>

    )
  }
}


text:
/*
 * TokenPhrases.h
 *
 * Created: 16/12/2016 1:56:38 PM
 *  Author: Chris
 */

#ifndef TOKENPHRASES_H_
#define TOKENPHRASES_H_

#include <stdint.h>
#include <avr/pgmspace.h>

 typedef struct TokenPhrases
 {
	 const PGM_P   token;
	 const uint8_t phraseCount;
	 const PGM_P*  phrases;
 }
 TokenPhrases;

 char*   tokenPhrases_copyToken        ( TokenPhrases tokenPhrases );
 uint8_t tokenPhrases_getPhraseCount   ( TokenPhrases tokenPhrases );
 char*   tokenPhrases_copyPhraseAtIndex( TokenPhrases tokenPhrases, uint8_t phraseIndex );

#endif /* TOKENPHRASES_H_ */


text:
{-
Copyright 2010-2012 Cognimeta Inc.

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.
-}

module Database.Perdure.Ref (
  Ref(..),
  ref,
  refLens
  ) where

import System.IO.Unsafe
import Database.Perdure.Deref
import Control.Lens
import Database.Perdure.Persistent
import Control.Applicative

class Deref r => Ref r where
  refIO :: a -> IO (r a)

{-# NOINLINE ref #-}
ref :: Ref r => a -> r a
ref = unsafePerformIO . refIO

refLens :: Ref r => Lens' (r a) a
refLens = lens deref $ const ref

instance Ref r => Ref (IRef r) where refIO = (IRef <$>) . refIO
instance Ref Ref0 where refIO = return . Ref0
instance Deref r => Ref (CRef r) where refIO = return . ToRef
instance Deref r => Functor (CRef r) where fmap f = ref . f . deref


text:
if [ ! -e "/sbin/initctl" ]
then
  # Apparently there are issues with upstart and connecting to sockets in
  # Ubuntu on virtual hosts, you have to redirect the response to "true".
  #
  # see: https://www.nesono.com/node/368
  sudo dpkg-divert --local --rename --add /sbin/initctl
  ln -s /bin/true /sbin/initctl
fi


text:
:root {
  --dark-primary-color: #303F9F;
  --default-primary-color:#3F51B5;
  --light-primary-color: #C5CAE9;
  --text-primary-color: #ffffff; /*text/icons*/
  --accent-color: #FF4081;
  --primary-background-color: #c5cae9;
  --primary-text-color: #212121;
  --secondary-text-color: #727272;
  --disabled-text-color: #bdbdbd;
  --divider-color: #B6B6B6;

  /* Components */

  /* paper-drawer-panel */
  --drawer-menu-color: #ffffff;
  --drawer-border-color: 1px solid #ccc;
  --drawer-toolbar-border-color: 1px solid rgba(0, 0, 0, 0.22);

    /* paper-menu */
  --paper-menu-background-color: #fff;
  --menu-link-color: #111111;
}

/* General styles */

paper-material {
  border-radius: 2px;
  height: 100%;
  padding: 16px 0px 16px 0px;
  width: calc(98.66% - 16px);
  margin: 16px auto;
  background: white;
}

#mainToolbar {
  box-shadow: 0 4px 5px 0 rgba(0,0,0,.14),
  0 2px 9px 1px rgba(0,0,0,.12),
  0 4px 2px -2px rgba(0,0,0,.2);
}

paper-menu iron-icon {
  margin-right: 33px;
  opacity: 0.54;
}

.paper-menu > .iron-selected {
  color: var(--default-primary-color);
}

#mainToolbar .bottom {
  padding-bottom: 120px;
  margin-left: 30px;
}

paper-menu a {
  text-decoration: none;
  color: var(--menu-link-color);
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-direction: row;
  -webkit-flex-direction: row;
  flex-direction: row;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-size: 14px;
  font-weight: 400;
  line-height: 24px;
  min-height: 48px;
  padding: 0px 16px;
}

#drawerToolbar {
  border-bottom: var(--drawer-toolbar-border-color);
  height: 120px;
}

#paperToggle {
  width: 45px;
  height: 45px;
  border: none;
  color: var(--drawer-menu-color);
  background-color: transparent;
  margin-right: 16px;
  padding: 8px;
}

section{
  padding: 30px;
}

/* Breakpoints */

/* Small */

@media (max-width: 600px) {

  paper-toolbar.has-shadow {
    height: 56px;
  }

  .paper-font-display2 {
    font-size: 30px;
  }

  .paper-font-display1 {
    font-size: 12px;
  }

  paper-material {
    --menu-container-display: none;
    width: calc(97.33% - 32px);
    padding-left: 16px;
    padding-right: 16px;
  }

  #drawer .paper-toolbar {
    margin-left: 16px;
  }

  #overlay {
    min-width: 360px;
  }

  .bg {
    background: white;
  }

  #mainToolbar .bottom {
    margin-left: 50px;
    padding-bottom: 24px;
  }

  #mainToolbar.has-shadow .bottom {
    padding-bottom: 0px;
  }

  .appname {
    font-size: 24px;
    padding-bottom: 0px;
  }
}

@media (min-width: 601px) {

  paper-material {
    width: calc(98% - 46px);
    padding-left: 30px;
    padding-right: 30px;
  }

    #mainToolbar.has-shadow .bottom {
        margin-left: 50px;
        padding-bottom: 0;
        padding-left: 0;
        font-size: 24px;
    }

}

/* Material Design Adaptive Breakpoints */
/*
  Below you'll find CSS media queries based on the breakpoint guidance
  published by the Material Design team. You can choose to use, customise
  or remove these breakpoints based on your needs.

  http://www.google.com/design/spec/layout/adaptive-ui.html#adaptive-ui-breakpoints
 */

/* mobile-small */
@media all and (min-width: 0px) and (max-width: 360px) and (orientation: portrait) { }
/* mobile-large */
@media all and (min-width: 361px) and (orientation: portrait) { }
/* mobile-small-landscape */
@media all and (min-width: 0px) and (max-width: 480px) and (orientation: landscape) { }
/* mobile-large-landscape */
@media all and (min-width: 481px) and (orientation: landscape) { }
/* tablet-small-landscape */
@media all and (min-width: 600px) and (max-width: 960px) and (orientation: landscape) { }
/* tablet-large-landscape */
@media all and (min-width: 961px) and (orientation: landscape) { }
/* tablet-small */
@media all and (min-width: 600px) and (orientation: portrait) { }
/* tablet-large */
@media all and (min-width: 601px) and (max-width: 840px) and (orientation : portrait) { }
/* desktop-x-small-landscape */
@media all and (min-width: 0px) and (max-width: 480px) and (orientation: landscape) { }
/* desktop-x-small */
@media all and (min-width: 0px) and (max-width: 480px) and (max-aspect-ratio: 4/3) { }
/* desktop-small-landscape */
@media all and (min-width: 481px) and (max-width: 840px) and (orientation: landscape) { }
/* desktop-small */
@media all and (min-width: 481px) and (max-width: 840px) and (max-aspect-ratio: 4/3) { }
/* desktop-medium-landscape */
@media all and (min-width: 841px) and (max-width: 1280px) and (orientation: landscape) { }
/* desktop-medium */
@media all and (min-width: 841px) and (max-width: 1280px) and (max-aspect-ratio: 4/3) { }
/* desktop-large */
@media all and (min-width: 1281px) and (max-width: 1600px) { }
/* desktop-xlarge */
@media all and (min-width: 1601px) and (max-width: 1920px) { }


text:
#ifndef CSTUBS_INTERNALS_H
#define CSTUBS_INTERNALS_H

/* This is just here for backwards compatibility and will eventually be
   removed. */

/* Include the real header. */
#include "ctypes_cstubs_internals.h"

#endif /* CSTUBS_INTERNALS_H */


text:
package io.bootique;

import com.google.inject.Module;
import com.google.inject.util.Modules;
import io.bootique.log.BootLogger;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import static java.util.stream.Collectors.toList;

class RuntimeModuleMerger {

    private BootLogger bootLogger;

    RuntimeModuleMerger(BootLogger bootLogger) {
        this.bootLogger = bootLogger;
    }

    Collection<Module> toGuiceModules(Collection<BQModule> bqModules) {
        return applyOverrides(checkCycles(collectUnique(bqModules)));
    }

    private Collection<Module> applyOverrides(Collection<RuntimeModule> modules) {
        return modules.stream()
                // find "heads" in override dependency linked lists.
                .filter(RuntimeModule::doesNotOverrideOthers)
                // fold each overrides linked list into a single module
                .map(this::fold)
                .collect(toList());
    }

    private Collection<RuntimeModule> checkCycles(Collection<RuntimeModule> modules) {
        modules.forEach(RuntimeModule::checkCycles);
        return modules;
    }

    private Collection<RuntimeModule> collectUnique(Collection<BQModule> bqModules) {

        // TODO: looking up modules by java type limits the use of lambdas as modules. E.g. we loaded test
        // properties are dynamically created modules in a repeatedly called Lambda. This didn't work..
        // So perhaps use provider name as a unique key?

        Map<Class<? extends Module>, RuntimeModule> map = new LinkedHashMap<>();

        for (BQModule bqModule : bqModules) {

            RuntimeModule rm = new RuntimeModule(bqModule);

            RuntimeModule existing = map.putIfAbsent(rm.getModuleType(), rm);
            if (existing != null) {
                bootLogger.trace(() -> String.format(
                        "Skipping module '%s' provided by '%s' (already provided by '%s')...",
                        rm.getModuleName(),
                        rm.getProviderName(),
                        existing.getProviderName()));
            }
        }

        calcOverrideGraph(map);

        return map.values();
    }

    private void calcOverrideGraph(Map<Class<? extends Module>, RuntimeModule> modules) {

        for (RuntimeModule rm : modules.values()) {

            for(Class<? extends Module> override : rm.getBqModule().getOverrides()) {
                RuntimeModule rmn = modules.get(override);
                if(rmn != null) {
                    rmn.setOverriddenBy(rm);
                    rm.setOverridesOthers(true);
                }
            }
        }
    }

    private Module fold(RuntimeModule rm) {

        RuntimeModule overriddenBy = rm.getOverriddenBy();

        if (overriddenBy == null) {
            trace(rm.getBqModule(), null);
            return rm.getModule();
        }

        trace(rm.getBqModule(), overriddenBy.getBqModule());

        // WARN: using recursion because fold.. is there a realistic prospect of this blowing the stack? I haven't
        // seen overrides more than 2-4 levels deep.

        // fold must happen in this order (overriding starts from the tail). Otherwise the algorithm will not work.
        return Modules.override(rm.getModule()).with(fold(overriddenBy));
    }

    private void trace(BQModule module, BQModule overriddenBy) {
        bootLogger.trace(() -> traceMessage(module, overriddenBy));
    }

    private String traceMessage(BQModule module, BQModule overriddenBy) {

        StringBuilder message = new StringBuilder("Loading module '")
                .append(module.getName())
                .append("'");

        String providerName = module.getProviderName();
        boolean hasProvider = providerName != null && providerName.length() > 0;
        if (hasProvider) {
            message.append(" provided by '").append(providerName).append("'");
        }

        if (overriddenBy != null) {
            if (hasProvider) {
                message.append(",");
            }

            message.append(" overridden by '").append(overriddenBy.getName()).append("'");
        }

        return message.toString();
    }
}


text:
import larv
import pygame

class RenderComponent(larv.Component):
    def __init__(self, sprite):
        assert isinstance(sprite, pygame.Surface)
        self.sprite = sprite
        # self.rect = sprite.get_rect()


text:
module Fog
  module XenServer
    class Compute
      module Models
        class Pgpus < Collection
          model Fog::XenServer::Compute::Models::Pgpu
        end
      end
    end
  end
end


text:
require "mini_magick/shell"

module MiniMagick
  ##
  # Abstract class that wraps command-line tools. It shouldn't be used directly,
  # but through one of its subclasses (e.g. {MiniMagick::Tool::Mogrify}). Use
  # this class if you want to be closer to the metal and execute ImageMagick
  # commands directly, but still with a nice Ruby interface.
  #
  # @example
  #   MiniMagick::Tool::Mogrify.new do |builder|
  #     builder.resize "500x500"
  #     builder << "path/to/image.jpg"
  #   end
  #
  class Tool

    CREATION_OPERATORS = %w[xc canvas logo rose gradient radial-gradient plasma
                            pattern text pango]

    ##
    # Aside from classic instantiation, it also accepts a block, and then
    # executes the command in the end.
    #
    # @example
    #   version = MiniMagick::Tool::Identify.new { |b| b.version }
    #   puts version
    #
    # @return [MiniMagick::Tool, String] If no block is given, returns an
    #   instance of the tool, if block is given, returns the output of the
    #   command.
    #
    def self.new(*args)
      instance = super(*args)

      if block_given?
        yield instance
        instance.call
      else
        instance
      end
    end

    # @private
    attr_reader :name, :args

    # @param whiny [Boolean] Whether to raise errors on exit codes different
    #   than 0.
    # @example
    #   MiniMagick::Tool::Identify.new(whiny: false) do |identify|
    #     identify.help # returns exit status 1, which would otherwise throw an error
    #   end
    def initialize(name, options = {})
      warn "MiniMagick::Tool.new(false) is deprecated and will be removed in MiniMagick 5, use MiniMagick::Tool.new(whiny: false) instead." if !options.is_a?(Hash)

      @name  = name
      @args  = []
      @whiny = options.is_a?(Hash) ? options.fetch(:whiny, MiniMagick.whiny) : options
    end

    ##
    # Executes the command that has been built up.
    #
    # @example
    #   mogrify = MiniMagick::Tool::Mogrify.new
    #   mogrify.resize("500x500")
    #   mogrify << "path/to/image.jpg"
    #   mogrify.call # executes `mogrify -resize 500x500 path/to/image.jpg`
    #
    # @example
    #   mogrify = MiniMagick::Tool::Mogrify.new
    #   # build the command
    #   mogrify.call do |stdout, stderr, status|
    #     # ...
    #   end
    #
    # @yield [Array] Optionally yields stdout, stderr, and exit status
    #
    # @return [String] Returns the output of the command
    #
    def call(*args)
      options = args[-1].is_a?(Hash) ? args.pop : {}
      warn "Passing whiny to MiniMagick::Tool#call is deprecated and will be removed in MiniMagick 5, use MiniMagick::Tool.new(whiny: false) instead." if args.any?
      whiny = args.fetch(0, @whiny)

      options[:whiny] = whiny
      options[:stderr] = false if block_given?

      shell = MiniMagick::Shell.new
      stdout, stderr, status = shell.run(command, options)
      yield stdout, stderr, status if block_given?

      stdout.chomp("\n")
    end

    ##
    # The currently built-up command.
    #
    # @return [Array<String>]
    #
    # @example
    #   mogrify = MiniMagick::Tool::Mogrify.new
    #   mogrify.resize "500x500"
    #   mogrify.contrast
    #   mogrify.command #=> ["mogrify", "-resize", "500x500", "-contrast"]
    #
    def command
      [*executable, *args]
    end

    ##
    # The executable used for this tool. Respects
    # {MiniMagick::Configuration#cli}, {MiniMagick::Configuration#cli_path},
    # and {MiniMagick::Configuration#cli_prefix}.
    #
    # @return [Array<String>]
    #
    # @example
    #   MiniMagick.configure { |config| config.cli = :graphicsmagick }
    #   identify = MiniMagick::Tool::Identify.new
    #   identify.executable #=> ["gm", "identify"]
    #
    # @example
    #   MiniMagick.configure do |config|
    #     config.cli = :graphicsmagick
    #     config.cli_prefix = ['firejail', '--force']
    #   end
    #   identify = MiniMagick::Tool::Identify.new
    #   identify.executable #=> ["firejail", "--force", "gm", "identify"]
    #
    def executable
      exe = [name]
      exe.unshift "magick" if MiniMagick.imagemagick7? && name != "magick"
      exe.unshift "gm" if MiniMagick.graphicsmagick?
      exe.unshift File.join(MiniMagick.cli_path, exe.shift) if MiniMagick.cli_path
      Array(MiniMagick.cli_prefix).reverse_each { |p| exe.unshift p } if MiniMagick.cli_prefix
      exe
    end

    ##
    # Appends raw options, useful for appending image paths.
    #
    # @return [self]
    #
    def <<(arg)
      args << arg.to_s
      self
    end

    ##
    # Merges a list of raw options.
    #
    # @return [self]
    #
    def merge!(new_args)
      new_args.each { |arg| self << arg }
      self
    end

    ##
    # Changes the last operator to its "plus" form.
    #
    # @example
    #   MiniMagick::Tool::Mogrify.new do |mogrify|
    #     mogrify.antialias.+
    #     mogrify.distort.+("Perspective", "0,0,4,5 89,0,45,46")
    #   end
    #   # executes `mogrify +antialias +distort Perspective '0,0,4,5 89,0,45,46'`
    #
    # @return [self]
    #
    def +(*values)
      args[-1] = args[-1].sub(/^-/, '+')
      self.merge!(values)
      self
    end

    ##
    # Create an ImageMagick stack in the command (surround.
    #
    # @example
    #   MiniMagick::Tool::Convert.new do |convert|
    #     convert << "wand.gif"
    #     convert.stack do |stack|
    #       stack << "wand.gif"
    #       stack.rotate(30)
    #     end
    #     convert.append.+
    #     convert << "images.gif"
    #   end
    #   # executes `convert wand.gif \( wizard.gif -rotate 30 \) +append images.gif`
    #
    def stack
      self << "("
      yield self
      self << ")"
    end

    ##
    # Adds ImageMagick's pseudo-filename `-` for standard input.
    #
    # @example
    #   identify = MiniMagick::Tool::Identify.new
    #   identify.stdin
    #   identify.call(stdin: image_content)
    #   # executes `identify -` with the given standard input
    #
    def stdin
      self << "-"
    end

    ##
    # Adds ImageMagick's pseudo-filename `-` for standard output.
    #
    # @example
    #   content = MiniMagick::Tool::Convert.new do |convert|
    #     convert << "input.jpg"
    #     convert.auto_orient
    #     convert.stdout
    #   end
    #   # executes `convert input.jpg -auto-orient -` which returns file contents
    #
    def stdout
      self << "-"
    end

    ##
    # Define creator operator methods
    #
    #   mogrify = MiniMagick::Tool.new("mogrify")
    #   mogrify.canvas("khaki")
    #   mogrify.command.join(" ") #=> "mogrify canvas:khaki"
    #
    CREATION_OPERATORS.each do |operator|
      define_method(operator.gsub('-', '_')) do |value = nil|
        self << "#{operator}:#{value}"
        self
      end
    end

    ##
    # This option is a valid ImageMagick option, but it's also a Ruby method,
    # so we need to override it so that it correctly acts as an option method.
    #
    def clone(*args)
      self << '-clone'
      self.merge!(args)
      self
    end

    ##
    # Any undefined method will be transformed into a CLI option
    #
    #   mogrify = MiniMagick::Tool.new("mogrify")
    #   mogrify.adaptive_blur("...")
    #   mogrify.foo_bar
    #   mogrify.command.join(" ") "mogrify -adaptive-blur ... -foo-bar"
    #
    def method_missing(name, *args)
      option = "-#{name.to_s.tr('_', '-')}"
      self << option
      self.merge!(args)
      self
    end

    def self.option_methods
      @option_methods ||= (
        tool = new(whiny: false)
        tool << "-help"
        help_page = tool.call(stderr: false)

        cli_options = help_page.scan(/^\s+-[a-z\-]+/).map(&:strip)
        if tool.name == "mogrify" && MiniMagick.graphicsmagick?
          # These options were undocumented before 2015-06-14 (see gm bug 302)
          cli_options |= %w[-box -convolve -gravity -linewidth -mattecolor -render -shave]
        end

        cli_options.map { |o| o[1..-1].tr('-','_') }
      )
    end

  end
end

require "mini_magick/tool/animate"
require "mini_magick/tool/compare"
require "mini_magick/tool/composite"
require "mini_magick/tool/conjure"
require "mini_magick/tool/convert"
require "mini_magick/tool/display"
require "mini_magick/tool/identify"
require "mini_magick/tool/import"
require "mini_magick/tool/magick"
require "mini_magick/tool/mogrify"
require "mini_magick/tool/mogrify_restricted"
require "mini_magick/tool/montage"
require "mini_magick/tool/stream"


text:
"""サービスラッパー"""

from ariblib.descriptors import (
    LogoTransmissionDescriptor,
    ServiceDescriptor,
)
from ariblib.sections import (
    ActualStreamServiceDescriptionSection,
    OtherStreamServiceDescriptionSection,
    ServiceDescriptionSection,
)

def services(ts, channel_id=None, single=False, stream=None):
    """トランスポートストリームから Service オブジェクトを返すジェネレータ"""

    if channel_id is None:
        get_channel_id = lambda sdt: tsid2channel(sdt.transport_stream_id)
    else:
        get_channel_id = lambda sdt: str(channel_id)

    if stream == 'actual':
        SDT = ActualStreamServiceDescriptionSection
    elif stream == 'other':
        SDT = OtherStreamServiceDescriptionSection
    else:
        SDT = ServiceDescriptionSection

    if single:
        sdt = next(ts.sections(SDT))
        for service in sdt.services:
            yield Service(service, get_channel_id(sdt))
    else:
        for sdt in ts.sections(SDT):
            for service in sdt.services:
                yield Service(service, get_channel_id(sdt))

def parse_tsid(tsid):
    # NHK-BS対応
    if 16625 <= tsid <= 16626:
        tsid -= 1
    network_lower_4bit = (tsid & 0xF000) >> 12
    new = (tsid & 0x0E000) >> 9
    repeater = (tsid & 0x01F0) >> 4
    slot = tsid & 0x0007

    return (network_lower_4bit, new, repeater, slot)

def tsid2channel(tsid):
    """transport_stream_id を recpt1 が認識する channel 形式に変える"""
    lower, new, repeater, slot = parse_tsid(tsid)
    # ほんとはSystemManagementDescriptorのbroadcasting_identifierで
    # BS/CSの判別をすべきだと思う
    if repeater % 2 == 0:
        return "CS{:02d}".format(repeater)
    else:
        return "BS{:02d}_{}".format(repeater, slot)

class Service(object):

    """サービスラッパークラス"""

    def __init__(self, service, channel_id):
        self.channel_id = channel_id
        if 'BS' in channel_id:
            self.broadcasting_type = 'BS'
            self.channel_number =\
                int(channel_id.split('_')[0].replace('BS', ''))
        elif 'CS' in channel_id:
            self.broadcasting_type = 'CS'
            self.channel_number = int(channel_id.replace('CS', ''))
        else:
            self.broadcasting_type = 'GR'
            self.channel_number = int(channel_id)
        self.service_id = service.service_id
        self.eit_flags = service.EIT_user_defined_flags
        self.eit_schedule = service.EIT_schedule_flag
        self.pseit = service.EIT_present_following_flag
        descs = service.descriptors
        sd = descs[ServiceDescriptor][0]
        self.service_type = sd.service_type
        self.provider = sd.service_provider_name
        self.name = sd.service_name
        self.free_CA_mode = service.free_CA_mode
        self.logo = ''
        for ltd in descs[LogoTransmissionDescriptor]:
            if ltd.logo_transmission_type == 3:
                self.logo = ltd.logo_char
                break


text:
function y = cmpndNoiseOut(noise, mu, varsigma)

% CMPNDNOISEOUT Compute the output of the CMPND noise given the input mean and variance.
% FORMAT
% DESC computes the ouptut for the compound
% noise given input mean and variances.
% ARG noise : the noise structure for which the output is computed.
% ARG mu : the input mean values.
% ARG varSigma : the input variance values.
% RETURN y : the output from the noise model.
%
% SEEALSO : cmpndNoiseParamInit, noiseOut, noiseCreate,
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005

% GPMAT

y = zeros(size(mu));
for i = 1:length(noise.comp)
  fhandle = str2func([noise.comp{i}.type 'NoiseOut']);
  y(:, i) = fhandle(noise.comp{i},...
                    mu(:, i), ...
                    varsigma(:, i));
end


text:
package com.epam.ta.reportportal.core.widget.content.updater;

import com.epam.ta.reportportal.entity.widget.Widget;
import com.epam.ta.reportportal.entity.widget.WidgetState;
import com.epam.ta.reportportal.ws.converter.builders.WidgetBuilder;
import org.springframework.stereotype.Component;

/**
 * @author Ivan Budayeu
 */
@Component
public class MaterializedWidgetStateUpdater implements WidgetUpdater {

	public static final String STATE = "state";

	@Override
	public void update(Widget widget) {
		new WidgetBuilder(widget).addOption(STATE, WidgetState.CREATED.getValue());
	}
}


text:
/*  -*- mode: c++; coding: utf-8; c-file-style: "stroustrup"; -*-

    Contributors: Asier Aguirre

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE.txt file.
*/

#pragma once

#include "vector.h"
#include "compatibility.h"
#include <vector>

namespace render {

    struct RGBA {
        union {
            uint32_t c;
            struct {
                uint8_t a, b, g, r;
            };
        };
        RGBA(): c(0) { }
        RGBA(uint32_t c): c(c) { }
    };

    struct Vertex {
        GLfloat pos[2];
        GLushort tex[2];
        RGBA color;
    };

    class VertexBuffer {
    public:
        VertexBuffer();
        ~VertexBuffer();
        bool init();
        void finish();

        void clear();
        int size() const { return vertices.size(); }
        Vertex* addTriangle(); // 3 vertices
        void addQuad(const webui::Box4f& vertex, const webui::Box4us& tex, RGBA color = 0x80808080);

        bool render(int glMode);

    private:
        GLuint vbo;    // vertex buffer object
        std::vector<Vertex> vertices;
    };

}


text:
import ChromaPy32 as Chroma  # Import the Chroma Module
from time import sleep

Keyboard = Chroma.Keyboard()  # Initialize a new Keyboard Instance

RED = (255, 0, 0)  # Initialize a new color by RGB (RED,GREEN,BLUE)

Keyboard.setColor(RED)  # sets the whole Keyboard-Grid to RED

Keyboard.applyGrid()  # applies the Keyboard-Grid to the connected Keyboard
sleep(5)


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_storage_h_
#define mozilla_storage_h_

////////////////////////////////////////////////////////////////////////////////
//// Public Interfaces

#include "mozStorageCID.h"
#include "mozIStorageAggregateFunction.h"
#include "mozIStorageConnection.h"
#include "mozIStorageError.h"
#include "mozIStorageFunction.h"
#include "mozIStoragePendingStatement.h"
#include "mozIStorageProgressHandler.h"
#include "mozIStorageResultSet.h"
#include "mozIStorageRow.h"
#include "mozIStorageService.h"
#include "mozIStorageStatement.h"
#include "mozIStorageStatementCallback.h"
#include "mozIStorageBindingParamsArray.h"
#include "mozIStorageBindingParams.h"
#include "mozIStorageServiceQuotaManagement.h"
#include "mozIStorageVacuumParticipant.h"
#include "mozIStorageCompletionCallback.h"
#include "mozIStorageAsyncStatement.h"

////////////////////////////////////////////////////////////////////////////////
//// Native Language Helpers

#include "mozStorageHelper.h"
#include "mozilla/storage/StatementCache.h"
#include "mozilla/storage/Variant.h"

#endif // mozilla_storage_h_


text:
// TODO: Copyright

namespace Planet.Dashboard.Rewards.Core.Entities
{
    public enum EntityType
    {
        Action,
        ActionEdits,
        Beacon,
		BeaconAction,
		CompletedAction,
        Event,
		EventBeacon,
        User,
        Organization,
        PointsGranted,
        Cause
    }
}


text:
import Twit from 'twit';
import _ from 'underscore';

const whitelistedFields = [
	'id',
	'name',
	'description',
	'profile_image_url',
	'profile_image_url_https',
	'lang',
	'email',
];

const getIdentity = function(accessToken, appId, appSecret, accessTokenSecret) {
	const Twitter = new Twit({
		consumer_key: appId,
		consumer_secret: appSecret,
		access_token: accessToken,
		access_token_secret: accessTokenSecret,
	});
	const syncTwitter = Meteor.wrapAsync(Twitter.get, Twitter);
	try {
		return syncTwitter('account/verify_credentials.json?include_email=true');
	} catch (err) {
		throw _.extend(new Error(`Failed to fetch identity from Twwiter. ${ err.message }`),
			{ response: err.response });
	}
};

RocketChat.registerAccessTokenService('twitter', function(options) {
	check(options, Match.ObjectIncluding({
		accessToken: String,
		appSecret: String,
		appId: String,
		accessTokenSecret: String,
		expiresIn: Match.Integer,
		identity: Match.Maybe(Object),
	}));

	const identity = options.identity || getIdentity(options.accessToken, options.appId, options.appSecret, options.accessTokenSecret);

	const serviceData = {
		accessToken: options.accessToken,
		expiresAt: (+new Date) + (1000 * parseInt(options.expiresIn, 10)),
	};

	const fields = _.pick(identity, whitelistedFields);
	_.extend(serviceData, fields);

	return {
		serviceData,
		options: {
			profile: {
				name: identity.name,
			},
		},
	};
});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.renren</groupId>
  <artifactId>renren-security</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>
  <description>renren-security</description>

	<properties>
		<java-version>1.7</java-version>
		<servlet-version>3.1.0</servlet-version>
		<junit-version>4.12</junit-version>
		<springframework-version>4.2.9.RELEASE</springframework-version>
		<mybatis-version>3.4.1</mybatis-version>
		<mybatis-spring-version>1.3.0</mybatis-spring-version>
		<mysql-version>5.1.38</mysql-version>
		<druid-version>1.0.26</druid-version>
		<commons-lang-version>2.6</commons-lang-version>
		<commons-fileupload-version>1.3.1</commons-fileupload-version>
		<commons-io-version>2.5</commons-io-version>
		<commons-codec-version>1.10</commons-codec-version>
		<commons-configuration-version>1.10</commons-configuration-version>
		<commons-logging-version>1.2</commons-logging-version>
		<slf4j-version>1.7.19</slf4j-version>
		<log4j-version>1.2.17</log4j-version>
		<fastjson-version>1.2.21</fastjson-version>
		<shiro-version>1.3.2</shiro-version>
		<quartz-version>2.2.3</quartz-version>
		<kaptcha-version>0.0.9</kaptcha-version>
		<velocity-version>1.7</velocity-version>
		<velocity-tools-version>2.0</velocity-tools-version>
		<jstl-version>1.2</jstl-version>
		<taglibs-version>1.1.2</taglibs-version>
		<freemarker-version>2.3.23</freemarker-version>
	</properties>

	<!-- 阿里云maven仓库 -->
	<repositories>
		<repository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>

	<dependencies>
		<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit-version}</version>
            <scope>test</scope>
        </dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet-version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis-version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${mybatis-spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${springframework-version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
            <groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j-version}</version>
        </dependency>
		<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j-version}</version>
        </dependency>
        <dependency>
			<artifactId>commons-logging</artifactId>
			<groupId>commons-logging</groupId>
			<version>${commons-logging-version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql-version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${druid-version}</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>${commons-lang-version}</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>${commons-fileupload-version}</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io-version}</version>
		</dependency>
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>${fastjson-version}</version>
		</dependency>
		<dependency>
		    <groupId>commons-codec</groupId>
		    <artifactId>commons-codec</artifactId>
		    <version>${commons-codec-version}</version>
		</dependency>
		<dependency>
			<groupId>commons-configuration</groupId>
			<artifactId>commons-configuration</artifactId>
			<version>${commons-configuration-version}</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-core</artifactId>
		    <version>${shiro-version}</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-spring</artifactId>
		    <version>${shiro-version}</version>
		</dependency>
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>${quartz-version}</version>
			<exclusions>
				<exclusion>
					<artifactId>c3p0</artifactId>
					<groupId>c3p0</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.github.axet</groupId>
			<artifactId>kaptcha</artifactId>
			<version>${kaptcha-version}</version>
		</dependency>
		<!-- Velocity视图所需jar -->
		<dependency>
			<artifactId>velocity</artifactId>
            <groupId>org.apache.velocity</groupId>
			<version>${velocity-version}</version>
		</dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>${velocity-tools-version}</version>
            <exclusions>
            	<exclusion>
            		<artifactId>dom4j</artifactId>
            		<groupId>dom4j</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>oro</artifactId>
            		<groupId>oro</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>sslext</artifactId>
            		<groupId>sslext</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>struts-core</artifactId>
            		<groupId>org.apache.struts</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>struts-taglib</artifactId>
            		<groupId>org.apache.struts</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>struts-tiles</artifactId>
            		<groupId>org.apache.struts</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>commons-validator</artifactId>
            		<groupId>commons-validator</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>commons-beanutils</artifactId>
            		<groupId>commons-beanutils</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>commons-chain</artifactId>
            		<groupId>commons-chain</groupId>
            	</exclusion>
            	<exclusion>
            		<artifactId>commons-collections</artifactId>
            		<groupId>commons-collections</groupId>
            	</exclusion>
            </exclusions>
        </dependency>
        <!-- JSP视图所需jar -->
        <dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl-version}</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${taglibs-version}</version>
		</dependency>
		<!-- Freemarker视图所需jar -->
        <dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>${freemarker-version}</version>
		</dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

    </dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java-version}</source>
					<target>${java-version}</target>
					<!-- true:跳过测试 -->
					<skip>true</skip>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<path>/</path>
					<charset>UTF-8</charset>
					<port>8080</port>
					<uriEncoding>UTF-8</uriEncoding>
				</configuration>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.js</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<finalName>renren-security</finalName>
	</build>
</project>


text:
package uk.co.nevarneyok.entities;

public class Page {

    private long id;
    private String title;
    private String text;

    public Page() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Page page = (Page) o;

        if (id != page.id) return false;
        if (title != null ? !title.equals(page.title) : page.title != null) return false;
        return !(text != null ? !text.equals(page.text) : page.text != null);
    }

    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + (title != null ? title.hashCode() : 0);
        result = 31 * result + (text != null ? text.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Page{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", text='" + text + '\'' +
                '}';
    }
}


text:
#pragma once
#include <aws/ecs/ECS_EXPORTS.h>
#include <aws/ecs/ECSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ecs/model/AutoScalingGroupProviderUpdate.h>
#include <utility>

namespace Aws
{
namespace ECS
{
namespace Model
{

  /**
   */
  class AWS_ECS_API UpdateCapacityProviderRequest : public ECSRequest
  {
  public:
    UpdateCapacityProviderRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateCapacityProvider"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the capacity provider to update.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The name of the capacity provider to update.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the capacity provider to update.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the capacity provider to update.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the capacity provider to update.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The name of the capacity provider to update.

     */
    inline UpdateCapacityProviderRequest& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The name of the capacity provider to update.

     */
    inline UpdateCapacityProviderRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The name of the capacity provider to update.

     */
    inline UpdateCapacityProviderRequest& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
An object that represent the parameters to update for the Auto Scaling group
     * capacity provider.

     */
    inline const AutoScalingGroupProviderUpdate& GetAutoScalingGroupProvider() const{ return m_autoScalingGroupProvider; }

    /**
     *
An object that represent the parameters to update for the Auto Scaling group
     * capacity provider.

     */
    inline bool AutoScalingGroupProviderHasBeenSet() const { return m_autoScalingGroupProviderHasBeenSet; }

    /**
     *
An object that represent the parameters to update for the Auto Scaling group
     * capacity provider.

     */
    inline void SetAutoScalingGroupProvider(const AutoScalingGroupProviderUpdate& value) { m_autoScalingGroupProviderHasBeenSet = true; m_autoScalingGroupProvider = value; }

    /**
     *
An object that represent the parameters to update for the Auto Scaling group
     * capacity provider.

     */
    inline void SetAutoScalingGroupProvider(AutoScalingGroupProviderUpdate&& value) { m_autoScalingGroupProviderHasBeenSet = true; m_autoScalingGroupProvider = std::move(value); }

    /**
     *
An object that represent the parameters to update for the Auto Scaling group
     * capacity provider.

     */
    inline UpdateCapacityProviderRequest& WithAutoScalingGroupProvider(const AutoScalingGroupProviderUpdate& value) { SetAutoScalingGroupProvider(value); return *this;}

    /**
     *
An object that represent the parameters to update for the Auto Scaling group
     * capacity provider.

     */
    inline UpdateCapacityProviderRequest& WithAutoScalingGroupProvider(AutoScalingGroupProviderUpdate&& value) { SetAutoScalingGroupProvider(std::move(value)); return *this;}

  private:

    Aws::String m_name;
    bool m_nameHasBeenSet = false;

    AutoScalingGroupProviderUpdate m_autoScalingGroupProvider;
    bool m_autoScalingGroupProviderHasBeenSet = false;
  };

} // namespace Model
} // namespace ECS
} // namespace Aws


text:
from django.views.generic.base import TemplateView

class Index(TemplateView):
    template_name = 'home/index.html'


text:
package com.streamsets.datacollector.config;

import com.streamsets.pipeline.api.impl.Utils;

import java.util.List;

public class RawSourceDefinition {

  private final String rawSourcePreviewerClass;
  private final String mimeType;
  List<ConfigDefinition> configDefinitions;

  public RawSourceDefinition(String rawSourcePreviewerClass, String mimeType,
                             List<ConfigDefinition> configDefinitions) {
    this.rawSourcePreviewerClass = rawSourcePreviewerClass;
    this.configDefinitions = configDefinitions;
    this.mimeType = mimeType;
  }

  public String getRawSourcePreviewerClass() {
    return rawSourcePreviewerClass;
  }

  public List<ConfigDefinition> getConfigDefinitions() {
    return configDefinitions;
  }

  public String getMimeType() {
    return mimeType;
  }

  @Override
  public String toString() {
    return Utils.format("RawSourceDefinition[rawSourcePreviewerClass='{}' mimeType='{}']", getRawSourcePreviewerClass(),
      getMimeType());
  }
}


text:
"""Pytest configuration."""

from __future__ import absolute_import, print_function

import os
import shutil
import tempfile

import pytest
from flask import Flask
from flask.cli import ScriptInfo
from flask_admin import Admin
from flask_babelex import Babel
from flask_celeryext import FlaskCeleryExt
from flask_mail import Mail
from flask_menu import Menu
from invenio_db import InvenioDB, db
from invenio_i18n import InvenioI18N
from simplekv.memory.redisstore import RedisStore
from sqlalchemy_utils.functions import create_database, database_exists, \
    drop_database

from invenio_accounts import InvenioAccounts
from invenio_accounts.admin import role_adminview, session_adminview, \
    user_adminview
from invenio_accounts.testutils import create_test_user

def _app_factory(config=None):
    """Application factory."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        ACCOUNTS_USE_CELERY=False,
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND="cache",
        LOGIN_DISABLED=False,
        MAIL_SUPPRESS_SEND=True,
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
        SERVER_NAME='example.com',
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    app.config.update(config or {})
    Menu(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    return app

def _database_setup(app, request):
    """Set up the database."""
    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            if database_exists(str(db.engine.url)):
                drop_database(str(db.engine.url))
            # Delete sessions in kvsession store
            if hasattr(app, 'kvsession_store') and \
                    isinstance(app.kvsession_store, RedisStore):
                app.kvsession_store.redis.flushall()
        shutil.rmtree(app.instance_path)

    request.addfinalizer(teardown)
    return app

@pytest.yield_fixture()
def base_app(request):
    """Flask application fixture."""
    app = _app_factory()
    _database_setup(app, request)
    yield app

@pytest.yield_fixture()
def app(request):
    """Flask application fixture with Invenio Accounts."""
    app = _app_factory()
    InvenioAccounts(app)

    from invenio_accounts.views.settings import blueprint
    app.register_blueprint(blueprint)

    _database_setup(app, request)
    yield app

@pytest.fixture
def script_info(app):
    """Get ScriptInfo object for testing CLI."""
    return ScriptInfo(create_app=lambda info: app)

@pytest.fixture
def task_app(request):
    """Flask application with Celery enabled."""
    app = _app_factory(dict(
        ACCOUNTS_USE_CELERY=True,
        MAIL_SUPPRESS_SEND=True,
    ))
    FlaskCeleryExt(app)
    InvenioAccounts(app)
    _database_setup(app, request)
    return app

@pytest.fixture
def cookie_app(request):
    """Flask application  enabled."""
    app = _app_factory(dict(
        SESSION_COOKIE_SECURE=True,
        SESSION_COOKIE_DOMAIN='example.com',
    ))
    InvenioAccounts(app)
    _database_setup(app, request)
    return app

@pytest.fixture
def admin_view(app):
    """Admin view fixture."""
    assert isinstance(role_adminview, dict)
    assert isinstance(user_adminview, dict)
    assert isinstance(session_adminview, dict)

    assert 'model' in role_adminview
    assert 'modelview' in role_adminview
    assert 'model' in user_adminview
    assert 'modelview' in user_adminview
    assert 'model' in session_adminview
    assert 'modelview' in session_adminview

    admin = Admin(app, name="Test")

    user_adminview_copy = dict(user_adminview)
    user_model = user_adminview_copy.pop('model')
    user_view = user_adminview_copy.pop('modelview')
    admin.add_view(user_view(user_model, db.session, **user_adminview_copy))

    admin.add_view(session_adminview['modelview'](
        session_adminview['model'], db.session,
        category=session_adminview['category']))

@pytest.fixture()
def app_i18n(app):
    """Init invenio-i18n."""
    InvenioI18N(app)
    return app

@pytest.fixture()
def users(app):
    """Create users."""
    user1 = create_test_user(email='info@inveniosoftware.org',
                             password='tester')
    user2 = create_test_user(email='info2@inveniosoftware.org',
                             password='tester2')

    return [
        {'email': user1.email, 'id': user1.id,
         'password': user1.password_plaintext},
        {'email': user2.email, 'id': user2.id,
         'password': user2.password_plaintext},
    ]


text:
package com.adamg.materialtemplate.ui.views;

/**
 * View interface created to abstract the view. Base marker class of the UI piece of the MVP paradigm.
 *
 * @author Adam Greenberg
 * @version 1 on 6/28/15
 *          All code under The MIT License (MIT) unless otherwise noted.
 */
public interface View {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <!-- %p:Level %m:Message %c.%M:Package+Method %F:%L:File+Line -->
    <property name="pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} | %p | %m | %c.%M | %F:%L %n"/>

    <!-- Print in Console -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder charset="UTF-8">
            <pattern>${pattern}</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>


text:
class Widget {
    public:
        bool isValidated() const { return true; }
        bool isProcessed() const { return true; }
        bool isArchived() const { return true; }

};

int main() {
    auto pw = std::make_unique<Widget>();

    auto func1 = [pw = std::move(pw)]
                {
                    return pw->isValidated() &&
                         pw->isArchived();
                };

    auto func2 = [pw = std::make_unique<Widget>()]
                 {
                     return pw->isValidated() &&
                            pw->isArchived();
                 };

    return 0;
}


text:
import React from 'react';
import {mount} from 'enzyme';
import Immutable, {Map} from 'immutable';

import {ManageCoursePage} from './ManageCoursePage';

describe('Manage Course Page Tests', () => {
	const props = {
		actions: {},
		authors: Immutable.fromJS(
			[
				{
					id: 0,
					firstName: 'Bill',
					lastName: 'Anderson',
					value: 0
				},
				{
					id: 1,
					firstName: 'John',
					lastName: 'Appleseed',
					value: 1
				}
			]
		),
		courseFormActions: {},
		coursesCntr: Map({}),
		modalData: Map({}),
		loading: false
	};
	const wrapper = mount(<ManageCoursePage {...props}/>);
	const saveButton = wrapper.find('.manage-course-form__action-btn');
	saveButton.simulate('click');

	describe('Form Validation', () => {
		it('Title', () => {
			// Positive tests
			expect(wrapper.state().errors.title).toBe('Please enter a title with at least three characters');
		});

		it('Author', () => {
			// Positive tests
			expect(wrapper.state().errors.authorId).toBe('Please select an author');
		});

		it('Length', () => {
			// Positive tests
			expect(wrapper.state().errors.length).toBe('Please enter a length value');
		});

		it('Category', () => {
			// Positive tests
			expect(wrapper.state().errors.category).toBe('Please enter a category name');
		});

		it('Watch URL', () => {
			// Positive tests
			expect(wrapper.state().errors.watchHref).toBe('Please enter a watch URL');
		});
	});

	describe('Form Updates', () => {
		it('Set Title', () => {
			// Set the value
			const titleElm = wrapper.find('.manage-course-form__title-input');
			titleElm.node.value = 'Testing Title';
			titleElm.simulate('change');

			// Positive tests
			expect(wrapper.state().course.title).toBe('Testing Title');
		});

		// it("Set Author", () => {
		//    // Set the value
		//    const authorElm = wrapper.find(".manage-course-form__author-select");
		//    authorElm.node.value = 0;
		//    authorElm.simulate("keyDown", { keyCode: 40 });

		//    // Positive tests
		//    expect(wrapper.state().course.author).toBe("0");
		// });

		it('Set Category', () => {
			// Set the value
			const catElm = wrapper.find('.manage-course-form__category-input');
			catElm.node.value = 'Testing Category';
			catElm.simulate('change');

			// Positive tests
			expect(wrapper.state().course.category).toBe('Testing Category');
		});

		it('Set Length', () => {
			// Set the value
			const lengthElm = wrapper.find('.manage-course-form__length-input');
			lengthElm.node.value = 'Testing Length';
			lengthElm.simulate('change');

			// Positive tests
			expect(wrapper.state().course.length).toBe('Testing Length');
		});

		it('Set Watch HREF', () => {
			// Set the value
			const watchElm = wrapper.find('.manage-course-form__watchHref-input');
			watchElm.node.value = 'Testing Watch HREF';
			watchElm.simulate('change');

			// Positive tests
			expect(wrapper.state().course.watchHref).toBe('Testing Watch HREF');
		});

		// //manage-course-form__cancel-btn
		// it("Cancel button clicked", () => {
		//    // Set the value
		//    const cancelBtnElm = wrapper.find(".manage-course-form__cancel-btn");
		//    cancelBtnElm.simulate("click");

		//    // Positive tests
		//    expect(wrapper.state().course.watchHref).toBe("Testing Watch HREF");
		// });
	});

	describe('Form Validation', () => {
		it('Title', () => {
			// Positive tests
			expect(wrapper.state().errors.title).toBe('Please enter a title with at least three characters');
		});
	});
});


text:
jRate - SVG based Rating jQuery plugin
=======================================

This jquery plugin helps to generate SVG based RATING with various fancy features. Download and include this plugin in your html file.

#####[Demo Page](http://www.toolitup.com/jRate.html)

![Demo](https://rawgit.com/senthilporunan/jRate/master/images/jRate-Star-Demo.gif)

![Twitter Demo](https://rawgit.com/senthilporunan/jRate/master/images/jRate-twitter-demo.gif)

## React jRate component

#### [react-jrate](https://github.com/senthilporunan/react-jrate)

### Including it on your page

Include jQuery and this plugin on your page.
```
<script src="jRate.js"></script>

```
### Basic Usage
```
<div id="jRate"></div>
$("#jRate").jRate();
```
#Features
###Start Color and End Color

Set your favourite start and end color. By giving value in the form of hex value, rgb value or standard color name. We can use one color format also by giving same start and end color.

```js
$("#jRate").jRate({
  startColor: "cyan",
  endColor: "blue"
});
```
###Initial Value
Set your own default initial value.
```js
$("#jRate").jRate({
  rating:2
});
```
###Width and Height
We can customize our own value for width and height.
```js
$("#jRate").jRate({
  width: 70,
  height: 70
});
```
####Shape
We can chooose shape from available list. If you need more shapes, raise feature request in github. Available shapes are STAR, RECTANGLE, SQUARE, CIRCLE, RHOMBUS, TRIANGLE.
```js
$("#jRate").jRate({
  shape: 'RHOMBUS'
});
```
####Width and Height Growth
Make the shapes from smaller to bigger. We can use growth field to make this happen.
```js
$("#jRate").jRate({
  widthGrowth: 0.2,
  heightGrowth: 0.2
});
```

####Count
Number of shapes was decided by the count parameter. We can customize own numeric value for it.
```js
$("#jRate").jRate({
  count: 10
});
```
####Background Color
Set your favourite background color. By giving value in the form of hex value, rgb value or standard color name.
```js
$("#jRate").jRate({
  backgroundColor: 'black'
});
```
####Color Transparency
Set transparency value between 0 and 1.
```js
$("#jRate").jRate({
  transparency: 0.5
});
```
####Gap
We can set our own gap between two shapes. We can customize our own values in it.
```js
$("#jRate").jRate({
  shapeGap: '10px'
});
```
####Opacity
Set opacity value.
```js
$("#jRate").jRate({
  opacity: 0.3
});
```

####Minimum and Maximum Value
Set a desired minimum and maximum value.
```js
$("#jRate").jRate({
  min: 10,
  max: 15
});
```
####Precision
Set the precision value.
```js
$("#jRate").jRate({
  precision: 0
});
```
####Stroke Width
Set the stroke width for STAR, CIRCLE, RECTANGLE, RHOMBUS, TRIANGLE only.
```js
$("#jRate").jRate({
  strokeWidth: '25px'
});
```
####Horizontal
We can set a boolean variable to make horizontal or vertical. And, set a boolean value for reverse.
```js
$("#jRate").jRate({
  horizontal: false
});
```
####Reverse
We can set a boolean variable to make reverse or not.
```js
$("#jRate").jRate({
  reverse: true
});
```
####ReadOnly
Set the readonly value.
```js
$("#jRate").jRate({
  readOnly: true
});
```
####onChange
Write your own methods to do own action when the rating value change action occurs.
```js
$("#jRate").jRate({
  onChange: function(rating) {
    $('#demo-onchange-value').text("Your Rating: "+rating);
  }
});
```
####onSet
Write your own methods to do own action when the rating value click or set action occurs.
```js
$("#jRate").jRate({
  onSet: function(rating) {
    $('#demo-onset-value').text("Selected Rating: "+rating);
  }
});
```
####License
This plugin is licensed under the [MIT license](https://github.com/senthilporunan/jRate/blob/master/LICENSE).

Copyright (c) 2015 [Senthil Porunan](http://www.toolitup.com/)


text:
namespace Halley {
	class ECSWindow : public UIWidget
	{
	public:
		explicit ECSWindow(UIFactory& factory, Project& project);

		void onMakeUI() override;

	private:
		UIFactory& factory;
		Project& project;

		void populateSystem(const String& name);
		void populateComponent(const String& name);
	};
}


text:
Copyright (C) 2017 Google, Inc.
License: Apache 2.0

## Disclaimer

This is not an official Google product. For research purposes only.

## What is this R package for?

This R package (`amss`) is an open-source implementation of the Aggregate
Marketing System Simulator developed at Google [1].

This package provides object classes, methods, and functions related to
simulated aggregate time series marketing data. It provides functionality to
generate both simulated data and associated ground truth metrics. Version 1.0
implements the simulation framework presented in [1].

## Documentation

See the vignette and the manual in this package (in the subdirectory `inst/doc/`
in the source package).

## References

[1] Zhang, S. and Vaver, J. (2017)
    [Introduction to the Aggregate Marketing System Simulator](https://research.google.com/pubs/pub45996.html).


text:
'use strict';

const program = require('commander');

const pkg = require('./../package.json');
const config = require('./config');
const { handleError, GeneralError } = require('./lib/errors');

function main() {
  const miteTracker = require('./lib/mite-tracker')(config.get());
  return miteTracker.get()
    .then(timeEntryId => {
      if (!timeEntryId) {
        throw new GeneralError('No running time entry found.');
      }
      return miteTracker.stop(timeEntryId);
    })
    .then((timeEntryId) => process.stdout.write(`${timeEntryId}\n`))
    .catch(handleError);
}

try {
  program
    .version(pkg.version)
    .description('stops any running time entry')
    .action(main)
    .parse();
} catch (err) {
  handleError(err);
}


text:
set -e

$(pwd)/scripts/build-container.sh

docker run \
    --rm \
    --name dev-css \
    -it \
    -v $(pwd):/app/src \
    stephanos/subvoc \
    /app/node_modules/postcss-cli/bin/postcss --use autoprefixer /app/static/css/**/*.css --replace


text:
class Create<%= model_name.classify.pluralize %> < ActiveRecord::Migration
  def change
    create_table :<%= model_name.underscore.pluralize %> do |t|
      t.string   'from'
      t.string   'to'

      #Timestamp for the last send attempt, 0 means, that there was no send attempt yet
      t.integer  'last_send_attempt', :default => 0

      #Mail body including headers
      t.text     'mail'

      #Custom delivery time, ArMailer won't send the email prior to this time
      t.datetime 'delivery_time'

      #Custom SMTP settings per email
      t.text     'smtp_settings'

      #You can add further attributes here, they can then be assigned
      #to the email record using the +ar_mailer_attribute+ method from
      #within mailer methods. Example:
      #
      # In the migration:
      #  t.integer :client_id
      #
      # Inside the mailer method:
      #   ar_mailer_attribute :client_id, @client.id

      t.timestamps
    end
  end
end


text:
import java.io.File;
import java.io.IOException;
import java.util.*;

public class PhonewordLister
{
    private PrefixTree ptTree;
    public PrefixTree getTree ( ) {return ptTree;}

    // this constructor should set "tree" to the prefix tree created from Knuth's word list
    public PhonewordLister ( ) throws IOException
    {
    	ptTree = new PrefixTree();
		Scanner scanner = new Scanner(new File("Knuth'swordlist.txt"));
		while(scanner.hasNextLine()){
			String line = scanner.nextLine();
			ptTree.addString(line);
		}
    }

	// returns Scrabble score if w is made only of letters, returns 0 otherwise
    public static int scrabbleScore (String strWord)
    {
        int [ ] value = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3,
                         1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
        int sum = 0;
        for (int i = 0; i < strWord.length( ); i++)
        {
		    if ('a' <= strWord.charAt(i) && strWord.charAt(i) <= 'z')
		    	sum += value[strWord.charAt(i) - 'a'];
		    else if ('A' <= strWord.charAt(i) && strWord.charAt(i) <= 'Z')
		    	sum += value[strWord.charAt(i) - 'A'];
	        else
	        	return 0;
        }
        return sum;
    }

	//  The input "digits" is to be a string of five characters, each a digit in the range 2-9 or a *.
    //  If it is of this form, return an array of all phonewords that can be made from the input,
    //  in order of Scrabble score with highest score first, treating a * as a wild-card.  (Handling *'s is extra credit.)
    //  If the input is invalid, return an array of length 0.
    public String [ ] list (String strDigits)
    {
    	PriorityQueue<ScrabbleWord> pqWords= new PriorityQueue<ScrabbleWord>();	//Will organize the 5 letter words found
    	PTNode current = ptTree.getRoot();										//Will traverse through the tree to find the words
    	PTNode parent2 = new PTNode("");										//Keep track of the parent nodes so that current can go back and look through another letter
    	PTNode parent3 = new PTNode("");
    	PTNode parent4 = new PTNode("");

    	String[] letters = new String[strDigits.length()];			//An array that will hold the letters that correspond to the digits entered

    	for(int i = 0; i < strDigits.length(); i++)//Go through the digits string and figure out the letters that correspond with each digit and set it the the letters array
    	{
    		if(strDigits.charAt(i) == '2') letters[i] = "abc";
    		else if(strDigits.charAt(i) == '3') letters[i] = "def";
    		else if(strDigits.charAt(i) == '4') letters[i] = "ghi";
    		else if(strDigits.charAt(i) == '5') letters[i] = "jkl";
    		else if(strDigits.charAt(i) == '6') letters[i] = "mno";
    		else if(strDigits.charAt(i) == '7') letters[i] = "pqrs";
    		else if(strDigits.charAt(i) == '8') letters[i] = "tuv";
    		else if(strDigits.charAt(i) == '9') letters[i] = "wxyz";
    		else if(strDigits.charAt(i) == '*') letters[i] = "abcdefghijklmnopqrstuvwxyz";
    		else letters[i] = "";
    	}

    	for(int i = 0; i < letters[0].length(); i++)//5 nested for loops, each for loop is for each digit/index of the letters array
    	{
    		current = ptTree.getRoot();
			if(current.getChild(letters[0].charAt(i)) == null)
				continue;	//If the letter of the first digit is not found, then move onto the next letter of the first digit
			else
				current = current.getChild(letters[0].charAt(i));

    		for(int j = 0; j < letters[1].length(); j++)
    		{
    			if(current.getChild(letters[1].charAt(j)) == null)
    				continue;	//If the letter of the 2nd digit is not found, then move onto the next letter of the 2nd digit
    			else
    			{
    				parent2 = current;
    				current = parent2.getChild(letters[1].charAt(j));
    			}

    			for(int k = 0; k < letters[2].length(); k++)
    			{
    				if(current.getChild(letters[2].charAt(k)) == null)
    					continue;//If the letter of the 3rd digit is not found, then move onto the next letter of the 3rd digit
    				else
    				{
    					parent3 = current;
    					current = parent3.getChild(letters[2].charAt(k));
    				}

    				for(int x = 0; x < letters[3].length(); x++)
    				{
    					if(current.getChild(letters[3].charAt(x)) == null)
    						continue;//If the letter of the 4th digit is not found, then move onto the next letter of the 4th digit
    					else
    					{
    						parent4 = current;
    						current = parent4.getChild(letters[3].charAt(x));
    					}

    					for(int y = 0; y < letters[4].length(); y++)
    					{
    						if(current.getChild(letters[4].charAt(y)) == null)
    							continue;//If the letter of the 5th digit is not found, then move onto the next letter of the 5th digit
    						else{//add to the priorityqueue the word found using the compare method in the ScrabbleWord class
    							pqWords.add(new ScrabbleWord(current.getChild(letters[4].charAt(y)).getElem(), scrabbleScore(current.getChild(letters[4].charAt(y)).getElem())));
    						}
    					}
    					current = parent4;
    				}
    				current = parent3;
    			}
    			current = parent2;
    		}
    	}

    	String[] words = new String[pqWords.size()];	//The list that will be returned

    	for(int i = 0; i < words.length; i++){	//Take everything in the queue and put it into the array that is to be returned
    		words[i] = pqWords.poll().getWord();
    	}

		return words;
    }
}


text:
<template name="GlobalVoicesWidget">

Global Voices

  {{# if Template.subscriptionsReady }}

{{ countryName }}

    {{# each feedItems }}
      {{> GVItem }}
    {{/each}}

  {{else}}
    {{ widgetLoading }}
  {{/if}}
</template>

<template name="GVItem">

{{ title }}

{{ niceDate }}

</template>


text:
package io.youi.path

import scala.collection.mutable.ListBuffer

case class Path(actions: List[PathAction]) extends PathBuilder with PathAction {
  lazy val boundingBox: BoundingBox = Path.boundingBox(actions)
  lazy val path2d: Val[Path2D] = Val(createPath2d(ui.ratio))

  override def draw(context: Context, x: Double, y: Double, scaleX: Double, scaleY: Double): Unit = {
    actions.foreach(_.draw(context, x, y, scaleX, scaleY))
  }

  def modify(mx: Double => Double, my: Double => Double): Path = {
    val updated = actions.map {
      case CurveTo(x1, y1, x2, y2, x, y) => CurveTo(mx(x1), my(y1), mx(x2), my(y2), mx(x), my(y))
      case LineTo(x, y) => LineTo(mx(x), my(y))
      case MoveTo(x, y) => MoveTo(mx(x), my(y))
      case QuadraticCurveTo(x1, y1, x, y) => QuadraticCurveTo(mx(x1), my(y1), mx(x), my(y))
      case Rectangle(x, y, width, height, begin, close) => Rectangle(mx(x), my(y), mx(width), my(height), begin, close)
      case BeginPath => BeginPath
      case ClosePath => ClosePath
      case action => throw new RuntimeException(s"Unsupported PathAction: $action.")
    }
    Path(updated)
  }

  private def createPath2d(ratio: => Double): Path2D = {
    val p = new Path2D
    def s(v: Double): Double = v * ratio
    actions.foreach {
      case CurveTo(x1, y1, x2, y2, x, y) => p.bezierCurveTo(s(x1), s(y1), s(x2), s(y2), s(x), s(y))
      case LineTo(x, y) => p.lineTo(s(x), s(y))
      case MoveTo(x, y) => p.moveTo(s(x), s(y))
      case QuadraticCurveTo(x1, y1, x, y) => p.quadraticCurveTo(s(x1), s(y1), s(x), s(y))
      case BeginPath => // No begin in path2d
      case ClosePath => p.closePath()
      case action => throw new RuntimeException(s"Unsupported PathAction: $action.")
    }
    p
  }

  def scale(x: Double = 1.0, y: Double = 1.0): Path = modify(_ * x, _ * y)

  def shift(adjustX: Double, adjustY: Double): Path = modify(_ + adjustX, _ + adjustY)

  def fix(): Path = modify(Path.fix, Path.fix)

  override def withAction(action: PathAction): Path = Path(actions ::: List(action))

  def withoutOpen(): Path = Path(actions.filterNot(_ == BeginPath))
  def withoutClose(): Path = Path(actions.filterNot(_ == ClosePath))

  override def toString: String = s"Path(${actions.mkString(", ")})"
}

object Path extends PathBuilder {
  lazy val empty: Path = Path(Nil)

  private lazy val actionCharacters = Set('M', 'L', 'C', 'Q', 'Z', 'H', 'V')

  private lazy val MoveRegex = """M[ ]?([-]?[0-9.]+)[ ]?([-]?[0-9.]+)""".r
  private lazy val LineRegex = """L[ ]?([-]?[0-9.]+)[ ]?([-]?[0-9.]+)""".r
  private lazy val HorizontalLineRegex = """H[ ]?([-]?[0-9.]+)""".r
  private lazy val VerticalLineRegex = """V[ ]?([-]?[0-9.]+)""".r
  private lazy val CurveRegex = """C[ ]?([-]?[0-9.]+)[ ]?([-]?[0-9.]+)[ ]?([-]?[0-9.]+)[ ]?([-]?[0-9.]+)[ ]?([-]?[0-9.]+)[ ]?([-]?[0-9.]+)""".r
  private lazy val QuadraticRegex = """Q([- ]?[0-9.]+)([- ]?[0-9.]+)([- ]?[0-9.]+)([- ]?[0-9.]+)""".r

  def apply(actions: PathAction*): Path = {
    var list = actions.toList
    if (list.head != BeginPath) {
      list = BeginPath :: list
    }
    if (list.last != ClosePath) {
      list = list ::: List(ClosePath)
    }
    Path(list)
  }

  def merge(paths: Path*): Path = Path(paths.flatMap(_.actions).toList)

  def apply(pathString: String): Path = {
    val b = new StringBuilder
    val actions = ListBuffer.empty[PathAction]
    var currentX = 0.0
    var currentY = 0.0
    def s2a(s: String): PathAction = s match {
      case MoveRegex(x, y) => {
        currentX = x.toDouble
        currentY = y.toDouble
        MoveTo(currentX, currentY)
      }
      case LineRegex(x, y) => {
        currentX = x.toDouble
        currentY = y.toDouble
        LineTo(currentX, currentY)
      }
      case HorizontalLineRegex(x) => {
        currentX = x.toDouble
        LineTo(currentX, currentY)
      }
      case VerticalLineRegex(y) => {
        currentY = y.toDouble
        LineTo(currentX, currentY)
      }
      case CurveRegex(x1, y1, x2, y2, x, y) => {
        currentX = x.toDouble
        currentY = y.toDouble
        CurveTo(x1.toDouble, y1.toDouble, x2.toDouble, y2.toDouble, currentX, currentY)
      }
      case QuadraticRegex(x1, y1, x, y) => {
        currentX = x.toDouble
        currentY = y.toDouble
        QuadraticCurveTo(x1.toDouble, y1.toDouble, currentX, currentY)
      }
      case "Z" => ClosePath
      case _ => throw new RuntimeException(s"Unknown action: [$s]")
    }

    pathString.replaceAll("[,]", " ").toUpperCase.foreach { c =>
      if (actionCharacters.contains(c)) {
        if (b.nonEmpty) {
          actions += s2a(b.toString().trim)
        }
        b.clear()
      }
      b.append(c)
    }
    if (b.nonEmpty) {
      actions += s2a(b.toString().trim)
    }

    Path(actions.toList)
  }

  def boundingBox(pathActions: List[PathAction]): BoundingBox = {
    var minX = Double.MaxValue
    var minY = Double.MaxValue
    var maxX = Double.MinValue
    var maxY = Double.MinValue

    var cx = 0.0
    var cy = 0.0

    def adjustTo(newX: Double, newY: Double, oldX: Double = cx, oldY: Double = cy, updateCoordinates: Boolean = true): Unit = {
      minX = math.min(oldX, math.min(minX, newX))
      minY = math.min(oldY, math.min(minY, newY))
      maxX = math.max(oldX, math.max(maxX, newX))
      maxY = math.max(oldY, math.max(maxY, newY))

      cx = newX
      cy = newY
    }

    pathActions.foreach {
      case BeginPath => // Nothing
      case ClosePath => // Nothing
      case CurveTo(_, _, _, _, x, y) => adjustTo(x, y)
      case LineTo(x, y) => adjustTo(x, y)
      case MoveTo(x, y) => {
        cx = x
        cy = y
      }
      case QuadraticCurveTo(_, _, x, y) => adjustTo(x, y)
      case Rectangle(x, y, width, height, _, _) => adjustTo(x + width, y + height, updateCoordinates = false)
      case RoundedRectangle(x, y, width, height, _) => adjustTo(x + width, y + height, updateCoordinates = false)
    }
    BoundingBox(minX, minY, maxX, maxY)
  }

  override def withAction(action: PathAction): Path = Path(List(action))

  def fix(value: Double): Double = value
}


text:
@charset "utf-8";

*:focus {
	outline: none;
}
/* fade */
.jbox-fade {
	background-color: #000000;
}
/* drag */
.jbox-drag {
	border: 1px dashed #8e0674;
}
/* jbox */
div.jbox {
	padding: 0px;
	border: none;
	font-size: 12px;
}
/* border */
div.jbox .jbox-border {
	background: none repeat scroll 0 0 #000000;
	filter: alpha(opacity = 20);
	-moz-opacity: 0.2;
	opacity: 0.2;
}
/* container */
div.jbox .jbox-container {
	background-color: #ffffff;
	border: 1px solid #999999;
}
/* title-panel */
div.jbox .jbox-title-panel {
	background: #8e0674;
	background: -webkit-gradient(linear, left top, left bottom, from(#9a1f82),
		to(#72055d));
	background: -moz-linear-gradient(top, #9a1f82, #72055d);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#9a1f82',
		endColorstr='#72055d');
	border-bottom: 1px solid #999999;
}

div.jbox .jbox-title {
	font-weight: bold;
	color: #ffffff;
}

div.jbox .jbox-title-icon {
	background: url(images/jbox-title-icon.gif) no-repeat scroll 3px 5px
		transparent;
}

div.jbox .jbox-close, div.jbox .jbox-close-hover {
	background: url(images/jbox-close1.gif) no-repeat scroll 0px 0px
		transparent;
}

div.jbox .jbox-close-hover {
	background-position: -16px 0;
}
/* content */
div.jbox .jbox-content {
	min-height: 24px;
	line-height: 18px;
	color: #444444;
}

div.jbox .jbox-content-loading {
	background-color: #E6E6E6;
}

div.jbox .jbox-content-loading-image {
	background: url(images/jbox-content-loading.gif) no-repeat bottom center;
}
/* button-panel */
div.jbox .jbox-button-panel {
	border-top: 1px solid #CCCCCC;
	background-color: #EEEEEE;
}

div.jbox .jbox-bottom-text {
	text-indent: 10px;
	color: #444444;
}

div.jbox .jbox-button {
	background: #8e0674;
	background: -webkit-gradient(linear, left top, left bottom, from(#9a1f82),
		to(#72055d));
	background: -moz-linear-gradient(top, #9a1f82, #72055d);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#9a1f82',
		endColorstr='#72055d');
	border: #47033a 1px solid;
	color: #fff;
	border-radius: 3px 3px 3px 3px;
	margin: 1px 7px 0px 0px;
	height: 22px;
	cursor: default;
}

div.jbox .jbox-button-hover {
	background: #8e0674;
	background: -webkit-gradient(linear, left top, left bottom, from(#8e0674),
		to(#550446));
	background: -moz-linear-gradient(top, #8e0674, #550446);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8e0674',
		endColorstr='#550446');
}

div.jbox .jbox-button-active {
	background: -webkit-gradient(linear, left top, left bottom, from(#550446),
		to(#8e0674));
	background: -moz-linear-gradient(top, #550446, #8e0674);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#550446',
		endColorstr='#8e0674');
}

div.jbox-warning .jbox .jbox-button-panel {
	background-color: #FFFFFF;
}
/* tip-color */
div.jbox .jbox-tip-color {
	background: #8e0674;
	background: -webkit-gradient(linear, left top, left bottom, from(#8e0674),
		to(#550446));
	background: -moz-linear-gradient(top, #8e0674, #550446);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8e0674',
		endColorstr='#550446');
	border-color: #47033a;
	border-radius: 3px 3px 3px 3px;
	color: #fff;
}
/* icons */
div.jbox span.jbox-icon {
	background: url(images/jbox-icons.png) no-repeat scroll 0 0 transparent;
	_background: url(images/jbox-icons-ie6.gif) no-repeat scroll 0 0
		transparent;
}

div.jbox span.jbox-icon-info {
	background-position: 0 0;
}

div.jbox span.jbox-icon-question {
	background-position: -36px 0;
}

div.jbox span.jbox-icon-success {
	background-position: -72px 0;
}

div.jbox span.jbox-icon-warning {
	background-position: -108px 0;
}

div.jbox span.jbox-icon-error {
	background-position: -144px 0;
}

div.jbox span.jbox-icon-none {
	display: none;
	overflow: hidden;
}

div.jbox span.jbox-icon-loading {
	background: url(images/jbox-loading1.gif) no-repeat scroll 0 0
		transparent;
}