text:
package com.facebook.buck.rules.keys;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.AddsToRuleKey;
import com.facebook.buck.rules.ArchiveMemberSourcePath;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.DefaultBuildTargetSourcePath;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.NonHashableSourcePathContainer;
import com.facebook.buck.rules.PathSourcePath;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SingleThreadedBuildRuleResolver;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.SourceRoot;
import com.facebook.buck.rules.SourceWithFlags;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TestCellBuilder;
import com.facebook.buck.testutil.FakeFileHashCache;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.util.sha1.Sha1HashCode;
import com.facebook.buck.util.types.Either;
import com.google.common.base.Preconditions;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.HashCode;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.junit.Test;

public class RuleKeyBuilderTest {

  private static final BuildTarget TARGET_1 =
      BuildTargetFactory.newInstance(Paths.get("/root"), "//example/base:one");
  private static final BuildTarget TARGET_2 =
      BuildTargetFactory.newInstance(Paths.get("/root"), "//example/base:one#flavor");
  private static final BuildRule IGNORED_RULE = new EmptyFakeBuildRule(TARGET_1);
  private static final BuildRule RULE_1 = new EmptyFakeBuildRule(TARGET_1);
  private static final BuildRule RULE_2 = new EmptyFakeBuildRule(TARGET_2);
  private static final RuleKey RULE_KEY_1 = new RuleKey("a002b39af204cdfaa5fdb67816b13867c32ac52c");
  private static final RuleKey RULE_KEY_2 = new RuleKey("b67816b13867c32ac52ca002b39af204cdfaa5fd");

  private static final AddsToRuleKey IGNORED_APPENDABLE = new FakeRuleKeyAppendable("");
  private static final AddsToRuleKey APPENDABLE_1 = new FakeRuleKeyAppendable("");
  private static final AddsToRuleKey APPENDABLE_2 = new FakeRuleKeyAppendable("42");

  private static final Path PATH_1 = Paths.get("path1");
  private static final Path PATH_2 = Paths.get("path2");
  private static final ProjectFilesystem FILESYSTEM = new FakeProjectFilesystem();
  private static final SourcePath SOURCE_PATH_1 = PathSourcePath.of(FILESYSTEM, PATH_1);
  private static final SourcePath SOURCE_PATH_2 = PathSourcePath.of(FILESYSTEM, PATH_2);
  private static final ArchiveMemberSourcePath ARCHIVE_PATH_1 =
      ArchiveMemberSourcePath.of(SOURCE_PATH_1, Paths.get("member"));
  private static final ArchiveMemberSourcePath ARCHIVE_PATH_2 =
      ArchiveMemberSourcePath.of(SOURCE_PATH_2, Paths.get("member"));
  private static final DefaultBuildTargetSourcePath TARGET_PATH_1 =
      DefaultBuildTargetSourcePath.of(TARGET_1);
  private static final DefaultBuildTargetSourcePath TARGET_PATH_2 =
      DefaultBuildTargetSourcePath.of(TARGET_2);

  @Test
  public void testUniqueness() {
    String[] fieldKeys = new String[] {"key1", "key2"};
    Object[] fieldValues =
        new Object[] {
          // Java types
          null,
          true,
          false,
          0,
          42,
          (long) 0,
          (long) 42,
          (short) 0,
          (short) 42,
          (byte) 0,
          (byte) 42,
          (float) 0,
          (float) 42,
          (double) 0,
          (double) 42,
          "",
          "42",
          new byte[0],
          new byte[] {42},
          new byte[] {42, 42},
          DummyEnum.BLACK,
          DummyEnum.WHITE,
          Pattern.compile(""),
          Pattern.compile("42"),

          // Buck simple types
          Sha1HashCode.of("a002b39af204cdfaa5fdb67816b13867c32ac52c"),
          Sha1HashCode.of("b67816b13867c32ac52ca002b39af204cdfaa5fd"),
          new SourceRoot(""),
          new SourceRoot("42"),
          RULE_KEY_1,
          RULE_KEY_2,
          BuildRuleType.of(""),
          BuildRuleType.of("42"),
          TARGET_1,
          TARGET_2,

          // Buck paths
          new NonHashableSourcePathContainer(SOURCE_PATH_1),
          new NonHashableSourcePathContainer(SOURCE_PATH_2),
          SOURCE_PATH_1,
          SOURCE_PATH_2,
          ARCHIVE_PATH_1,
          ARCHIVE_PATH_2,
          TARGET_PATH_1,
          TARGET_PATH_2,
          SourceWithFlags.of(SOURCE_PATH_1, ImmutableList.of("42")),
          SourceWithFlags.of(SOURCE_PATH_2, ImmutableList.of("42")),

          // Buck rules & appendables
          RULE_1,
          RULE_2,
          APPENDABLE_1,
          APPENDABLE_2,

          // Wrappers
          Suppliers.ofInstance(42),
          Optional.of(42),
          Either.ofLeft(42),
          Either.ofRight(42),

          // Containers & nesting
          ImmutableList.of(42),
          ImmutableList.of(42, 42),
          ImmutableMap.of(42, 42),
          ImmutableList.of(ImmutableList.of(1, 2, 3, 4)),
          ImmutableList.of(ImmutableList.of(1, 2), ImmutableList.of(3, 4)),
        };

    List<RuleKey> ruleKeys = new ArrayList<>();
    List<String> desc = new ArrayList<>();
    ruleKeys.add(newBuilder().build(RuleKey::new));
    desc.add("<empty>");
    for (String key : fieldKeys) {
      for (Object val : fieldValues) {
        ruleKeys.add(calcRuleKey(key, val));
        String clazz = (val != null) ? val.getClass().getSimpleName() : "";
        desc.add(String.format("{key=%s, val=%s{%s}}", key, clazz, val));
      }
    }
    // all of the rule keys should be different
    for (int i = 0; i < ruleKeys.size(); i++) {
      for (int j = 0; j < i; j++) {
        assertNotEquals(
            String.format("Collision: %s == %s", desc.get(i), desc.get(j)),
            ruleKeys.get(i),
            ruleKeys.get(j));
      }
    }
  }

  @Test
  public void testNoOp() {
    RuleKey noop = newBuilder().build(RuleKey::new);
    assertEquals(noop, calcRuleKey("key", ImmutableList.of()));
    assertEquals(noop, calcRuleKey("key", ImmutableList.of().iterator()));
    assertEquals(noop, calcRuleKey("key", ImmutableMap.of()));
    assertEquals(noop, calcRuleKey("key", ImmutableList.of(IGNORED_RULE)));
    assertEquals(noop, calcRuleKey("key", Suppliers.ofInstance(IGNORED_RULE)));
    assertEquals(noop, calcRuleKey("key", Optional.of(IGNORED_RULE)));
    assertEquals(noop, calcRuleKey("key", Either.ofLeft(IGNORED_RULE)));
    assertEquals(noop, calcRuleKey("key", Either.ofRight(IGNORED_RULE)));
    assertEquals(noop, calcRuleKey("key", IGNORED_RULE));
    assertEquals(noop, calcRuleKey("key", IGNORED_APPENDABLE));
  }

  private RuleKey calcRuleKey(String key, @Nullable Object val) {
    return newBuilder().setReflectively(key, val).build(RuleKey::new);
  }

  private RuleKeyBuilder<HashCode> newBuilder() {
    Map<BuildTarget, BuildRule> ruleMap = ImmutableMap.of(TARGET_1, RULE_1, TARGET_2, RULE_2);
    Map<BuildRule, RuleKey> ruleKeyMap = ImmutableMap.of(RULE_1, RULE_KEY_1, RULE_2, RULE_KEY_2);
    Map<AddsToRuleKey, RuleKey> appendableKeys =
        ImmutableMap.of(APPENDABLE_1, RULE_KEY_1, APPENDABLE_2, RULE_KEY_2);
    BuildRuleResolver ruleResolver = new FakeBuildRuleResolver(ruleMap);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    FakeFileHashCache hashCache =
        new FakeFileHashCache(
            ImmutableMap.of(
                FILESYSTEM.resolve(PATH_1), HashCode.fromInt(0),
                FILESYSTEM.resolve(PATH_2), HashCode.fromInt(42)),
            ImmutableMap.of(
                pathResolver.getAbsoluteArchiveMemberPath(ARCHIVE_PATH_1), HashCode.fromInt(0),
                pathResolver.getAbsoluteArchiveMemberPath(ARCHIVE_PATH_2), HashCode.fromInt(42)),
            ImmutableMap.of());

    return new RuleKeyBuilder<HashCode>(
        ruleFinder, pathResolver, hashCache, RuleKeyBuilder.createDefaultHasher(Optional.empty())) {

      @Override
      protected RuleKeyBuilder<HashCode> setBuildRule(BuildRule rule) {
        if (rule == IGNORED_RULE) {
          return this;
        }
        return setBuildRuleKey(ruleKeyMap.get(rule));
      }

      @Override
      public RuleKeyBuilder<HashCode> setAddsToRuleKey(AddsToRuleKey appendable) {
        if (appendable == IGNORED_APPENDABLE) {
          return this;
        }
        return setAddsToRuleKey(appendableKeys.get(appendable));
      }

      @Override
      protected RuleKeyBuilder<HashCode> setSourcePath(SourcePath sourcePath) throws IOException {
        if (sourcePath instanceof BuildTargetSourcePath) {
          return setSourcePathAsRule((BuildTargetSourcePath) sourcePath);
        } else {
          return setSourcePathDirectly(sourcePath);
        }
      }

      @Override
      protected RuleKeyBuilder<HashCode> setNonHashingSourcePath(SourcePath sourcePath) {
        return setNonHashingSourcePathDirectly(sourcePath);
      }
    };
  }

  // This ugliness is necessary as we don't have mocks in Buck unit tests.
  private static class FakeBuildRuleResolver extends SingleThreadedBuildRuleResolver {
    private final Map<BuildTarget, BuildRule> ruleMap;

    public FakeBuildRuleResolver(Map<BuildTarget, BuildRule> ruleMap) {
      super(
          TargetGraph.EMPTY,
          new DefaultTargetNodeToBuildRuleTransformer(),
          new TestCellBuilder().build().getCellProvider(),
          null);
      this.ruleMap = ruleMap;
    }

    @Override
    public BuildRule getRule(BuildTarget target) {
      return Preconditions.checkNotNull(ruleMap.get(target), "No rule for target: " + target);
    }
  }

  private static class FakeRuleKeyAppendable implements AddsToRuleKey {

    @AddToRuleKey private final String field;

    public FakeRuleKeyAppendable(String field) {
      this.field = field;
    }
  }

  private enum DummyEnum {
    BLACK,
    WHITE,
  }
}


text:
namespace chromeos {
namespace input_method {

namespace {

bool FindAndUpdateProperty(const InputMethodProperty& new_prop,
                           InputMethodPropertyList* prop_list) {
  return IBusControllerImpl::FindAndUpdatePropertyForTesting(new_prop,
                                                             prop_list);
}

}  // namespace

TEST(IBusControllerImplTest, TestFindAndUpdateProperty) {
  InputMethodPropertyList properties;
  EXPECT_FALSE(FindAndUpdateProperty(InputMethodProperty(), &properties));

  properties.push_back(
      InputMethodProperty("key1", "label1", false, false));
  EXPECT_FALSE(FindAndUpdateProperty(InputMethodProperty(), &properties));
  EXPECT_FALSE(FindAndUpdateProperty(
      InputMethodProperty("keyX", "labelX", false, false), &properties));
  EXPECT_EQ(InputMethodProperty("key1", "label1", false, false),
            properties[0]);
  EXPECT_TRUE(FindAndUpdateProperty(
      InputMethodProperty("key1", "labelY", false, false), &properties));
  EXPECT_EQ(InputMethodProperty("key1", "labelY", false, false),
            properties[0]);

  properties.push_back(
      InputMethodProperty("key2", "label2", false, false));
  EXPECT_FALSE(FindAndUpdateProperty(InputMethodProperty(), &properties));
  EXPECT_FALSE(FindAndUpdateProperty(
      InputMethodProperty("keyX", "labelX", false, false), &properties));
  EXPECT_EQ(InputMethodProperty("key2", "label2", false, false),
            properties[1]);
  EXPECT_TRUE(FindAndUpdateProperty(
      InputMethodProperty("key2", "labelZ", false, false), &properties));
  EXPECT_EQ(InputMethodProperty("key2", "labelZ", false, false),
            properties[1]);
}

}  // namespace input_method
}  // namespace chromeos

redpajama_set_name: RedPajamaGithub


text:
module Akapen
  # = Akapen::Dsl
  class Dsl
    # == questions information
    attr_accessor :questions

    class << self
      # == get dynamic define field names.
      def get_dynamic_field_names
        Akapen::Dsl.instance_methods(false).delete_if { |e|e.match /(questions|method_missing)/ }.delete_if { |e|e.match /^_.*$/ }
      end
    end

    # == init Akapen::Dsl
    def initialize
      @questions = []
    end

    # == create dynamic define field or set question_ok or question_ng
    #- if you call qX_ok, call set_question_ok
    #- if you call qX_ng, call set_question_ng
    #- others, you define field by called name & value.
    def method_missing(method_name, *args, &block)
      arg = args[0]
      return if set_question_ok(method_name, arg)
      return if set_question_ng(method_name, arg)
      define_others(method_name, arg)
    end

    private
    def set_question_ok(method_name, ok_message)
      return unless method_name.to_s.match /^q(\d+)_ok$/

      ret = @questions.find { |qe|qe.no == Regexp.last_match[1] }
      if ret
        ret.ok = ok_message
      else
        q = Question.new(Regexp.last_match[1])
        q.ok = ok_message
        @questions << q
      end
      true
    end

    def set_question_ng(method_name, ng_message)
      return unless method_name.to_s.match /^q(\d+)_ng$/

      ret = @questions.find { |qe|qe.no == Regexp.last_match[1] }
      if ret
        ret.ng = ng_message
      else
        q = Question.new(Regexp.last_match[1])
        q.ng = ng_message
        @questions << q
      end
      true
    end

    def define_others(method_name, arg)
      self.class.class_eval "attr_accessor :_#{method_name}"
      self.class.class_eval <<-EOS
def #{method_name}(_#{method_name})
  @_#{method_name} = _#{method_name}
end
      EOS
      method("#{method_name}").call(arg)
    end
  end

  class Question
    attr_accessor :no, :ok, :ng
    def initialize(no)
      @no = no
    end
  end
end


text:
import { ApproximateDate, DateRange, DatesAreEqual } from "../core/resume";

const months: { [month: number]: string } = {
  1: "January",
  2: "February",
  3: "March",
  4: "April",
  5: "May",
  6: "June",
  7: "July",
  8: "August",
  9: "September",
  10: "October",
  11: "November",
  12: "December",
};

export function RenderApproxDate(date: ApproximateDate): string {
  // if (date.day) {  }
  if (date.month) {
    return "" + months[date.month] + "\u00A0" + date.year;
  }
  return "" + date.year;
}

export function RenderDateRange(range: DateRange): string {
  if (range.end && DatesAreEqual(range.start, range.end)) {
    return RenderApproxDate(range.start);
  }
  if (
    range.end &&
    range.start.year === range.end.year &&
    range.start.month &&
    range.end.month
  ) {
    return (
      "" +
      months[range.start.month] +
      "\u00A0\u2013 " +
      RenderApproxDate(range.end)
    );
  }
  return (
    RenderApproxDate(range.start) +
    "\u00A0\u2013 " +
    (range.end ? RenderApproxDate(range.end) : "Present")
  );
}

export function RenderYearRange(range: DateRange): string {
  if (range.end && range.start.year === range.end.year) {
    return "" + range.start.year;
  }
  return (
    "" +
    range.start.year +
    "\u00A0\u2013 " +
    (range.end ? range.end.year : "Present")
  );
}

export function RenderUrlText(url: string): string {
  // strip protocol
  const protocol = /^.+:\/\/\/?/;
  return url.replace(protocol, "");
}


text:
Skicka e-post till okända användare vidare till dator

Om man inte har valt <tt>Dela ut lokalt</tt> kommer e-post från lokala
användare till en okänd användare att skickas till den angivna datorn.
Detta är användbart om systemet är en delad arbetsstation och man vill
att e-post ska skickas till en gemensam e-postserver.


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Last Mile</title>

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

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

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

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/white.css" id="theme">
		<link href='http://fonts.googleapis.com/css?family=Crimson+Text:400,600,700,400italic,600italic' rel='stylesheet' type='text/css'>
   		<link href='http://fonts.googleapis.com/css?family=Libre+Baskerville:400,700,400italic' rel='stylesheet' type='text/css'>
   		<link href="https://fonts.googleapis.com/css?family=Karla" rel="stylesheet">
   		<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

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

新聞上的地圖運用

林辰峰 Jeremy C.F. Lin

我是誰?

什麼場合用什麼地圖

NYT Amanda Cox : "Intent matters most in mapping. Your map form depends
						on what you want to show."

衛星地圖

						NYT: The Oregon Protest and the Battle Over Western Lands

衛星地圖

						NYT: Areas of Skirmishes and Protests in Hong Kong

衛星地圖

 標示詳細地點與區域,特別適合突發新聞

						忘記做尺標換算,忘記加上註解

地勢圖

						WaPo: 'Himalayan Viagra': Tibet's gold rush may be coming to an end

地勢圖

						WaPo: 'A very dangerous place to be': Huge California blaze forces 82,000 evacuations

地勢圖

 用顏色凸顯區塊,可看到高地勢區域

						畫面太亂沒重點

地勢圖: 標示方法

地點標示圖

						WaPo: 10 great places to eat in Philadelphia, for convention-goers and the rest of us

地點標示圖: 也可以來拿做新聞分析

						NYT: High Lead Levels Were Detected in Nearly 400 Flint Homes, and There May Be More

地點標示圖

 表現
密集程度與分佈。適合座標重要性高以及區域難以整合的新聞。

						點的重疊

Choropleth

						Texas Tribune: Obamacare Health Plans to Get Special Label

Choropleth

						WaPo: Louisiana flooding is the country's 'worst natural disaster' since Hurricane Sandy, Red Cross says

Choropleth

						WaPo: Despite a big year for women in politics, national legislatures are still dominated by men

Choropleth

 展示統計標準化後的每個位置的不同處

						如果地域太小就很難比對, 完全忘記要做統計標準化

Choropleth

等比圓圈地圖

						WaPo: The world of coups since 1950

等比圓圈地圖

						ONA 15 Attendees: Demographic Breakdown

等比圓圈地圖

 精準地展示數據範圍。不用做統計標準化,直接用原始數據即可。

						一般讀者有時候看不懂,因為人類不擅長讀面積。完全變成人口圖。如果沒有變化的話其實有時候看起來滿無聊的。

等比圓圈地圖

						人類不擅長讀面積

熱圖

						WaPo: What you need to know about the Zika virus

熱圖

 展示集中區域,將注意力放在數據與地理邊界沒辦法完全吻合的區塊。

						顏色和分顏色的臨界點沒有統計意義。

Cartogram

						WaPo: What a real 'Brexit Britain' would look like

不是有了經緯度就一定要做成地圖

						WaPo: Trump claims his golf courses are worth tens of millions. Until the tax bill arrives

不是有了經緯度就一定要做成地圖

						WaPo: The world is getting better at paid maternity leave. The U.S. is not

資源

Mapping: QGIS, Adobe Illustrator, D3.js (interactive or small-multiples), Leaflet, Mapbox

Projections: Projection Wizard

Geocoding: Batch Geocode

Geo-data: Natural Earth, 30-Meter SRTM Tile Downloader, Earth Explorer, NASA

Simplify Geo-data : Mapshaper

資源

Reading: 如何製作新聞地圖, 記者可以怎麼運用地理資訊系統QGIS?, Building a U.S. Election Basemap with D3.js and TopoJSON

Who to follow: NYT Graphics, Post Graphics, Tim Wallace, Gregor Aisch, Derek WatkinsLazaro Gamio, Laris Karklis

最重要的資源

GOOGLE!


text:
<?php

namespace flat\sql;

class Sum extends \flat\sql\SqlTemplate{

    private $_columnName = '';

    protected function generateTemplateQuery() {

        $query = "
            SELECT SUM($this->_columnName ) AS sum
            FROM (".$this->getOriginalSQL()->getQueryString().") vw
            ";
        return $query;

    }

    /**
     *
     * @param \flat\Sql $originalSQL
     * @param string $columnName
     */
    public function __construct(\flat\Sql $originalSQL, $columnName) {

        $this->_columnName = $columnName;
        parent::__construct($originalSQL);

    }

}


text:
module Typingpool
  class Test
    class Script < Test
      require 'typingpool'
      require 'open3'
      require 'fileutils'
      require 'nokogiri'
      require 'typingpool/utility/test/script'

      include Utility::Test::Script

      #Overrides method in Utility::Test::Script
      def do_later
        Minitest.after_run{ yield }
      end

      def write_s3_config_with_bad_password(dir, config=Config.file(config_path(dir)))
        bad_password = 'f'
        refute_equal(config.to_hash['amazon']['secret'], bad_password)
        config.to_hash['amazon']['secret'] = bad_password
        write_config(dir, reconfigure_for_s3(config), '.config_s3_bad')
      end

      def assert_has_transcript(project, transcript_file='transcript.html')
        transcript_path = File.join(project.local, transcript_file)
        assert(File.exist?(transcript_path))
        assert(not((transcript = IO.read(transcript_path)).empty?))
        transcript
      end

      def assert_has_partial_transcript(project)
        assert_has_transcript(project, 'transcript_in_progress.html')
      end

      def assert_assignment_csv_has_transcription_count(count, project, which_csv='assignment.csv')
        assert_equal(count, project_transcript_count(project, which_csv))
      end

      def assert_html_has_audio_count(count, html)
        assert_equal(count, Nokogiri::HTML(html).css('audio').size)
      end

      def assert_all_assets_have_upload_status(assignment_csv, type, status)
        recorded_uploads = assignment_csv.map{|assignment| assignment["#{type}_uploaded"] }
        refute_empty(recorded_uploads)
        assert_equal(recorded_uploads.count, recorded_uploads.select{|uploaded| uploaded == status }.count)
      end

      def assert_script_abort_match(args, regex)
        with_temp_transcripts_dir do |dir|
          exception = assert_raises(Typingpool::Error::Shell) do
            yield([*args, '--config', config_path(dir)])
          end
          assert_match(regex, exception.message)
        end #with_temp_transcripts_dir do...
      end

    end #Script
  end #Test
end #Typingpool


text:
struct Int {
    int *pointer;
    int length;
};
struct Float {
    float *pointer;
    int length;
};

class BinaryHeap {
public:
    //constructors
    BinaryHeap();

    BinaryHeap(int maxCapacity);

    BinaryHeap(const int *val1s, Int keys);

    BinaryHeap(const int *val1s, Int keys, int maxCapacity);

    ~BinaryHeap();

    int size() const; //return BinaryHeap size

    //functions
    int insert(int val1, int key) const; //insert element
    void deleteMin() const; //Remove the smallest item from the priority queue

    bool isEmpty() const; //check if empty
    void makeEmpty() const; //empty heap

    static bool binHeapTest(bool verbose);

    std::vector<std::pair<int, int> > *heap;

    static const int DEFAULT_CAPACITY = 1000;
};

#endif


text:
"""
The MIT License (MIT)

Copyright (c) 2015 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

class Server(object):
    """Represents a Discord server.

    Instance attributes:

    .. attribute:: name

        The server name.
    .. attribute:: roles

        An array of :class:`Role` that the server has available.
    .. attribute:: region

        The region the server belongs on.
    .. attribute:: afk_timeout

        The timeout to get sent to the AFK channel.
    .. attribute:: afk_channel_id

        The channel ID for the AFK channel. None if it doesn't exist.
    .. attribute:: members

        An array of :class:`Member` that are currently on the server.
    .. attribute:: channels

        An array of :class:`Channel` that are currently on the server.
    .. attribute:: icon

        The server's icon.
    .. attribute:: id

        The server's ID.
    .. attribute:: owner

        The :class:`Member` who owns the server.
    .. attribute:: unavailable

        A boolean indicating if the server is unavailable. If this is ``True`` then the
        reliability of other attributes outside of :meth:`Server.id` is slim and they might
        all be None. It is best to not do anything with the server if it is unavailable.

        Check the :func:`on_server_unavailable` and :func:`on_server_available` events.
    """

    def __init__(self, **kwargs):
        self.name = kwargs.get('name')
        self.roles = kwargs.get('roles')
        self.region = kwargs.get('region')
        self.afk_timeout = kwargs.get('afk_timeout')
        self.afk_channel_id = kwargs.get('afk_channel_id')
        self.members = kwargs.get('members')
        self.icon = kwargs.get('icon')
        self.id = kwargs.get('id')
        self.owner = kwargs.get('owner')
        self.unavailable = kwargs.get('unavailable', False)

    def get_default_role(self):
        """Gets the @everyone role that all members have by default."""
        for role in self.roles:
            if role.is_everyone():
                return role


text: docker run -e MYSQL_ROOT_PASSWORD=wherehows mysql:8.0.0


text:
title: Save WebSMS
action: de.ub0r.android.callmeter.SAVE_WEBSMS
extras:
  -
    name: uri
    type: String
    var: msgUri
    description: uri of a sent text message
  -
    name: connector
    type: String
    var: connectorName
    description: name of a WebConnector
component: receiver
hide_use: true
---
Send the URI of a sent text message as broadcast to notify Call Meter 3G that the message was sent with the given WebSMS Connector.


text:
<?php declare(strict_types=1);

/**
 * @license     http://opensource.org/licenses/mit-license.php MIT
 * @link        https://github.com/nicoSWD
 * @author      Nicolas Oelgart <nico@oelgart.com>
 */
namespace nicoSWD\Rule\tests\integration\methods;

use nicoSWD\Rule\tests\integration\AbstractTestBase;

final class JoinTest extends AbstractTestBase
{
    protected array $array = ['foo' => ['foo', 'bar']];

    /** @test */
    public function ifOmittedDelimiterFallsBackToDefault(): void
    {
        $this->assertTrue($this->evaluate('foo.join() === "foo,bar"', $this->array));
    }

    /** @test */
    public function literalStringDelimiter(): void
    {
        $this->assertTrue($this->evaluate('foo.join("|") === "foo|bar"', $this->array));
    }

    /** @test */
    public function variableValueAsDelimiter(): void
    {
        $this->assertTrue($this->evaluate(
            'foo.join(separator) === "foo$bar"',
            $this->array + ['separator' => '$']
        ));
    }

    /** @test */
    public function callOnStringLiteralArray(): void
    {
        $this->assertTrue($this->evaluate('[1, 2, 3].join("|") === "1|2|3"'));
        $this->assertTrue($this->evaluate('[1, 2, 3] . join("|") === "1|2|3"'));
    }

    /** @test */
    public function variableInArrayIsJoined(): void
    {
        $this->assertTrue($this->evaluate('[1, 2, foo].join("|") === "1|2|3"', ['foo' => 3]));
    }

    /** @test */
    public function joinOnEmptyArray(): void
    {
        $this->assertTrue($this->evaluate('[].join("|") === ""'));
    }
}


text: """The aruba component."""


text:
package demo.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;

public class StringUtil {
	public static final HashMap<String, String> theNumToGb2312CharMap = new HashMap<String, String>();
	public static final int MSG_TYPE_ASCII = 0;
	public static final int MSG_TYPE_WRITECARD = 3;
	public static final int MSG_TYPE_BINARY = 4;
	public static final int MSG_TYPE_UCS2 = 8;
	public static final int MSG_TYPE_CHINESE = 15;

	static {
		theNumToGb2312CharMap.put("+", "��");
		theNumToGb2312CharMap.put("-", "��");
		theNumToGb2312CharMap.put("0", "��");
		theNumToGb2312CharMap.put("1", "һ");
		theNumToGb2312CharMap.put("2", "��");
		theNumToGb2312CharMap.put("3", "��");
		theNumToGb2312CharMap.put("4", "��");
		theNumToGb2312CharMap.put("5", "��");
		theNumToGb2312CharMap.put("6", "��");
		theNumToGb2312CharMap.put("7", "��");
		theNumToGb2312CharMap.put("8", "��");
		theNumToGb2312CharMap.put("9", "��");
		theNumToGb2312CharMap.put("10", "ʮ");
		theNumToGb2312CharMap.put("100", "��");
		theNumToGb2312CharMap.put("1000", "ǧ");
		theNumToGb2312CharMap.put("10000", "��");
	}

	public static boolean zero(String o) {
		return (o == null) || (o.length() <= 0);
	}

	public static boolean empty(String o) {
		return (o == null) || (o.length() <= 0) || (o.trim().equals(""));
	}

	public static String toZeroSafe(String str) {
		if (zero(str))
			return "";
		return str;
	}

	public static String toZeroSafe(String str, String def) {
		if (zero(str))
			return def;
		return str;
	}

	public static String toEmptySafe(String str) {
		if (empty(str))
			return "";
		return str;
	}

	public static String toEmptySafe(String str, String def) {
		if (empty(str))
			return def;
		return str;
	}

	public static String trim(String str) {
		if (empty(str))
			return str;
		return str.trim();
	}

	public static boolean equals(String s1, String s2) {
		if (s1 == s2)
			return true;
		if (s1 == null)
			return false;
		return s1.equals(s2);
	}

	public static boolean equalsIgnoreCase(String s1, String s2) {
		if (s1 == s2)
			return true;
		if (s1 == null)
			return false;
		return s1.equalsIgnoreCase(s2);
	}

	public static String toString(char[] array) {
		return String.valueOf(array);
	}

	public static String toHexString(byte[] b) {
		if (b == null)
			return "";
		StringBuffer strBuffer = new StringBuffer(b.length * 3);
		for (int i = 0; i < b.length; i++) {
			strBuffer.append(Integer.toHexString(b[i] & 0xFF));
			strBuffer.append(" ");
		}
		return strBuffer.toString();
	}

	public static String toHexString(String str) {
		if (zero(str))
			return "";
		return toHexString(str.getBytes());
	}

	public static String toHexString(String str, String enc) {
		if (zero(str))
			return "";
		byte[] b = null;
		if (!empty(enc)) {
			try {
				b = str.getBytes(enc);
			} catch (UnsupportedEncodingException e) {
				return "UnsupportedEncodingException = " + e.getMessage();
			}
		}
		return toHexString(b);
	}

	public static String normalize(String str, String token, String escape) {
		if (empty(str)) {
			return "";
		}
		StringTokenizer tokenizer = new StringTokenizer(str, token);
		String fixed = new String("");
		while (tokenizer.hasMoreTokens()) {
			if (fixed.equals(""))
				fixed = tokenizer.nextToken();
			else {
				fixed = fixed + escape + token + tokenizer.nextToken();
			}
		}
		if (str.indexOf(escape) == 0) {
			fixed = escape + token + fixed;
		}
		if (str.lastIndexOf(escape) == str.length() - 1) {
			fixed = fixed + escape + token;
		}
		return fixed;
	}

	public static String replace(String src, char charOld, String strNew) {
		if (src == null)
			return src;
		if (strNew == null) {
			return src;
		}
		StringBuffer buf = new StringBuffer();
		int i = 0;
		for (int n = src.length(); i < n; i++) {
			char c = src.charAt(i);
			if (c == charOld)
				buf.append(strNew);
			else
				buf.append(c);
		}
		return buf.toString();
	}

	public static String commonPrefix(String s1, String s2) {
		if ((s1 == null) || (s2 == null))
			return null;
		StringBuffer sb = new StringBuffer();
		int len = Math.min(s1.length(), s2.length());
		for (int i = 0; i < len; i++) {
			char c = s1.charAt(i);
			if (c != s2.charAt(i))
				break;
			sb.append(c);
		}
		return sb.toString();
	}

	public static String upperFirst(String s) {
		String str = null;
		if (s != null) {
			if (s.length() == 1)
				str = s.toUpperCase();
			else {
				str = s.substring(0, 1).toUpperCase() + s.substring(1);
			}
		}
		return str;
	}

	public static void upperFirst(StringBuffer sb) {
		if ((sb != null) && (sb.length() > 0))
			sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
	}

	public static String lowerFirst(String s) {
		String str = null;
		if (s != null) {
			if (s.length() == 1)
				str = s.toLowerCase();
			else {
				str = s.substring(0, 1).toLowerCase() + s.substring(1);
			}
		}
		return str;
	}

	public static void lowerFirst(StringBuffer sb) {
		if ((sb != null) && (sb.length() > 0))
			sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
	}

	public static String getLastSuffix(String str, String delima) {
		if (zero(delima)) {
			return str;
		}
		String suffix = "";
		if (!zero(str)) {
			int index = str.lastIndexOf(delima);
			if (index >= 0)
				suffix = str.substring(index + delima.length());
			else
				suffix = str;
		}
		return suffix;
	}

	public static String getLastPrefix(String src, String delima) {
		if (zero(delima)) {
			return src;
		}
		String prefix = "";
		if (!zero(src)) {
			int index = src.lastIndexOf(delima);
			if (index >= 0)
				prefix = src.substring(0, index);
		}
		return prefix;
	}

	public static String[] split2(String str, String delim) {
		if (empty(str)) {
			return new String[] { "" };
		}
		StringTokenizer st = new StringTokenizer(str, delim);
		String[] contents = new String[st.countTokens()];
		if (contents.length == 0) {
			return new String[] { "" };
		}
		int i = 0;
		while (st.hasMoreTokens()) {
			contents[(i++)] = st.nextToken();
		}

		return contents;
	}

	public static final String[] splitWithoutBackspace(String str, String delim) {
		if ((zero(str)) || (zero(delim)))
			return new String[0];
		List list = new ArrayList();
		for (StringTokenizer tokenizer = new StringTokenizer(str, delim); tokenizer.hasMoreTokens();) {
			String child = tokenizer.nextToken().trim();
			if (!child.equals("")) {
				list.add(child);
			}
		}
		return (String[]) list.toArray(new String[list.size()]);
	}

	public static String[] splitNumAndStr(String oldStr) {
		if ((oldStr == null) || (oldStr.length() <= 0)) {
			return null;
		}
		String[] tempSeparator = new String[2];
		int i = 0;
		String tempChr = oldStr.substring(i++, i);
		while (i < oldStr.length()) {
			int j = 0;
			for (j = 0; j <= 9; j++) {
				if (tempChr.equals(String.valueOf(j))) {
					break;
				}
			}
			if (j == 10) {
				tempSeparator[0] = oldStr.substring(0, --i);
				tempSeparator[1] = oldStr.substring(i, oldStr.length());
				return tempSeparator;
			}

			if (i < oldStr.length()) {
				tempChr = oldStr.substring(i++, i);
			}

		}

		return null;
	}

	public static String join(String[] set, String delim) {
		if ((set == null) || (set.length <= 0))
			return "";
		StringBuffer sb = new StringBuffer();
		sb.append(toEmptySafe(set[0]));
		for (int i = 1; i < set.length; i++) {
			if (!empty(set[i])) {
				sb.append(delim);
				sb.append(toEmptySafe(set[i]));
			}
		}
		return sb.toString();
	}

	public static String join(String[] set, String delim, int fromIndex) {
		if ((set == null) || (set.length <= 0) || (fromIndex >= set.length)) {
			return "";
		}
		if (fromIndex < 0) {
			fromIndex = 0;
		}
		StringBuffer sb = new StringBuffer();
		sb.append(set[fromIndex]);
		for (int i = fromIndex + 1; i < set.length; i++) {
			sb.append(delim);
			sb.append(set[i]);
		}
		return sb.toString();
	}

	public static String joinWithSpace(String[] keys) {
		return join(keys, " ");
	}

	public static String appendDelimSuffix(String str, String suffix, String primaryDelim, String alternateDelim) {
		if (zero(str))
			str = "";
		if (zero(suffix)) {
			suffix = "";
		}
		String delim = primaryDelim;
		if (str.indexOf(primaryDelim) >= 0)
			delim = alternateDelim;
		if (zero(delim)) {
			delim = "";
		}
		return str + delim + suffix;
	}

	public static String[] stringsCopy(String[] strings) {
		if (strings == null)
			return null;
		String[] copyStr = new String[strings.length];
		for (int i = 0; i < strings.length; i++) {
			if (strings[i] != null)
				copyStr[i] = new String(strings[i]);
			else
				copyStr[i] = null;
		}
		return copyStr;
	}

	public static String[] stringsCopyExcludeNull(String[] strings) {
		if (strings == null)
			return null;
		int iCount = 0;
		for (int i = 0; i < strings.length; i++) {
			if (strings[i] != null)
				iCount++;
		}
		String[] copyStr = new String[iCount];
		int i = 0;
		for (int j = 0; i < strings.length; i++) {
			if (strings[i] != null)
				copyStr[(j++)] = new String(strings[i]);
		}
		return copyStr;
	}

	public static String[] stringsCopyConvertNull(String[] strings) {
		if (strings == null)
			return null;
		String[] copyStr = new String[strings.length];
		for (int i = 0; i < strings.length; i++) {
			if (strings[i] != null)
				copyStr[i] = new String(strings[i]);
			else
				copyStr[i] = "";
		}
		return copyStr;
	}

	public static String copy(String str) {
		if (str == null)
			return "";
		return new String(str);
	}

	public static boolean contains(String str, char searchChar) {
		if ((str == null) || (str.length() == 0)) {
			return false;
		}
		return str.indexOf(searchChar) >= 0;
	}

	public static boolean contains(String str, String searchStr) {
		if ((str == null) || (searchStr == null))
			return false;
		if (searchStr.length() == 0) {
			return false;
		}
		return str.indexOf(searchStr) >= 0;
	}

	public static boolean contains(StringBuffer str, String searchStr) {
		if ((str == null) || (searchStr == null))
			return false;
		if (searchStr.length() == 0) {
			return false;
		}
		return contains(str.toString(), searchStr);
	}

	public static boolean contains(String str, String[] searchStrSet) {
		if ((str == null) || (searchStrSet == null)) {
			return false;
		}
		for (int i = 0; i < searchStrSet.length; i++) {
			String searchStr = searchStrSet[i];
			if (!contains(str, searchStr))
				return false;
		}
		return true;
	}

	public static boolean contains(String[] set, String searchStr) {
		if ((set == null) || (searchStr == null))
			return false;
		for (int i = 0; i < set.length; i++) {
			String str = set[i];
			if (searchStr.equals(str))
				return true;
		}
		return false;
	}

	public static int countMul(String src, String search) {
		StringTokenizer st = new StringTokenizer(src, search);
		return st.countTokens();
	}

	public static String reverse(String s) {
		if (s == null) {
			return null;
		}

		char[] c = s.toCharArray();
		char[] reverse = new char[c.length];

		for (int i = 0; i < c.length; i++) {
			reverse[i] = c[(c.length - i - 1)];
		}

		return new String(reverse);
	}

	public static Object removeExisted(String[] original, String searchKey) {
		Set set = new HashSet();

		for (int i = 0; i < original.length; i++) {
			set.add(original[i]);
		}
		set.remove(searchKey);

		return set;
	}

	public static String[] split(String dest, int maxLength) {
		int length = 0;

		length = dest.length();
		if (length <= maxLength) {
			return new String[] { dest };
		}

		int count = length / maxLength;
		if (length % maxLength > 0) {
			count++;
		}
		String[] contents = new String[count];
		int pointer = 0;
		for (int i = 0; i < count - 1; i++) {
			contents[i] = dest.substring(pointer, pointer + maxLength);
			pointer += maxLength;
		}
		contents[(count - 1)] = dest.substring(pointer);

		return contents;
	}

	public static String toGb2312Number(int num, boolean hasSeperator) {
		StringBuffer sb = new StringBuffer();

		String str = String.valueOf(num);
		int len = str.length();
		for (int i = 0; i < len; i++) {
			if ((num < 10) || (num >= 20) || (i != 0)) {
				char c = str.charAt(i);
				String v = (String) theNumToGb2312CharMap.get(String.valueOf(c));
				if (v != null) {
					if ((hasSeperator) && (i != 0)) {
						int key = (int) Math.pow(10.0D, len - i);
						sb.append((String) theNumToGb2312CharMap.get(String.valueOf(key)));
					}

					if ((c != '0') || (i != len - 1)) {
						sb.append(v);
					}
				}
			}

		}

		return sb.toString();
	}

	public static String format(int original, int length, char padding) {
		String str = String.valueOf(original);
		int feeLength = str.length();

		if (length < feeLength) {
			str = str.substring(0, length);
		} else if (length > feeLength) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < length - feeLength; i++) {
				sb.append(padding);
			}
			str = str;
		}

		return str;
	}

	public static String fillBlank(String name, int bitNo) {
		while (bitNo >= 0) {
			if (bitNo == 0) {
				return name;
			}
			name = "0" + name;
			bitNo--;
			fillBlank(name, bitNo);
		}
		return name;
	}

	public static boolean isExistCH(String str) {
		str = str.trim();
		if (empty(str)) {
			return false;
		}
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if ((c < '!') || (c > '~')) {
				return true;
			}
		}
		return false;
	}

	public static String convertMap(Map<String, String> map) {
		StringBuilder sb = new StringBuilder();
		if ((map != null) && (map.size() > 0)) {
			for (Iterator localIterator = map.keySet().iterator(); localIterator.hasNext();) {
				Object key = localIterator.next();
				sb.append("'");
				sb.append(key);
				sb.append("'");
				sb.append(",");
			}
		}
		String ret = sb.toString();
		if (sb.length() > 0) {
			ret = sb.substring(0, sb.length() - 1);
		}
		return ret;
	}

	public static String convertArray(String[] array) {
		StringBuilder sb = new StringBuilder();
		if ((array != null) && (array.length > 0)) {
			String[] arrayOfString = array;
			int j = array.length;
			for (int i = 0; i < j; i++) {
				String key = arrayOfString[i];
				sb.append("'");
				sb.append(key);
				sb.append("'");
				sb.append(",");
			}
		}
		String ret = sb.toString();
		if (sb.length() > 0) {
			ret = sb.substring(0, sb.length() - 1);
		}
		return ret;
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static boolean isEmpty(Object str) {
		if ((str == null) || ("".equals(String.valueOf(str).trim())) || ("null".equalsIgnoreCase(String.valueOf(str).trim()))) {
			return true;
		}
		return false;
	}

	public static boolean isNotEmpty(Object str) {
		return !isEmpty(str);
	}

	public static String parseClassName(String className) {
		if (className != null) {
			if (className.indexOf(".") >= 0) {
				return className.substring(className.lastIndexOf(".") + 1, className.length());
			}
			return className;
		}
		return "";
	}

	public static String get4RandomNum() {
		return new Random().nextInt(9) + "" + new Random().nextInt(9) + "" + new Random().nextInt(9) + "" + new Random().nextInt(9);
	}

	public static String getRandomNum(int num) {
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < num; i++) {
			str.append(new Random().nextInt(9));
		}
		return str.toString();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>
	<artifactId>softwaremill-sqs</artifactId>
	<name>Softwaremill SQS support</name>

	<parent>
        <groupId>com.softwaremill.common</groupId>
        <artifactId>softwaremill-common-parent</artifactId>
        <version>81-SNAPSHOT</version>
    </parent>

	<dependencies>
		<dependency>
			<groupId>com.softwaremill.common</groupId>
			<artifactId>softwaremill-conf</artifactId>
            <version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.softwaremill.common</groupId>
			<artifactId>softwaremill-util</artifactId>
            <version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.jboss.spec</groupId>
			<artifactId>jboss-javaee-6.0</artifactId>
			<type>pom</type>
			<scope>provided</scope>
		</dependency>

        <!-- For creating temporary requests in SQSTaskTimerBean -->
        <dependency>
           <groupId>org.jboss.weld.servlet</groupId>
           <artifactId>weld-servlet-core</artifactId>
           <scope>provided</scope>
       </dependency>

        <!-- AWS -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
        </dependency>

        <!-- ElasticMQ for testing -->
        <dependency>
            <groupId>org.elasticmq</groupId>
            <artifactId>elasticmq-core_2.9.1</artifactId>
            <version>0.6.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.elasticmq</groupId>
            <artifactId>elasticmq-rest-sqs_2.9.1</artifactId>
            <version>0.6.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
            <version>${slf4j.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.awaitility</groupId>
            <artifactId>awaitility</artifactId>
        </dependency>
        <!-- Use a fresh version of hamcrest. Version 1.1 didn't have the MatcherAssert class yet. -->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
        </dependency>

        <!-- mock smtp -->
		<dependency>
			<groupId>dumbster</groupId>
			<artifactId>dumbster</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<testResources>
			<testResource>
				<directory>src/test/resources</directory>
				<filtering>true</filtering>
			</testResource>
		</testResources>
		<plugins>
			<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${surefire.version}</version>
				<configuration>
					<skipTests>${softwaremill.common.skipIntegrationTests}</skipTests>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
import contextlib

import mock
from oslo_vmware import exceptions as oslo_vmw_exceptions
from oslo_vmware import vim_util as vutil

from nova.compute import vm_states
from nova import context
from nova import exception
from nova import test
from nova.tests.unit import fake_instance
from nova.tests.unit.image import fake as image_fake
from nova.tests.unit.virt.vmwareapi import fake as vmwareapi_fake
from nova.tests.unit.virt.vmwareapi import stubs
from nova.virt.vmwareapi import constants
from nova.virt.vmwareapi import driver
from nova.virt.vmwareapi import vm_util
from nova.virt.vmwareapi import volumeops

class VMwareVolumeOpsTestCase(test.NoDBTestCase):

    def setUp(self):

        super(VMwareVolumeOpsTestCase, self).setUp()
        vmwareapi_fake.reset()
        stubs.set_stubs(self.stubs)
        self._session = driver.VMwareAPISession()
        self._context = context.RequestContext('fake_user', 'fake_project')

        self._volumeops = volumeops.VMwareVolumeOps(self._session)
        self._image_id = image_fake.get_valid_image_id()
        self._instance_values = {
            'name': 'fake_name',
            'uuid': 'fake_uuid',
            'vcpus': 1,
            'memory_mb': 512,
            'image_ref': self._image_id,
            'root_gb': 10,
            'node': 'respool-1001(MyResPoolName)',
            'expected_attrs': ['system_metadata'],
        }
        self._instance = fake_instance.fake_instance_obj(self._context,
            **self._instance_values)

    def _test_detach_disk_from_vm(self, destroy_disk=False):
        def fake_call_method(module, method, *args, **kwargs):
            vmdk_detach_config_spec = kwargs.get('spec')
            virtual_device_config = vmdk_detach_config_spec.deviceChange[0]
            self.assertEqual('remove', virtual_device_config.operation)
            self.assertEqual('ns0:VirtualDeviceConfigSpec',
                              virtual_device_config.obj_name)
            if destroy_disk:
                self.assertEqual('destroy',
                                 virtual_device_config.fileOperation)
            else:
                self.assertFalse(hasattr(virtual_device_config,
                                 'fileOperation'))
            return 'fake_configure_task'
        with contextlib.nested(
            mock.patch.object(self._session, '_wait_for_task'),
            mock.patch.object(self._session, '_call_method',
                              fake_call_method)
        ) as (_wait_for_task, _call_method):
            fake_device = vmwareapi_fake.DataObject()
            fake_device.backing = vmwareapi_fake.DataObject()
            fake_device.backing.fileName = 'fake_path'
            fake_device.key = 'fake_key'
            self._volumeops.detach_disk_from_vm('fake_vm_ref', self._instance,
                                                fake_device, destroy_disk)
            _wait_for_task.assert_has_calls([
                   mock.call('fake_configure_task')])

    def test_detach_with_destroy_disk_from_vm(self):
        self._test_detach_disk_from_vm(destroy_disk=True)

    def test_detach_without_destroy_disk_from_vm(self):
        self._test_detach_disk_from_vm(destroy_disk=False)

    def _fake_call_get_object_property(self, uuid, result):
        def fake_call_method(vim, method, vm_ref, prop):
            expected_prop = 'config.extraConfig["volume-%s"]' % uuid
            self.assertEqual('VirtualMachine', vm_ref._type)
            self.assertEqual(expected_prop, prop)
            return result
        return fake_call_method

    def test_get_volume_uuid(self):
        vm_ref = vmwareapi_fake.ManagedObjectReference('VirtualMachine',
                                                       'vm-134')
        uuid = '1234'
        opt_val = vmwareapi_fake.OptionValue('volume-%s' % uuid, 'volume-val')
        fake_call = self._fake_call_get_object_property(uuid, opt_val)
        with mock.patch.object(self._session, "_call_method", fake_call):
            val = self._volumeops._get_volume_uuid(vm_ref, uuid)
            self.assertEqual('volume-val', val)

    def test_get_volume_uuid_not_found(self):
        vm_ref = vmwareapi_fake.ManagedObjectReference('VirtualMachine',
                                                       'vm-134')
        uuid = '1234'
        fake_call = self._fake_call_get_object_property(uuid, None)
        with mock.patch.object(self._session, "_call_method", fake_call):
            val = self._volumeops._get_volume_uuid(vm_ref, uuid)
            self.assertIsNone(val)

    def test_attach_volume_vmdk_invalid(self):
        connection_info = {'driver_volume_type': 'vmdk',
                           'serial': 'volume-fake-id',
                           'data': {'volume': 'vm-10',
                                    'volume_id': 'volume-fake-id'}}
        instance = mock.MagicMock(name='fake-name', vm_state=vm_states.ACTIVE)
        vmdk_info = vm_util.VmdkInfo('fake-path', constants.ADAPTER_TYPE_IDE,
                                     constants.DISK_TYPE_PREALLOCATED, 1024,
                                     'fake-device')
        with contextlib.nested(
            mock.patch.object(vm_util, 'get_vm_ref'),
            mock.patch.object(self._volumeops, '_get_volume_ref'),
            mock.patch.object(vm_util, 'get_vmdk_info',
                              return_value=vmdk_info)
        ) as (get_vm_ref, get_volume_ref, get_vmdk_info):
            self.assertRaises(exception.Invalid,
                self._volumeops._attach_volume_vmdk, connection_info,
                instance)

            get_vm_ref.assert_called_once_with(self._volumeops._session,
                                               instance)
            get_volume_ref.assert_called_once_with(
                connection_info['data']['volume'])
            self.assertTrue(get_vmdk_info.called)

    @mock.patch.object(vm_util, 'get_vm_extra_config_spec',
                       return_value=mock.sentinel.extra_config)
    @mock.patch.object(vm_util, 'reconfigure_vm')
    def test_update_volume_details(self, reconfigure_vm,
                                   get_vm_extra_config_spec):
            volume_uuid = '26f5948e-52a3-4ee6-8d48-0a379afd0828'
            device_uuid = '0d86246a-2adb-470d-a9f7-bce09930c5d'
            self._volumeops._update_volume_details(
                mock.sentinel.vm_ref, volume_uuid, device_uuid)

            get_vm_extra_config_spec.assert_called_once_with(
                self._volumeops._session.vim.client.factory,
                {'volume-%s' % volume_uuid: device_uuid})
            reconfigure_vm.assert_called_once_with(self._volumeops._session,
                                                   mock.sentinel.vm_ref,
                                                   mock.sentinel.extra_config)

    def test_detach_volume_vmdk(self):

        vmdk_info = vm_util.VmdkInfo('fake-path', 'lsiLogic', 'thin',
                                     1024, 'fake-device')
        with contextlib.nested(
            mock.patch.object(vm_util, 'get_vm_ref',
                              return_value=mock.sentinel.vm_ref),
            mock.patch.object(self._volumeops, '_get_volume_ref',
                              return_value=mock.sentinel.volume_ref),
            mock.patch.object(self._volumeops,
                              '_get_vmdk_backed_disk_device',
                              return_value=mock.sentinel.device),
            mock.patch.object(vm_util, 'get_vmdk_info',
                              return_value=vmdk_info),
            mock.patch.object(self._volumeops, '_consolidate_vmdk_volume'),
            mock.patch.object(self._volumeops, 'detach_disk_from_vm'),
            mock.patch.object(self._volumeops, '_update_volume_details'),
        ) as (get_vm_ref, get_volume_ref, get_vmdk_backed_disk_device,
              get_vmdk_info, consolidate_vmdk_volume, detach_disk_from_vm,
              update_volume_details):

            connection_info = {'driver_volume_type': 'vmdk',
                               'serial': 'volume-fake-id',
                               'data': {'volume': 'vm-10',
                                        'volume_id':
                                        'd11a82de-ddaa-448d-b50a-a255a7e61a1e'
                                        }}
            instance = mock.MagicMock(name='fake-name',
                                      vm_state=vm_states.ACTIVE)
            self._volumeops._detach_volume_vmdk(connection_info, instance)

            get_vm_ref.assert_called_once_with(self._volumeops._session,
                                               instance)
            get_volume_ref.assert_called_once_with(
                connection_info['data']['volume'])
            get_vmdk_backed_disk_device.assert_called_once_with(
                mock.sentinel.vm_ref, connection_info['data'])
            get_vmdk_info.assert_called_once_with(self._volumeops._session,
                                                  mock.sentinel.volume_ref)
            consolidate_vmdk_volume.assert_called_once_with(
                instance, mock.sentinel.vm_ref, mock.sentinel.device,
                mock.sentinel.volume_ref, adapter_type=vmdk_info.adapter_type,
                disk_type=vmdk_info.disk_type)
            detach_disk_from_vm.assert_called_once_with(mock.sentinel.vm_ref,
                                                        instance,
                                                        mock.sentinel.device)
            update_volume_details.assert_called_once_with(
                mock.sentinel.vm_ref, connection_info['data']['volume_id'], "")

    def test_detach_volume_vmdk_invalid(self):
        connection_info = {'driver_volume_type': 'vmdk',
                           'serial': 'volume-fake-id',
                           'data': {'volume': 'vm-10',
                                    'volume_id': 'volume-fake-id'}}
        instance = mock.MagicMock(name='fake-name', vm_state=vm_states.ACTIVE)
        vmdk_info = vm_util.VmdkInfo('fake-path', constants.ADAPTER_TYPE_IDE,
                                     constants.DISK_TYPE_PREALLOCATED, 1024,
                                     'fake-device')
        with contextlib.nested(
            mock.patch.object(vm_util, 'get_vm_ref',
                              return_value=mock.sentinel.vm_ref),
            mock.patch.object(self._volumeops, '_get_volume_ref'),
            mock.patch.object(self._volumeops,
                              '_get_vmdk_backed_disk_device'),
            mock.patch.object(vm_util, 'get_vmdk_info',
                              return_value=vmdk_info)
        ) as (get_vm_ref, get_volume_ref, get_vmdk_backed_disk_device,
              get_vmdk_info):
            self.assertRaises(exception.Invalid,
                self._volumeops._detach_volume_vmdk, connection_info,
                instance)

            get_vm_ref.assert_called_once_with(self._volumeops._session,
                                               instance)
            get_volume_ref.assert_called_once_with(
                connection_info['data']['volume'])
            get_vmdk_backed_disk_device.assert_called_once_with(
                mock.sentinel.vm_ref, connection_info['data'])
            self.assertTrue(get_vmdk_info.called)

    def _test_attach_volume_vmdk(self, adapter_type=None):
        connection_info = {'driver_volume_type': constants.DISK_FORMAT_VMDK,
                           'serial': 'volume-fake-id',
                           'data': {'volume': 'vm-10',
                                    'volume_id': 'volume-fake-id'}}
        vm_ref = 'fake-vm-ref'
        volume_device = mock.MagicMock()
        volume_device.backing.fileName = 'fake-path'
        default_adapter_type = constants.DEFAULT_ADAPTER_TYPE
        disk_type = constants.DEFAULT_DISK_TYPE
        disk_uuid = 'e97f357b-331e-4ad1-b726-89be048fb811'
        backing = mock.Mock(uuid=disk_uuid)
        device = mock.Mock(backing=backing)
        vmdk_info = vm_util.VmdkInfo('fake-path', default_adapter_type,
                                     disk_type, 1024,
                                     device)
        adapter_type = adapter_type or default_adapter_type

        with contextlib.nested(
            mock.patch.object(vm_util, 'get_vm_ref', return_value=vm_ref),
            mock.patch.object(self._volumeops, '_get_volume_ref'),
            mock.patch.object(vm_util, 'get_vmdk_info',
                              return_value=vmdk_info),
            mock.patch.object(self._volumeops, 'attach_disk_to_vm'),
            mock.patch.object(self._volumeops, '_update_volume_details')
        ) as (get_vm_ref, get_volume_ref, get_vmdk_info, attach_disk_to_vm,
              update_volume_details):
            self._volumeops.attach_volume(connection_info, self._instance,
                                          adapter_type)

            get_vm_ref.assert_called_once_with(self._volumeops._session,
                                               self._instance)
            get_volume_ref.assert_called_once_with(
                connection_info['data']['volume'])
            self.assertTrue(get_vmdk_info.called)
            attach_disk_to_vm.assert_called_once_with(
                vm_ref, self._instance, adapter_type,
                constants.DISK_TYPE_PREALLOCATED, vmdk_path='fake-path')
            update_volume_details.assert_called_once_with(
                vm_ref, connection_info['data']['volume_id'], disk_uuid)

    def _test_attach_volume_iscsi(self, adapter_type=None):
        connection_info = {'driver_volume_type': 'iscsi',
                           'serial': 'volume-fake-id',
                           'data': {'volume': 'vm-10',
                                    'volume_id': 'volume-fake-id'}}
        vm_ref = 'fake-vm-ref'
        default_adapter_type = constants.DEFAULT_ADAPTER_TYPE
        adapter_type = adapter_type or default_adapter_type

        with contextlib.nested(
            mock.patch.object(vm_util, 'get_vm_ref', return_value=vm_ref),
            mock.patch.object(self._volumeops, '_iscsi_discover_target',
                              return_value=(mock.sentinel.device_name,
                                            mock.sentinel.uuid)),
            mock.patch.object(vm_util, 'get_scsi_adapter_type',
                              return_value=adapter_type),
            mock.patch.object(self._volumeops, 'attach_disk_to_vm')
        ) as (get_vm_ref, iscsi_discover_target, get_scsi_adapter_type,
              attach_disk_to_vm):
            self._volumeops.attach_volume(connection_info, self._instance,
                                          adapter_type)

            get_vm_ref.assert_called_once_with(self._volumeops._session,
                                               self._instance)
            iscsi_discover_target.assert_called_once_with(
                connection_info['data'])
            if adapter_type is None:
                self.assertTrue(get_scsi_adapter_type.called)
            attach_disk_to_vm.assert_called_once_with(vm_ref,
                self._instance, adapter_type, 'rdmp',
                device_name=mock.sentinel.device_name)

    def test_attach_volume_vmdk(self):
        for adapter_type in (None, constants.DEFAULT_ADAPTER_TYPE,
                             constants.ADAPTER_TYPE_BUSLOGIC,
                             constants.ADAPTER_TYPE_IDE,
                             constants.ADAPTER_TYPE_LSILOGICSAS,
                             constants.ADAPTER_TYPE_PARAVIRTUAL):
            self._test_attach_volume_vmdk(adapter_type)

    def test_attach_volume_iscsi(self):
        for adapter_type in (None, constants.DEFAULT_ADAPTER_TYPE,
                             constants.ADAPTER_TYPE_BUSLOGIC,
                             constants.ADAPTER_TYPE_LSILOGICSAS,
                             constants.ADAPTER_TYPE_PARAVIRTUAL):
            self._test_attach_volume_iscsi(adapter_type)

    @mock.patch.object(volumeops.VMwareVolumeOps,
                       '_get_vmdk_base_volume_device')
    @mock.patch.object(volumeops.VMwareVolumeOps, '_relocate_vmdk_volume')
    def test_consolidate_vmdk_volume_with_no_relocate(
            self, relocate_vmdk_volume, get_vmdk_base_volume_device):
        file_name = mock.sentinel.file_name
        backing = mock.Mock(fileName=file_name)
        original_device = mock.Mock(backing=backing)
        get_vmdk_base_volume_device.return_value = original_device

        device = mock.Mock(backing=backing)

        volume_ref = mock.sentinel.volume_ref
        vm_ref = mock.sentinel.vm_ref

        self._volumeops._consolidate_vmdk_volume(self._instance, vm_ref,
                                                 device, volume_ref)

        get_vmdk_base_volume_device.assert_called_once_with(volume_ref)
        self.assertFalse(relocate_vmdk_volume.called)

    @mock.patch.object(volumeops.VMwareVolumeOps,
                       '_get_vmdk_base_volume_device')
    @mock.patch.object(volumeops.VMwareVolumeOps, '_relocate_vmdk_volume')
    @mock.patch.object(volumeops.VMwareVolumeOps, '_get_host_of_vm')
    @mock.patch.object(volumeops.VMwareVolumeOps, '_get_res_pool_of_host')
    @mock.patch.object(volumeops.VMwareVolumeOps, 'detach_disk_from_vm')
    @mock.patch.object(volumeops.VMwareVolumeOps, 'attach_disk_to_vm')
    def test_consolidate_vmdk_volume_with_relocate(
            self, attach_disk_to_vm, detach_disk_from_vm, get_res_pool_of_host,
            get_host_of_vm, relocate_vmdk_volume, get_vmdk_base_volume_device):
        file_name = mock.sentinel.file_name
        backing = mock.Mock(fileName=file_name)
        original_device = mock.Mock(backing=backing)
        get_vmdk_base_volume_device.return_value = original_device

        new_file_name = mock.sentinel.new_file_name
        datastore = mock.sentinel.datastore
        new_backing = mock.Mock(fileName=new_file_name, datastore=datastore)
        device = mock.Mock(backing=new_backing)

        host = mock.sentinel.host
        get_host_of_vm.return_value = host
        rp = mock.sentinel.rp
        get_res_pool_of_host.return_value = rp

        instance = self._instance
        volume_ref = mock.sentinel.volume_ref
        vm_ref = mock.sentinel.vm_ref
        adapter_type = constants.ADAPTER_TYPE_BUSLOGIC
        disk_type = constants.DISK_TYPE_EAGER_ZEROED_THICK

        self._volumeops._consolidate_vmdk_volume(instance, vm_ref, device,
                                                 volume_ref, adapter_type,
                                                 disk_type)

        get_vmdk_base_volume_device.assert_called_once_with(volume_ref)
        relocate_vmdk_volume.assert_called_once_with(
            volume_ref, rp, datastore, host)
        detach_disk_from_vm.assert_called_once_with(
            volume_ref, instance, original_device, destroy_disk=True)
        attach_disk_to_vm.assert_called_once_with(
            volume_ref, instance, adapter_type, disk_type,
            vmdk_path=new_file_name)

    @mock.patch.object(volumeops.VMwareVolumeOps,
                       '_get_vmdk_base_volume_device')
    @mock.patch.object(volumeops.VMwareVolumeOps, '_relocate_vmdk_volume')
    @mock.patch.object(volumeops.VMwareVolumeOps, '_get_host_of_vm')
    @mock.patch.object(volumeops.VMwareVolumeOps, '_get_res_pool_of_host')
    @mock.patch.object(volumeops.VMwareVolumeOps, 'detach_disk_from_vm')
    @mock.patch.object(volumeops.VMwareVolumeOps, 'attach_disk_to_vm')
    def test_consolidate_vmdk_volume_with_missing_vmdk(
            self, attach_disk_to_vm, detach_disk_from_vm, get_res_pool_of_host,
            get_host_of_vm, relocate_vmdk_volume, get_vmdk_base_volume_device):
        file_name = mock.sentinel.file_name
        backing = mock.Mock(fileName=file_name)
        original_device = mock.Mock(backing=backing)
        get_vmdk_base_volume_device.return_value = original_device

        new_file_name = mock.sentinel.new_file_name
        datastore = mock.sentinel.datastore
        new_backing = mock.Mock(fileName=new_file_name, datastore=datastore)
        device = mock.Mock(backing=new_backing)

        host = mock.sentinel.host
        get_host_of_vm.return_value = host
        rp = mock.sentinel.rp
        get_res_pool_of_host.return_value = rp

        relocate_vmdk_volume.side_effect = [
            oslo_vmw_exceptions.FileNotFoundException, None]

        instance = mock.sentinel.instance
        volume_ref = mock.sentinel.volume_ref
        vm_ref = mock.sentinel.vm_ref
        adapter_type = constants.ADAPTER_TYPE_BUSLOGIC
        disk_type = constants.DISK_TYPE_EAGER_ZEROED_THICK

        self._volumeops._consolidate_vmdk_volume(instance, vm_ref, device,
                                                 volume_ref, adapter_type,
                                                 disk_type)

        get_vmdk_base_volume_device.assert_called_once_with(volume_ref)

        relocate_calls = [mock.call(volume_ref, rp, datastore, host),
                          mock.call(volume_ref, rp, datastore, host)]
        self.assertEqual(relocate_calls, relocate_vmdk_volume.call_args_list)
        detach_disk_from_vm.assert_called_once_with(
            volume_ref, instance, original_device)
        attach_disk_to_vm.assert_called_once_with(
            volume_ref, instance, adapter_type, disk_type,
            vmdk_path=new_file_name)

    def test_iscsi_get_host_iqn(self):
        host_mor = mock.Mock()
        iqn = 'iscsi-name'
        hba = vmwareapi_fake.HostInternetScsiHba(iqn)
        hbas = mock.MagicMock(HostHostBusAdapter=[hba])

        with contextlib.nested(
            mock.patch.object(vm_util, 'get_host_ref_for_vm',
                              return_value=host_mor),
            mock.patch.object(self._volumeops._session, '_call_method',
                              return_value=hbas)
        ) as (fake_get_host_ref_for_vm, fake_call_method):
            result = self._volumeops._iscsi_get_host_iqn(self._instance)

            fake_get_host_ref_for_vm.assert_called_once_with(
                            self._volumeops._session, self._instance)
            fake_call_method.assert_called_once_with(vutil,
                                    "get_object_property",
                                    host_mor,
                                    "config.storageDevice.hostBusAdapter")

            self.assertEqual(iqn, result)

    def test_iscsi_get_host_iqn_instance_not_found(self):
        host_mor = mock.Mock()
        iqn = 'iscsi-name'
        hba = vmwareapi_fake.HostInternetScsiHba(iqn)
        hbas = mock.MagicMock(HostHostBusAdapter=[hba])

        with contextlib.nested(
            mock.patch.object(vm_util, 'get_host_ref_for_vm',
                              side_effect=exception.InstanceNotFound('fake')),
            mock.patch.object(vm_util, 'get_host_ref',
                              return_value=host_mor),
            mock.patch.object(self._volumeops._session, '_call_method',
                              return_value=hbas)
        ) as (fake_get_host_ref_for_vm,
              fake_get_host_ref,
              fake_call_method):
            result = self._volumeops._iscsi_get_host_iqn(self._instance)

            fake_get_host_ref_for_vm.assert_called_once_with(
                        self._volumeops._session, self._instance)
            fake_get_host_ref.assert_called_once_with(
                        self._volumeops._session, self._volumeops._cluster)
            fake_call_method.assert_called_once_with(vutil,
                                    "get_object_property",
                                    host_mor,
                                    "config.storageDevice.hostBusAdapter")

            self.assertEqual(iqn, result)

    def test_get_volume_connector(self):
        vm_id = 'fake-vm'
        vm_ref = mock.MagicMock(value=vm_id)
        iqn = 'iscsi-name'
        url = 'test_url'
        self.flags(host_ip=url, group='vmware')

        with contextlib.nested(
            mock.patch.object(vm_util, 'get_vm_ref', return_value=vm_ref),
            mock.patch.object(self._volumeops, '_iscsi_get_host_iqn',
                              return_value=iqn)
        ) as (fake_get_vm_ref, fake_iscsi_get_host_iqn):
            connector = self._volumeops.get_volume_connector(self._instance)

            fake_get_vm_ref.assert_called_once_with(self._volumeops._session,
                                                    self._instance)
            fake_iscsi_get_host_iqn.assert_called_once_with(self._instance)

            self.assertEqual(url, connector['ip'])
            self.assertEqual(url, connector['host'])
            self.assertEqual(iqn, connector['initiator'])
            self.assertEqual(vm_id, connector['instance'])


text:
<?php

use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Psr\Log\LoggerInterface;

/**
 * appProdUrlGenerator
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appProdUrlGenerator extends Symfony\Component\Routing\Generator\UrlGenerator
{
    private static $declaredRoutes = array(
        'teaching_user_homepage' => array (  0 =>   array (  ),  1 =>   array (    '_controller' => 'Teaching\\UserBundle\\Controller\\UserController::indexAction',  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/usuario/',    ),  ),  4 =>   array (  ),),
        'teaching_user_messages' => array (  0 =>   array (  ),  1 =>   array (    '_controller' => 'Teaching\\UserBundle\\Controller\\UserController::messagesAction',  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/usuario/mensajes/',    ),  ),  4 =>   array (  ),),
        'teaching_teacher_homepage' => array (  0 =>   array (  ),  1 =>   array (    '_controller' => 'Teaching\\TeacherBundle\\Controller\\TeacherController::indexAction',  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/profesor/',    ),  ),  4 =>   array (  ),),
        'teaching_admin_homepage' => array (  0 =>   array (  ),  1 =>   array (    '_controller' => 'Teaching\\AdminBundle\\Controller\\AdminController::indexAction',  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/admin/',    ),  ),  4 =>   array (  ),),
        'teaching_homepage' => array (  0 =>   array (  ),  1 =>   array (    '_controller' => 'Teaching\\GeneralBundle\\Controller\\HomeController::indexAction',  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/',    ),  ),  4 =>   array (  ),),
        'exito' => array (  0 =>   array (  ),  1 =>   array (    '_controller' => 'Teaching\\GeneralBundle\\Controller\\HomeController::redirectAction',  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/validado',    ),  ),  4 =>   array (  ),),
        'login_check' => array (  0 =>   array (  ),  1 =>   array (  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/login_check',    ),  ),  4 =>   array (  ),),
        'logout' => array (  0 =>   array (  ),  1 =>   array (  ),  2 =>   array (  ),  3 =>   array (    0 =>     array (      0 => 'text',      1 => '/logout',    ),  ),  4 =>   array (  ),),
    );

    /**
     * Constructor.
     */
    public function __construct(RequestContext $context, LoggerInterface $logger = null)
    {
        $this->context = $context;
        $this->logger = $logger;
    }

    public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
    {
        if (!isset(self::$declaredRoutes[$name])) {
            throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
        }

        list($variables, $defaults, $requirements, $tokens, $hostTokens) = self::$declaredRoutes[$name];

        return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens);
    }
}