text:
namespace apps {

APP_ENUM_TO_STRING(ConditionType,
                   kScheme,
                   kHost,
                   kPath,
                   kAction,
                   kMimeType,
                   kFile)

ConditionValue::ConditionValue(const std::string& value,
                               PatternMatchType match_type)
    : value(value), match_type(match_type) {}

ConditionValue::~ConditionValue() = default;

bool ConditionValue::operator==(const ConditionValue& other) const {
  return value == other.value && match_type == other.match_type;
}

bool ConditionValue::operator!=(const ConditionValue& other) const {
  return !(*this == other);
}

std::string ConditionValue::ToString() const {
  std::stringstream out;
  if (match_type == PatternMatchType::kSuffix) {
    out << "*";
  }
  out << value;
  if (match_type == PatternMatchType::kPrefix) {
    out << "*";
  }
  return out.str();
}

Condition::Condition(ConditionType condition_type,
                     ConditionValues condition_values)
    : condition_type(condition_type),
      condition_values(std::move(condition_values)) {}

Condition::~Condition() = default;

bool Condition::operator==(const Condition& other) const {
  if (condition_values.size() != other.condition_values.size()) {
    return false;
  }

  for (int i = 0; i < static_cast<int>(condition_values.size()); i++) {
    if (*condition_values[i] != *other.condition_values[i]) {
      return false;
    }
  }

  return condition_type == other.condition_type;
}

bool Condition::operator!=(const Condition& other) const {
  return !(*this == other);
}

ConditionPtr Condition::Clone() const {
  ConditionValues values;
  for (const auto& condition_value : condition_values) {
    values.push_back(std::make_unique<ConditionValue>(
        condition_value->value, condition_value->match_type));
  }

  return std::make_unique<Condition>(condition_type, std::move(values));
}

std::string Condition::ToString() const {
  std::stringstream out;
  out << " - " << EnumToString(condition_type) << ":";
  for (const auto& condition_value : condition_values) {
    out << " " << condition_value->ToString();
  }
  return out.str();
}

IntentFilter::IntentFilter() = default;
IntentFilter::~IntentFilter() = default;

bool IntentFilter::operator==(const IntentFilter& other) const {
  if (conditions.size() != other.conditions.size()) {
    return false;
  }

  for (int i = 0; i < static_cast<int>(conditions.size()); i++) {
    if (*conditions[i] != *other.conditions[i]) {
      return false;
    }
  }

  return activity_name == other.activity_name &&
         activity_label == other.activity_label;
}

bool IntentFilter::operator!=(const IntentFilter& other) const {
  return !(*this == other);
}

IntentFilterPtr IntentFilter::Clone() const {
  IntentFilterPtr intent_filter = std::make_unique<IntentFilter>();

  for (const auto& condition : conditions) {
    intent_filter->conditions.push_back(condition->Clone());
  }

  if (activity_name.has_value())
    intent_filter->activity_name = activity_name.value();

  if (activity_label.has_value())
    intent_filter->activity_label = activity_label.value();

  return intent_filter;
}

void IntentFilter::AddSingleValueCondition(
    ConditionType condition_type,
    const std::string& value,
    PatternMatchType pattern_match_type) {
  ConditionValues condition_values;
  condition_values.push_back(
      std::make_unique<ConditionValue>(value, pattern_match_type));
  conditions.push_back(
      std::make_unique<Condition>(condition_type, std::move(condition_values)));
}

int IntentFilter::GetFilterMatchLevel() {
  int match_level = static_cast<int>(IntentFilterMatchLevel::kNone);
  for (const auto& condition : conditions) {
    switch (condition->condition_type) {
      case ConditionType::kAction:
        // Action always need to be matched, so there is no need for
        // match level.
        break;
      case ConditionType::kScheme:
        match_level += static_cast<int>(IntentFilterMatchLevel::kScheme);
        break;
      case ConditionType::kHost:
        match_level += static_cast<int>(IntentFilterMatchLevel::kHost);
        break;
      case ConditionType::kPath:
        match_level += static_cast<int>(IntentFilterMatchLevel::kPath);
        break;
      case ConditionType::kMimeType:
      case ConditionType::kFile:
        match_level += static_cast<int>(IntentFilterMatchLevel::kMimeType);
        break;
    }
  }
  return match_level;
}

void IntentFilter::GetMimeTypesAndExtensions(
    std::set<std::string>& mime_types,
    std::set<std::string>& file_extensions) {
  for (const auto& condition : conditions) {
    if (condition->condition_type != ConditionType::kFile) {
      continue;
    }
    for (const auto& condition_value : condition->condition_values) {
      if (condition_value->match_type == PatternMatchType::kFileExtension) {
        file_extensions.insert(condition_value->value);
      }
      if (condition_value->match_type == PatternMatchType::kMimeType) {
        mime_types.insert(condition_value->value);
      }
    }
  }
}

std::set<std::string> IntentFilter::GetSupportedLinksForAppManagement() {
  std::set<std::string> hosts;
  std::set<std::string> paths;
  bool is_http_or_https = false;

  for (auto& condition : conditions) {
    // For scheme conditions we check if it's http or https and set a Boolean
    // if this intent filter is for one of those schemes.
    if (condition->condition_type == ConditionType::kScheme) {
      for (auto& condition_value : condition->condition_values) {
        // We only care about http and https schemes.
        if (condition_value->value == url::kHttpScheme ||
            condition_value->value == url::kHttpsScheme) {
          is_http_or_https = true;
          break;
        }
      }

      // There should only be one condition of type |kScheme| so if there
      // aren't any http or https scheme values this indicates that no http or
      // https scheme exists in the intent filter and thus we will have to
      // return an empty list.
      if (!is_http_or_https) {
        break;
      }
    }

    // For host conditions we add each value to the |hosts| set.
    if (condition->condition_type == ConditionType::kHost) {
      for (auto& condition_value : condition->condition_values) {
        // Prepend the wildcard to indicate any subdomain in the hosts
        std::string host = condition_value->value;
        if (condition_value->match_type == PatternMatchType::kSuffix) {
          host = "*" + host;
        }
        hosts.insert(host);
      }
    }

    // For path conditions we add each value to the |paths| set.
    if (condition->condition_type == ConditionType::kPath) {
      for (auto& condition_value : condition->condition_values) {
        std::string value = condition_value->value;
        // Glob and literal patterns can be printed exactly, but prefix
        // patterns must have be appended with "*" to indicate that
        // anything with that prefix can be matched.
        if (condition_value->match_type == PatternMatchType::kPrefix) {
          value.append("*");
        }
        paths.insert(value);
      }
    }
  }

  // We only care about http and https schemes.
  if (!is_http_or_https) {
    return std::set<std::string>();
  }

  std::set<std::string> supported_links;
  for (auto& host : hosts) {
    for (auto& path : paths) {
      if (path.front() == '/') {
        supported_links.insert(host + path);
      } else {
        supported_links.insert(host + "/" + path);
      }
    }
  }

  return supported_links;
}

bool IntentFilter::IsBrowserFilter() {
  if (GetFilterMatchLevel() !=
      static_cast<int>(IntentFilterMatchLevel::kScheme)) {
    return false;
  }
  for (const auto& condition : conditions) {
    if (condition->condition_type != ConditionType::kScheme) {
      continue;
    }
    for (const auto& condition_value : condition->condition_values) {
      if (condition_value->value == url::kHttpScheme ||
          condition_value->value == url::kHttpsScheme) {
        return true;
      }
    }
  }

  return false;
}

bool IntentFilter::IsFileExtensionsFilter() {
  for (const auto& condition : conditions) {
    // We expect action conditions to be paired with file conditions.
    if (condition->condition_type == ConditionType::kAction) {
      continue;
    }
    if (condition->condition_type != ConditionType::kFile) {
      return false;
    }
    for (const auto& condition_value : condition->condition_values) {
      if (condition_value->match_type != PatternMatchType::kFileExtension) {
        return false;
      }
    }
  }
  return true;
}

bool IntentFilter::FilterNeedsUpgrade() {
  for (const auto& condition : conditions) {
    if (condition->condition_type == ConditionType::kAction) {
      return false;
    }
  }
  return true;
}

std::string IntentFilter::ToString() const {
  std::stringstream out;
  if (activity_name.has_value()) {
    out << " activity_name: " << activity_name.value() << std::endl;
  }
  if (activity_label.has_value()) {
    out << " activity_label: " << activity_label.value() << std::endl;
  }
  if (!conditions.empty()) {
    out << " conditions:" << std::endl;
    for (const auto& condition : conditions) {
      out << condition->ToString() << std::endl;
    }
  }
  return out.str();
}

IntentFilters CloneIntentFilters(const IntentFilters& intent_filters) {
  IntentFilters ret;
  for (const auto& intent_filter : intent_filters) {
    ret.push_back(intent_filter->Clone());
  }
  return ret;
}

base::flat_map<std::string, IntentFilters> CloneIntentFiltersMap(
    const base::flat_map<std::string, IntentFilters>& intent_filters_map) {
  base::flat_map<std::string, IntentFilters> ret;
  for (const auto& it : intent_filters_map) {
    ret.insert(std::make_pair(it.first, CloneIntentFilters(it.second)));
  }
  return ret;
}

bool IsEqual(const IntentFilters& source, const IntentFilters& target) {
  if (source.size() != target.size()) {
    return false;
  }

  for (int i = 0; i < static_cast<int>(source.size()); i++) {
    if (*source[i] != *target[i]) {
      return false;
    }
  }
  return true;
}

bool Contains(const IntentFilters& intent_filters,
              const IntentFilterPtr& intent_filter) {
  for (const auto& filter : intent_filters) {
    if (*filter == *intent_filter) {
      return true;
    }
  }
  return false;
}

ConditionType ConvertMojomConditionTypeToConditionType(
    const apps::mojom::ConditionType& mojom_condition_type) {
  switch (mojom_condition_type) {
    case apps::mojom::ConditionType::kScheme:
      return ConditionType::kScheme;
    case apps::mojom::ConditionType::kHost:
      return ConditionType::kHost;
    case apps::mojom::ConditionType::kPath:
      return ConditionType::kPath;
    case apps::mojom::ConditionType::kAction:
      return ConditionType::kAction;
    case apps::mojom::ConditionType::kMimeType:
      return ConditionType::kMimeType;
    case apps::mojom::ConditionType::kFile:
      return ConditionType::kFile;
  }
}

apps::mojom::ConditionType ConvertConditionTypeToMojomConditionType(
    const ConditionType& condition_type) {
  switch (condition_type) {
    case ConditionType::kScheme:
      return apps::mojom::ConditionType::kScheme;
    case ConditionType::kHost:
      return apps::mojom::ConditionType::kHost;
    case ConditionType::kPath:
      return apps::mojom::ConditionType::kPath;
    case ConditionType::kAction:
      return apps::mojom::ConditionType::kAction;
    case ConditionType::kMimeType:
      return apps::mojom::ConditionType::kMimeType;
    case ConditionType::kFile:
      return apps::mojom::ConditionType::kFile;
  }
}

PatternMatchType ConvertMojomPatternMatchTypeToPatternMatchType(
    const apps::mojom::PatternMatchType& mojom_pattern_match_type) {
  switch (mojom_pattern_match_type) {
    case apps::mojom::PatternMatchType::kLiteral:
      return PatternMatchType::kLiteral;
    case apps::mojom::PatternMatchType::kPrefix:
      return PatternMatchType::kPrefix;
    case apps::mojom::PatternMatchType::kGlob:
      return PatternMatchType::kGlob;
    case apps::mojom::PatternMatchType::kMimeType:
      return PatternMatchType::kMimeType;
    case apps::mojom::PatternMatchType::kFileExtension:
      return PatternMatchType::kFileExtension;
    case apps::mojom::PatternMatchType::kIsDirectory:
      return PatternMatchType::kIsDirectory;
    case apps::mojom::PatternMatchType::kSuffix:
      return PatternMatchType::kSuffix;
  }
}

apps::mojom::PatternMatchType ConvertPatternMatchTypeToMojomPatternMatchType(
    const PatternMatchType& pattern_match_type) {
  switch (pattern_match_type) {
    case PatternMatchType::kLiteral:
      return apps::mojom::PatternMatchType::kLiteral;
    case PatternMatchType::kPrefix:
      return apps::mojom::PatternMatchType::kPrefix;
    case PatternMatchType::kGlob:
      return apps::mojom::PatternMatchType::kGlob;
    case PatternMatchType::kMimeType:
      return apps::mojom::PatternMatchType::kMimeType;
    case PatternMatchType::kFileExtension:
      return apps::mojom::PatternMatchType::kFileExtension;
    case PatternMatchType::kIsDirectory:
      return apps::mojom::PatternMatchType::kIsDirectory;
    case PatternMatchType::kSuffix:
      return apps::mojom::PatternMatchType::kSuffix;
  }
}

ConditionValuePtr ConvertMojomConditionValueToConditionValue(
    const apps::mojom::ConditionValuePtr& mojom_condition_value) {
  if (!mojom_condition_value) {
    return nullptr;
  }

  ConditionValuePtr condition_value = std::make_unique<ConditionValue>(
      mojom_condition_value->value,
      ConvertMojomPatternMatchTypeToPatternMatchType(
          mojom_condition_value->match_type));
  return condition_value;
}

apps::mojom::ConditionValuePtr ConvertConditionValueToMojomConditionValue(
    const ConditionValuePtr& condition_value) {
  auto mojom_condition_value = apps::mojom::ConditionValue::New();
  if (!condition_value) {
    return mojom_condition_value;
  }

  mojom_condition_value->value = condition_value->value;
  mojom_condition_value->match_type =
      ConvertPatternMatchTypeToMojomPatternMatchType(
          condition_value->match_type);
  return mojom_condition_value;
}

ConditionPtr ConvertMojomConditionToCondition(
    const apps::mojom::ConditionPtr& mojom_condition) {
  if (!mojom_condition) {
    return nullptr;
  }

  ConditionValues values;
  for (const auto& condition_value : mojom_condition->condition_values) {
    values.push_back(
        ConvertMojomConditionValueToConditionValue(condition_value));
  }
  return std::make_unique<Condition>(
      ConvertMojomConditionTypeToConditionType(mojom_condition->condition_type),
      std::move(values));
}

apps::mojom::ConditionPtr ConvertConditionToMojomCondition(
    const ConditionPtr& condition) {
  auto mojom_condition = apps::mojom::Condition::New();
  if (!condition) {
    return mojom_condition;
  }

  mojom_condition->condition_type =
      ConvertConditionTypeToMojomConditionType(condition->condition_type);

  for (const auto& condition_value : condition->condition_values) {
    if (condition_value) {
      mojom_condition->condition_values.push_back(
          ConvertConditionValueToMojomConditionValue(condition_value));
    }
  }
  return mojom_condition;
}

IntentFilterPtr ConvertMojomIntentFilterToIntentFilter(
    const apps::mojom::IntentFilterPtr& mojom_intent_filter) {
  if (!mojom_intent_filter) {
    return nullptr;
  }

  IntentFilterPtr intent_filter = std::make_unique<IntentFilter>();
  for (const auto& condition : mojom_intent_filter->conditions) {
    if (condition) {
      intent_filter->conditions.push_back(
          ConvertMojomConditionToCondition(condition));
    }
  }

  if (mojom_intent_filter->activity_name.has_value())
    intent_filter->activity_name = mojom_intent_filter->activity_name.value();

  if (mojom_intent_filter->activity_label.has_value())
    intent_filter->activity_label = mojom_intent_filter->activity_label.value();

  return intent_filter;
}

apps::mojom::IntentFilterPtr ConvertIntentFilterToMojomIntentFilter(
    const IntentFilterPtr& intent_filter) {
  auto mojom_intent_filter = apps::mojom::IntentFilter::New();
  if (!intent_filter) {
    return mojom_intent_filter;
  }

  for (const auto& condition : intent_filter->conditions) {
    if (condition) {
      mojom_intent_filter->conditions.push_back(
          ConvertConditionToMojomCondition(condition));
    }
  }

  mojom_intent_filter->activity_name = intent_filter->activity_name;
  mojom_intent_filter->activity_label = intent_filter->activity_label;
  return mojom_intent_filter;
}

IntentFilters ConvertMojomIntentFiltersToIntentFilters(
    const std::vector<apps::mojom::IntentFilterPtr>& mojom_intent_filters) {
  IntentFilters intent_filters;
  intent_filters.reserve(mojom_intent_filters.size());
  for (const auto& mojom_intent_filter : mojom_intent_filters) {
    intent_filters.push_back(
        ConvertMojomIntentFilterToIntentFilter(mojom_intent_filter));
  }
  return intent_filters;
}

std::vector<apps::mojom::IntentFilterPtr>
ConvertIntentFiltersToMojomIntentFilters(const IntentFilters& intent_filters) {
  std::vector<apps::mojom::IntentFilterPtr> mojom_intent_filters;
  mojom_intent_filters.reserve(intent_filters.size());
  for (const auto& intent_filter : intent_filters) {
    mojom_intent_filters.push_back(
        ConvertIntentFilterToMojomIntentFilter(intent_filter));
  }
  return mojom_intent_filters;
}

}  // namespace apps


text:
/* jslint node: true */
/* global featureFile, scenarios, steps */
"use strict";

var Yadda = require('yadda');
Yadda.plugins.mocha.AsyncStepLevelPlugin.init();

new Yadda.FeatureFileSearch('../features').each(function(file) {

    featureFile(file, function(feature) {

        var library = require('./AddaPlayer');
        var yadda = new Yadda.Yadda(library);

		before(function(done) {
		// ensure a clean environment
		console.log('running before');
            done();
        });

        scenarios(feature.scenarios, function(scenario) {
            steps(scenario.steps, function(step, done) {
                yadda.yadda(step, done);
            });
        });

		after(function(done) {
		// ensure a clean environment
		console.log('running after');
            done();
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
import os
import stat
from setuptools import setup
from setuptools.command import install
import shutil

shutil.copyfile('bottle-run.sh', 'bottle-run')

class Installer(install.install):
    """ http://stackoverflow.com/a/25761434/240515 """
    def run(self):
        install.install.run(self)

        for filepath in self.get_outputs():
            _, ext = os.path.splitext(filepath)
            if ext in ('.fish', '.sh', '.zsh'):
                mode = stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
                os.chmod(filepath, mode)
setup(
    name='wine_env',
    version='1.0',
    packages=['wine_env'],
    cmdclass={'install': Installer},
    entry_points={
        'console_scripts': [
            'bottle = wine_env.bottle:main',
        ]
    },
    scripts=(
        'bottle-run',
        'bottler.sh',
        'bottler.fish',
        'wine_env_complete.sh',
        'wine_env_complete.zsh'
    ),
)


text:
1. This repo is a base for all of my code to live in.
1. There is no production code written for business/a company.

# Coding Principles

Because software development is continuously evolving, I hope to demonstrate my coding practices and principles within this repo, which are also evolving as the field does.

Some of my current core beliefs for writing code include but are not limited to:
1. Code should be written with the intention that other people/developers will read it.
  * Variable and method/function names should express explicit meaning of what they represent.
    * Shorter names are generally better than longer names, but longer names are fine if they add clarity.
    * Concise and to-the-point is best when naming.
    * Don't append the word 'class' or 'function' or 'method' to names. (Follow conventions of language first.)
2. Methods/Functions should follow the Single Responsibility Principle at all times (or most, whenever possible), meaning a method should have a single, clear action/job that it is performing. If a method is has two separate behaviors, split it into two separate methods.
3. Decouple dependencies whenever possible.
4. Spending a little time to refactor code often minimizes technical debt compared to waiting until the code becomes so complex that it is extremely difficult to refactor.
5. All languages and tools have their strengths and weaknesses. Use the right language or tool for the job, instead of forcing what I already know to fit the project.
6. Test, test, test. Use test-driven development. Unit tests, acceptance tests, and integration tests are all integral in creating working code.
7. Build security throughout instead of tacking it on at the end.
8. Injecting faults or bugs into a system intentionally (under controlled circumstances) can help to understand how the program will react to those faults, leading to solutions on how to prevent the faults from happening in production. AKA 'resilience engineering'.
9. Make code so readable (because the naming of variables and methods is so clear) that comments become unnecessary, but still comment.
10. Comments are necessary, especially if there is a behavior that is not transparent.
  * If on a team or project with others, follow a standard commenting scheme.
11. While working on a team:
  * Make work as transparent as possible.
    * Use GitHub or other tracker to track and assign issues.
    * When commiting to a repo, write informative commit messages, but not too lengthy. Concise is best.
    * Use a kanban board or something like it to track work. (Again, GitHub works for this.)
  * Commit often. No code nukes. Lots of commits with small amounts of code is better than one commit with a huge amount of code.
12. Reflect on mistakes and/or errors to better improve myself and my code.


text: A IM web application using socket.io to build it


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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.camelinaction</groupId>
        <artifactId>parent</artifactId>
        <version>2.0.0</version>
    </parent>

    <artifactId>chapter16</artifactId>
    <packaging>pom</packaging>
    <version>2.0.0</version>
    <name>Camel in Action 2 :: Chapter 16</name>

    <modules>
        <module>health</module>
        <module>logging</module>
    </modules>

</project>


text:
require 'whois/record/parser/base'

module Whois
  class Record
    class Parser

      # The Blank parser isn't a real parser. It's just a fake parser
      # that acts as a parser but doesn't provide any special capability.
      #
      # It doesn't register itself in the parser_registry,
      # it doesn't scan any string, it only exists to be initialized
      # in case a record needs to create a parser for a WHOIS server
      # not yet supported.
      #
      class Blank < Base

        Whois::Record::Parser::PROPERTIES.each do |method|
          define_method(method) do
            raise ParserNotFound, "Unable to find a parser for the server `#{part.host}'"
          end
        end

      end

    end
  end
end


text:
CUniteStandardDataModel::CUniteStandardDataModel(void)
{
}

CUniteStandardDataModel::~CUniteStandardDataModel(void)
{
}


text:
/// <amd-dependency path="canvasRenderer"/>
/// <amd-dependency path="projector"/>
/// <amd-dependency path="jquery"/>

import app = require("../app");

/**
 * @summary Directive for scroll to an element by its identifier.
 * @author  Cyril Schumacher
 * @class
 */
class CanvasParticlesWavesDirective implements ng.IDirective {
    /**
     * @summary Gets the screen height.
     * @private
     * @return {number} The screen height.
     */
    private get SCREEN_HEIGHT(): number {
        return window.innerHeight;
    }

    /**
     * @summary Gets the screen width.
     * @private
     * @return {number} The screen width.
     */
    private get SCREEN_WIDTH(): number {
        return window.innerWidth;
    }

    /**
     * @summary Gets the separation.
     * @private
     * @return {number} The separation.
     */
    private get SEPARATION(): number {
        return 100;
    }

    /**
     * @summary Dependencies injection.
     * @type {Array<string>}
     */
    public static $inject: Array<string> = [];

    /**
     * @summary Restrict option.
     * @type {string}
     */
    public restrict: string = "A";

    /**
     * @summary X.
     * @private
     * @type {number}
     */
    private _amountX: number;

    /**
     * @summary Y.
     * @private
     * @type {number}
     */
    private _amountY: number;

    /**
     * @summary Camera.
     * @private
     * @type {THREE.PerspectiveCamera}
     */
    private _camera: THREE.PerspectiveCamera;

    /**
     * @summary Count position.
     * @private
     * @type {number}
     */
    private _count: number;

    /**
     * Renderer identifier.
     * @private
     * @type {number}
     */
    private _idRenderer: number;

    /**
     * @summary Horizontal position of the mouse.
     * @private
     * @type {number}
     */
    private _mouseX: number;

    /**
     * @summary Vertical position of the mouse.
     * @private
     * @type {number}
     */
    private _mouseY: number;

    /**
     * @summary Particles.
     * @private
     * @type {Array}
     */
    private _particles: Array<THREE.Sprite>;

    /**
     * @summary Render.
     * @private
     * @type {THREE.CanvasRenderer}
     */
    private _renderer: THREE.CanvasRenderer;

    /**
     * @summary Scene.
     * @private
     * @type {THREE.Scene}
     */
    private _scene: THREE.Scene;

    /**
     * @summary Horizontal size of the window.
     * @private
     * @type {number}
     */
    private _windowHalfX: number;

    /**
     * @summary Vertical size of the window.
     * @private
     * @type {number}
     */
    private _windowHalfY: number;

    /**
     * @summary Animates the animation.
     * @private
     */
    private _animate = (): void => {
        this._idRenderer = requestAnimationFrame(this._animate);
        this._render();
    };

    /**
     * @summary Destroys the directive.
     * @private
     */
    private _destroy = (): void => {
        cancelAnimationFrame(this._idRenderer);
        this._idRenderer = -1;
    };

    /**
     * @summary Initializes the animation.
     * @private
     */
    private _initialize = (container: HTMLDivElement): void => {
        this._idRenderer = -1;
        this._mouseX = 0;
        this._mouseY = 0;
        this._amountX = 50;
        this._amountY = 50;
        this._count = 0;
        this._windowHalfX = window.innerWidth / 2;
        this._windowHalfY = window.innerHeight / 2;

        this._camera = new THREE.PerspectiveCamera(100, (this.SCREEN_WIDTH / this.SCREEN_HEIGHT), 1, 10000);
        this._camera.position.z = 500;

        this._scene = new THREE.Scene();
        this._particles = new Array<THREE.Sprite>();

        let PI2 = Math.PI * 2;
        let material = new THREE.SpriteCanvasMaterial({
            color: 0xA6ABB2,
            program: (context) => {
                context.beginPath();
                context.arc(0, 0, 0.5, 0, PI2, true);
                context.fill();
            }
        });

        let i = 0;
        for (var ix = 0; ix < this._amountX; ix++) {
            for (var iy = 0; iy < this._amountY; iy++) {
                let particle = this._particles[i++] = new THREE.Sprite(material);
                particle.position.x = (ix * this.SEPARATION) - ((this._amountX * this.SEPARATION) / 2);
                particle.position.z = (iy * this.SEPARATION) - ((this._amountY * this.SEPARATION) / 2);

                this._scene.add(particle);
            }
        }

		const parameters: THREE.CanvasRendererParameters = { alpha: true };
        this._renderer = new THREE.CanvasRenderer(parameters);
        this._renderer.setPixelRatio(window.devicePixelRatio);
        this._renderer.setSize(window.innerWidth, window.innerHeight);
        container.appendChild(this._renderer.domElement);
    };

    /**
     * @summary Determines if the WebGL is supported.
     * @private
     * @return {boolean} True if the WebGL is supported, otherwise, False.
     */
    private _isWebGLSupported = (): boolean => {
        return (() => {
            try {
                return !!window["WebGLRenderingContext"] && !!document.createElement("canvas").getContext("experimental-webgl");
            } catch (e) {
                return false;
            }
        })();
    };

    /**
     * @summary Raises when the window is resized.
     * @private
     */
    private _onWindowResize = (): void => {
        this._windowHalfX = window.innerWidth / 2;
        this._windowHalfY = window.innerHeight / 2;

        this._camera.aspect = window.innerWidth / window.innerHeight;
        this._camera.updateProjectionMatrix();

        this._renderer.setSize(window.innerWidth, window.innerHeight);
    };

    /**
     * @summary Raises when the mouse pointer is moved over the control.
     * @private
     */
    private _onDocumentMouseMove = (event: MouseEvent): void => {
        this._mouseX = event.clientX - this._windowHalfX;
        this._mouseY = event.clientY - this._windowHalfY;
    };

    /**
     * @summary Raises when the user makes contact with the touch surface and
     * creates a touch point inside the element the event is bound to.
     * @private
     */
    private _onDocumentTouchStart = (event: TouchEvent): void => {
        if (event.touches.length > 1) {
            event.preventDefault();

            this._mouseX = event.touches[0].pageX - this._windowHalfX;
            this._mouseY = event.touches[0].pageY - this._windowHalfY;
        }
    };

    /**
     * @summary Raises when the user moves the touch point across the touch surface.
     * @private
     */
    private _onDocumentTouchMove = (event: TouchEvent): void => {
        if (event.touches.length === 1) {
            event.preventDefault();

            this._mouseX = event.touches[0].pageX - this._windowHalfX;
            this._mouseY = event.touches[0].pageY - this._windowHalfY;
        }
    };

    /**
     * @summary Renders the animation.
     * @private
     */
    private _render = (): void => {
        this._camera.position.x += (this._mouseX - this._camera.position.x) * .05;
        this._camera.position.y += (- this._mouseY - this._camera.position.y) * .05;
        this._camera.lookAt(this._scene.position);

        let i = 0;
        for (var ix = 0; ix < this._amountX; ix++) {
            for (var iy = 0; iy < this._amountY; iy++) {
                let particle = this._particles[i++];
                particle.position.y = (Math.sin((ix + this._count) * 0.3) * 50) + (Math.sin((iy + this._count) * 0.5) * 50);
                particle.scale.x = (Math.sin((ix + this._count) * 0.3) + 1) * 4 + (Math.sin((iy + this._count) * 0.5) + 1) * 4;
                particle.scale.y = particle.scale.x;
            }
        }

        this._renderer.render(this._scene, this._camera);
        this._count += 0.1;
    };

    /**
     * @summary Manipulates the DOM of the current page.
     * @param {IScope}      scope   Angular scope object.
     * @param {JQuery}      element jqLite-wrapped element that this directive matches.
     * @param {IAttributes} attrs   hash object with key-value pairs of normalized attribute names and their corresponding attribute values.
     */
    public link = (scope: ng.IScope, element: JQuery, attrs: ng.IAttributes): void => {
        if (this._isWebGLSupported()) {
            this._initialize(<HTMLDivElement>element[0]);
            this._animate();

            // Document events.
            document.addEventListener("mousemove", this._onDocumentMouseMove, false);
            document.addEventListener("touchstart", this._onDocumentTouchStart, false);
            document.addEventListener("touchmove", this._onDocumentTouchMove, false);

            // Windows events.
            window.addEventListener("resize", this._onWindowResize, false);

            // Element events.
            element.on("$destroy", this._destroy);
        }
    };
}

export = CanvasParticlesWavesDirective;
app.module.directive("canvasParticlesWaves", () => new CanvasParticlesWavesDirective());


text:
package org.jhaws.common.lang;

import java.awt.BorderLayout;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

import org.jhaws.common.pool.Job;
import org.jhaws.common.pool.Pool;
import org.jhaws.common.pool.Task;

// https://stackoverflow.com/questions/10961714/how-to-properly-stop-the-thread-in-java
public class ThreadTest {
    public static void main(String[] args) {
        Pool<Object> wdljobs = new Pool<>("test", 2);
        Map<Job<Object>, Task<Object>> map = new LinkedHashMap<>();
        for (int i = 0; i < 1; i++) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    System.out.println("started " + this);
                    try {
                        // if (true) throw new RuntimeException();
                        while (true) {
                            // System.out.println(Thread.currentThread() + "-" + System.currentTimeMillis());
                            Thread.sleep(1000l);
                            // if (Thread.currentThread().isInterrupted()) {
                            // break;
                            // }
                            System.out.println("running " + this);
                        }
                    } catch (InterruptedException ex) {
                        System.out.println("interrupted " + this);
                    }
                    System.out.println("done " + this);
                }
            };
            Job<Object> job = new Job<>(r, null);
            Task<Object> task = wdljobs.addJob(job);
            map.put(job, task);
        }

        JFrame f = new JFrame();
        f.setSize(200, 200);
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JButton b = new JButton("x");
        b.addActionListener(ev -> {
            System.out.println("A" + wdljobs.getAll().size() + "/D" + wdljobs.getCompleted().size() + "/C" + wdljobs.getCurrent().size() + "/Q" + wdljobs.getQueued().size() + "/F" + wdljobs.getFailed().size() + "/X" + wdljobs.getCancelled().size());
            CollectionUtils8.reverse(map.values().stream()).forEach(wdljobs::remove);
            System.out.println("A" + wdljobs.getAll().size() + "/D" + wdljobs.getCompleted().size() + "/C" + wdljobs.getCurrent().size() + "/Q" + wdljobs.getQueued().size() + "/F" + wdljobs.getFailed().size() + "/X" + wdljobs.getCancelled().size());
        });
        f.getContentPane().add(b, BorderLayout.CENTER);
        f.setVisible(true);
    }
}


text:
package com.haulmont.cuba.gui.components;

/**
 * A component that is marked with this interface allows to manage additional style names for options displayed
 * by this component.
 */
public interface HasOptionsStyleProvider {
    /**
     * Sets the given {@code optionsStyleProvider} to the component.
     *
     * @param optionsStyleProvider {@link OptionsStyleProvider} instance that will be user by this component
     */
    void setOptionsStyleProvider(OptionsStyleProvider optionsStyleProvider);

    /**
     * @return {@link OptionsStyleProvider} instance that is used by this component
     */
    OptionsStyleProvider getOptionsStyleProvider();
}


text:
<?php

namespace GeneratedHydratorPerformance;

use stdClass;

/**
 * Performance tests for {@see \GeneratedHydrator\ClassGenerator\HydratorGenerator} produced
 * objects
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 */
class StdClassHydratonEvent extends AbstractHydratorPerformanceAthleticEvent
{
    /**
     * {@inheritDoc}
     */
    protected function getHydratedObject()
    {
        return new stdClass();
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=us_ascii" />
<meta name="generator" content="Docutils 0.5: http://docutils.sourceforge.net/" />
<title>Tutorial of GUI front-end GemX</title>

Tutorial of GUI front-end GemX

<col class="field-name" />
<col class="field-body" />

Author:	Toshihiro Kamiya

Date:	2008/May/7

Contact:	info@ccfinder.net

Copyright:	2005-2008 ( C ) Toshihiro Kamiya. All rights reserved.

Contents

1. Detecting Code Clone

2. Investigating Code Clones

2.1 Scatter Plot

2.2 File Table

2.3 Source Text

2.4 Clone-Set Table

2.5 Saving Detected Code Clone or Scope

3. Analyzing Code Clones by Metrics

File Metrics

Clone Set Metrics

Line-based Metrics

1. Detecting Code Clone

Specify target source code from menu [File]-[Detect Clones].
That is, select a (preprocess script of) programming language and directories of the garget source code.

By "Add Direcotry" button or drag-and-drop, add directories to the "Target directory list".

CCFinderX will look up source files recursively from the directories.

In the options dialog, use default values at first. Refer the manual for detail of each option.

After that, the tool will detect code clones. When the detection finished, views of the tool will be updated.

<col class="field-name" />
<col class="field-body" />

 Tip:	When the detected code clones are too many, check "Use prescreening" in the optoins dialog.

<col class="field-name" />
<col class="field-body" />

 Tip:	By default, the order of source files is a lexical order of their path (multi-byte encoding lexical oder).
CCFinderX seraches a file with one of the extensions that are predefined to each programming language
(For example, .c, .cc, .cpp, .cxx, .h, .hh, .hpp, .hxx for C++).
In order to change the order of source files and/or specify source files with special extension,
make a file list by hand (file list is a text file, which includes a path of source file per line),
and use GemX's menu [File]-[Detect Clones from File List].

2. Investigating Code Clones

You can investigate the detected code clones with views named File Table, Clone-Set Table, Scatter Plot, and Source Text, Scrapbook, and a Search box.

<col class="field-name" />
<col class="field-body" />

File Table:	This view shows a list of target source files.

Clone-Set Table:

 	This view shows a list of the detected code clones.

Scatter Plot:	This view shows where and how the code clones are distributed in the whole source files.

Source Text:	This view shows text of a source file. Code clones are illustrated as highlighted texts.

Scrapbook:	You can copy the code fragments shwon in Source Text view to Scrapbook.
This view is almost the same as Source Text, except for Scrapbook does not follow the selection change in File Table or Clone-Set Table.

Search box:	Search in File Table, Clone-Set Table, Source Text, or Scrapbook.

2.1 Scatter Plot

This view shows where and how the code clones are distributed in the whole source files.
Checkboxes at the upper side of Scatter Plot are used to turn on/off boundary of source files, directory, etc.
Refer the manual for the detail of each option.

Gray vertical and horizontal lines are boundaries of the source files, that is, locations of the end-of-flies.

Squares drawn by black lines (on the main diagonal line) are directories.

Black lines (and dots) that located parallel to the main diagonal line are code clones

The corresponding orthogonal projections to the horizontal axis and vertical axis are the locations of similar code fragments.

Also, The list of source files are shown in File Table at the left of the Scatter Plot.

Narrowing Down of File List (Zooming Scatter Plot)

Select files by dragging. Then, from right-click menu [Fit Scope to Selected Files],
you can narrow down the target files to the selected files.
(This operation will also affect File Table, that is, the list of files in it will be updated.)

In order to undo this operation, use right-click menu [Pop Scope].
This option often cause missing number in File ID's.
The file boundaries between such discontinuous file ID's are shown by dotted-line.

<col class="field-name" />
<col class="field-body" />

 Tip:	Files in a directory can be selecteb by clicking the upper-right corner or lower-left corner of the square corresponding to the directory.

2.2 File Table

File Table shows a list of target source files.

For each file, the following informations are shown:

Index of the file(File ID)

Path of the file

Length of the file in token(LEN)

Count of code clones included in the file(CLN)

On the above of the list, a "common" path of the source files is shown.
The common path is a path of the root directory of the files in the list.

You can narrow down the list, by right-click menu.

Select files by click, CTRL + click, or SHIFT + click -> [Fit Scope to Selected Files] or [Fit Scope to Files Except for Selected Ones]

Alternatively, [Select Files That Have Clones Between Them] or [Selected Files Under] ? [Fit Scope to Selected Files] or [Fit Scope to Files Except for Selected Ones]

The status of narrowing-down of files can be canceled by menu [Pop Scope]

<col class="field-name" />
<col class="field-body" />

 Tip:	In order to narrow down the file list with more complex selection
(for example, keep files under two directories, or keep unselected files),
use check boxes at the files in File Table. Refer the manual for operations about these check boxes.

Source File Search

When the File Table has focus (the focus is shown by colored frame),
you can search in File List by putting file name or path in Search box.
You can also select a file having a specific File ID by putting "#number" (file ID) in Search box,

Looking up File Name in Scatter Plot (Scatter Plot -> File Table)

When you click on Scatter Plot, the corresponding two files on vertical axis and horizontal axis will get into selected state.
These files will be highlighted in File Table.
By this operation, you can find out the names of the files.

2.3 Source Text

This view shows text of a source file. Code clones are illustrated as highlighted text.

When you select a file by clicking in File Table, text of the file will be shown in the Source Text.

The area is composed of three views, Map (described in the next sheet), Line Number, and Text.

Code clones are shown as text with gray background.

The highlighting of line number shows code clones, but it also shows origin of the code. A highlight at left side means the code is similar to text of the other file. A highlight at the right side means the code is similar to text within the same file.

Comments and the tokens (of comments or simple getters/setters) removed by a preprocess script are shown in green characters. Reserved words are shown in dark red characters.

Text Search

When Source Text has focus, you can search in text by putting word in Search box.
You can also move to the specific line by putting "#number" (line number) in Search box.

Multiple Text Mode

When two (or more) files are selected in File Table or in Scatter Plot, Source Text will show two of the files.

Figures shown in the map are:

White bar: source file

Gray vertical bars at the left side of the white bar: Clone code fragment enclosed within the file.

Gray vertical bars at the right side of the white bar: Clone code fragment between the file and the other files.

Gray crosswise or U-shaped line: indicates the code fragments belongs to a clone set.

Yellow rounded rectangle: Range of shown text. You can update a Source Text view by dragging on the right side of the rectangle.

<col class="field-name" />
<col class="field-body" />

 Tip:	The number of panes of Source Text view (that is, the maximum number of source files shown in the view at the same time)
can be changed by menu [Preferences]-[GemX Preferences].

Copy to Scrapbook

By right click menu [Copy to Scrapbook] in Source Text, its text is copied to Scrapbook.
The Scrapbook is  not affected by selection change in File Table or Clone-Set Table,
so the Scrapbook is conveninent when you are investigating code clones around a specific code fragment(s).

2.4 Clone-Set Table

Clone-Set Table shows a list of the detected code clones.
A clone set is a set of code fragments, in which any pair of the code fragments is a code clone.
For each clone set, ID (Clone-Set ID) and length are shown.

Scope of Clone-Set Table is linked to scope of File Table.
That is, if some files are removed from File Table by narrowing down,
the enclosed code clones (whose code fragments appear only in these files) will be removed in Clone Set Table.
(The reverse is not true. That is, if some code clones are removed from Clone-Set Table, the related files never be removed automatically.)

To Show Code Fragment of a Clone Set (Clone-Set Table -> Source Text)

Show the Clone-Set Table at the left side, and show the Source Text at the right side, in advance.

Select a clone set by clicking in Clone-Set Table, then pair of code fragments of the clone set will be shown in Source Text.
By clicking the same clone set again, the next pair will be shown.

You can see two code fragments of a clone a clone set at the same time, by right-click menu [Show Next Clone-Pair Code]

Also, you can narrow down clone sets by right-click menu [Fit Scope to Selected Clone Sets].

<col class="field-name" />
<col class="field-body" />

 Tip:	Right-click menu [Show a Code Fragment] is used to show one code fragment of a clone set.

2.5 Saving Detected Code Clone or Scope

File menu has menu items to save scope and file list.

<col class="field-name" />
<col class="field-body" />

Saving scope:	A scope is a state of narrow-downing of files and code clones. Scopes are shown in Scope History at the leftmost view.

Save: from menu [File]-[Open Current Scope As]

Load: from menu [File]-[Open Clone Data]

<col class="field-name" />
<col class="field-body" />

Saving file list:

 	A file list contains paths of source files in File Table.

Save: from menu [File]-[Save File List as]

From menu [File]-[Detect Clones from File List], you can re-detect code clones from the source files that have been beforehand saved as a file list.

<col class="field-name" />
<col class="field-body" />

Re-detection of clones:

 	In order to detect code clones from the source files of current scope with the different detection options, use menu [File]-[Re-Detect Clones].

3. Analyzing Code Clones by Metrics

Metrics of code clones and metrics of files will help you find interesting code clones or source files.
Also, line-based metrics measures the statistics by count of lines.
GemX provides narrow-downing operations with metrics.

File Metrics

File metrics will be shown in File Table, by menu [Metrics]-[Show File Metrics].

<col class="field-name" />
<col class="field-body" />

NBR (neighbor):	Count of files that have a code-clone fragment between the file.

RSA (ratio of similarity between another files):

 	Ratio (percentage) of tokens that are covered by a code clone between the file and one of the other files.
If a file has a RSA value close to 100%, then it is possible that the file was created by copying a file.

RSI (ratio of similarity within the file):

 	Ratio (percentage) of tokens that are covered by a code clone enclosed within the file.
If a file has a RSI value close to 100%, then it is possible that the file contains a series of the similar functions or methods.

CVR (coverage):	Ratio (percentage) of tokens that are covered by any code clone. By definition, max(RSA, RSI) <= CVR <= RSA+RSI

RNR (ratio of non-repeated code):

 	Ratio of non-repeated code. 1 - (ratio of tokens appears in repetition in the text)
If the value is near to zero, the code is repetition of simple statements and/or defenitions.

From menu [Metrics]-[Filter File by Metrics], You can narrow down the file list by the minimum and maximum values of a metric.

<col class="field-name" />
<col class="field-body" />

 Tip:	By default, when you perform narrowing down of file list after showing file metrics, the metrics value will disappear from File Table.
In order to make GemX re-calculate and show file metrics automatically after such narrowing-down,
add check mark to [Calc File Metrics Always] in the dialog shown by menu [Preferences]-[GemX Prererences].

Clone Set Metrics

Clone-set metrics will be shown by menu [Metrics]-[Show Clone-Set Metrics].

<col class="field-name" />
<col class="field-body" />

LEN (length):	Length (in token) of a code fragment of the code clone

POP (population):

 	Count of code fragments of the code clone

NIF:	Count of source files that include one or more code fragments of the code clone.
By definition, NIF <= POP (This metric is imported from Gemini, developed by Yoshiki Higo, Osaka Univ..)

RAD (radius):	Range of the source code fragments of a code clone in the directory hierarchy.
(When all the code fragments of the code clone are located in one source file, the value is 0.)

RNR (ratio of non-repeated tokens):

 	Ratio (percentage) of tokens that are not included in repeated part of a code fragment of the code clone.

TKS (token set size):

 	Size of a set of tokens of a code fragment of the code clone. If a code clone has a extremely small TKS value, then the code fragment is a simple statement, such as a series of declaration of variables.

LOOP, COND, McCabe:

 	LOOP is defined as count of loops in a code fragment, COND is defined as count of conditional branches, and McCabe is defined as the sum of them.
In order to focus attention on complex code, select code clones with the higher values of these metrics.

You can do filtering of code clones from menu [Metrics]-[Filter Clone Set by Metrics].

When clone-set metrics are calculated, each clone in scatter plot will be colored by RNR metric value (by default).

<col class="field-name" />
<col class="field-body" />

 Tip:	Just like file metrics, the clone-set metrics can be automatically re-calculated and shown by menu [Preferences]-[GemX Preferences].

Line-based Metrics

Line-based metrics will be shown by menu [Metrics]-[Show Line-based Metrics].

<col class="field-name" />
<col class="field-body" />

LOC:	Raw line count of the soure file.

SLOC:	Count of lines, in case of excluding lines whithout any valid tokens.
Here, the "tokens" are specific to CCFinderX. (For example, definitions of simple getters/setters
in Java source file will be entirely neglected by CCFinderX.)
Such neglected characters are shown in green color in Source Text view.

CLOC:	Count of lines including at least one token of a code fragment of a code clone.

CVRL:	Ratio of the lines including a token of a code fragment of a code clone. CVRL = CLOC / SLOC.


text:
package com.vikas.sample;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class LonelyInteger {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[] = new int[n];
        int result = 0;
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
            result ^= a[a_i];
        }

        System.out.println(result);
    }
}


text:
package com.duastone.stalactite.entity;

import java.util.Date;

/**
 * @author Quesle
 * Github Quesle
 * Date Feb 23, 2016 11:00:48 PM
 */
public class Mission {

	private String id;
	private String content;
	private String title;
	private String type;
	private String author;
	private String reaper;
	private String status;
	private long createDate;
	private long startDate;
	private long endDate;

    @Override
    public String toString() {
        return "Mission{" +
                "id='" + id + '\'' +
                ", content='" + content + '\'' +
                ", title='" + title + '\'' +
                ", type='" + type + '\'' +
                ", author='" + author + '\'' +
                ", reaper='" + reaper + '\'' +
                ", status='" + status + '\'' +
                ", createDate=" + createDate +
                ", startDate=" + startDate +
                ", endDate=" + endDate +
                '}';
    }

    public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}

    public String getTitle() {
        return title;
    }

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

    public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getReaper() {
		return reaper;
	}
	public void setReaper(String reaper) {
		this.reaper = reaper;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}

    public long getCreateDate() {
        return createDate;
    }

    public void setCreateDate(long createDate) {
        this.createDate = createDate;
    }

    public long getStartDate() {
        return startDate;
    }

    public void setStartDate(long startDate) {
        this.startDate = startDate;
    }

    public long getEndDate() {
        return endDate;
    }

    public void setEndDate(long endDate) {
        this.endDate = endDate;
    }
}


text:
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
 *
 *  (C) 2009 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */

#include "mpiimpl.h"
#include "topo.h"

/* -- Begin Profiling Symbol Block for routine MPI_Dist_graph_neighbors_count */
#if defined(HAVE_PRAGMA_WEAK)
#pragma weak MPI_Dist_graph_neighbors_count = PMPI_Dist_graph_neighbors_count
#elif defined(HAVE_PRAGMA_HP_SEC_DEF)
#pragma _HP_SECONDARY_DEF PMPI_Dist_graph_neighbors_count  MPI_Dist_graph_neighbors_count
#elif defined(HAVE_PRAGMA_CRI_DUP)
#pragma _CRI duplicate MPI_Dist_graph_neighbors_count as PMPI_Dist_graph_neighbors_count
#endif
/* -- End Profiling Symbol Block */

/* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build
   the MPI routines */
#ifndef MPICH_MPI_FROM_PMPI
#undef MPI_Dist_graph_neighbors_count
#define MPI_Dist_graph_neighbors_count PMPI_Dist_graph_neighbors_count
/* any utility functions should go here, usually prefixed with PMPI_LOCAL to
 * correctly handle weak symbols and the profiling interface */

#undef FUNCNAME
#define FUNCNAME MPIR_Dist_graph_neighbors_count_impl
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
int MPIR_Dist_graph_neighbors_count_impl(MPID_Comm *comm_ptr, int *indegree, int *outdegree, int *weighted)
{
    int mpi_errno = MPI_SUCCESS;
    MPIR_Topology *topo_ptr = NULL;

    topo_ptr = MPIR_Topology_get(comm_ptr);
    MPIU_ERR_CHKANDJUMP(!topo_ptr || topo_ptr->kind != MPI_DIST_GRAPH, mpi_errno, MPIR_ERR_RECOVERABLE, "**notdistgraphtopo");
    *indegree = topo_ptr->topo.dist_graph.indegree;
    *outdegree = topo_ptr->topo.dist_graph.outdegree;
    *weighted = topo_ptr->topo.dist_graph.is_weighted;

fn_exit:
    return mpi_errno;
fn_fail:
    goto fn_exit;
}

#endif

#undef FUNCNAME
#define FUNCNAME MPI_Dist_graph_neighbors_count
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
/*@
MPI_Dist_graph_neighbors_count - Provides adjacency information for a distributed graph topology.

Input Parameters:
. comm - communicator with distributed graph topology (handle)

Output Parameters:
+ indegree - number of edges into this process (non-negative integer)
. outdegree - number of edges out of this process (non-negative integer)
- weighted - false if MPI_UNWEIGHTED was supplied during creation, true otherwise (logical)

.N ThreadSafe

.N Fortran

.N Errors
.N MPI_SUCCESS
@*/
int MPI_Dist_graph_neighbors_count(MPI_Comm comm, int *indegree, int *outdegree, int *weighted)
{
    int mpi_errno = MPI_SUCCESS;
    MPID_Comm *comm_ptr = NULL;
    MPID_MPI_STATE_DECL(MPID_STATE_MPI_DIST_GRAPH_NEIGHBORS_COUNT);

    MPIR_ERRTEST_INITIALIZED_ORDIE();

    /* FIXME: Why does this routine require a CS? */
    MPIU_THREAD_CS_ENTER(ALLFUNC,);
    MPID_MPI_FUNC_ENTER(MPID_STATE_MPI_DIST_GRAPH_NEIGHBORS_COUNT);

    /* Validate parameters, especially handles needing to be converted */
#   ifdef HAVE_ERROR_CHECKING
    {
        MPID_BEGIN_ERROR_CHECKS;
        {
            MPIR_ERRTEST_COMM(comm, mpi_errno);
        }
        MPID_END_ERROR_CHECKS;
    }
#   endif

    /* Convert MPI object handles to object pointers */
    MPID_Comm_get_ptr(comm, comm_ptr);

    /* Validate parameters and objects (post conversion) */
#   ifdef HAVE_ERROR_CHECKING
    {
        MPID_BEGIN_ERROR_CHECKS;
        {
            MPID_Comm_valid_ptr(comm_ptr, mpi_errno);
            if (mpi_errno != MPI_SUCCESS) goto fn_fail;

            MPIR_ERRTEST_ARGNULL(indegree, "indegree", mpi_errno);
            MPIR_ERRTEST_ARGNULL(outdegree, "outdegree", mpi_errno);
            MPIR_ERRTEST_ARGNULL(weighted, "weighted", mpi_errno);
        }
        MPID_END_ERROR_CHECKS;
    }
#   endif /* HAVE_ERROR_CHECKING */

    /* ... body of routine ...  */

    mpi_errno = MPIR_Dist_graph_neighbors_count_impl(comm_ptr, indegree, outdegree, weighted);
    if (mpi_errno) MPIU_ERR_POP(mpi_errno);

    /* ... end of body of routine ... */

  fn_exit:
    MPID_MPI_FUNC_EXIT(MPID_STATE_MPI_DIST_GRAPH_NEIGHBORS_COUNT);
    MPIU_THREAD_CS_EXIT(ALLFUNC,);
    return mpi_errno;

  fn_fail:
    /* --BEGIN ERROR HANDLING-- */
#   ifdef HAVE_ERROR_CHECKING
    {
        mpi_errno = MPIR_Err_create_code(
            mpi_errno, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_OTHER,
            "**mpi_dist_graph_neighbors_count", "**mpi_dist_graph_neighbors_count %C %p %p %p",
            comm, indegree, outdegree, weighted);
    }
#   endif
    mpi_errno = MPIR_Err_return_comm(comm_ptr, FCNAME, mpi_errno);
    goto fn_exit;
    /* --END ERROR HANDLING-- */
}


text:
seq=`basename $0`
seqres=$RESULT_DIR/$seq
echo "QA output created by $seq"

here=`pwd`
tmp=/tmp/$$
status=1	# failure is the default!
trap "_cleanup; exit \$status" 0 1 2 3 15

_cleanup()
{
	_cleanup_flakey
	cd /
	rm -f $tmp.*
}

# get standard environment, filters and checks
. ./common/rc
. ./common/filter
. ./common/dmflakey

# 256MB in byte
fssize=$((2**20 * 256))

# remove previous $seqres.full before test
rm -f $seqres.full

# real QA test starts here
_supported_fs $FILESYSTEM_TYPE
_supported_os Linux
_require_scratch_nocheck
_require_dm_target flakey

# initialize scratch device
_scratch_mkfs_sized $fssize >> $seqres.full 2>&1
_require_metadata_journaling $SCRATCH_DEV
_init_flakey

stat_opt='-c  %n - blocks: %b size: %s inode: %i links: %h'

# Rename wraps 'mv' except that 'rename A/ B/'
# would replace B, instead of creating A/B
rename() {
    [ -d $1 ] && [ -d $2 ] && rm -rf $2
    mv $1 $2
}

# Usage: general_stat [--data-only] file1 [--data-only] [file2] ..
# If the --data-only flag precedes a file, then only that file's
# data will be printed.
general_stat() {
    data_only="false"
    while (( "$#" )); do
        case $1 in
            --data-only)
                data_only="true"
                ;;
            *)
                local file="$1"
                echo "-- $file --"
                if [ ! -f "$file" ] && [ ! -d "$file" ]; then
                    echo "Doesn't exist!"
                elif [ "$data_only" = "true" ] && [ -d "$file" ]; then
                    # Directory with --data-only
                    echo "Directory Data"
                    [[ -z "$(ls -A $file)" ]] || ls -1 "$file" | sort
                elif [ "$data_only" = "true" ]; then
                    # File with --data-only
                    echo "File Data"
                    od "$file"
                elif [ -d "$file" ]; then
                    # Directory with metadata and data
                    echo "Directory Metadata"
                    stat "$stat_opt" "$file"
                    echo "Directory Data"
                    [[ -z "$(ls -A $file)" ]] || ls -1 "$file" | sort
                else
                    # File with metadata and data
                    echo "File Metadata"
                    stat "$stat_opt" "$file"
                    echo "File Data"
                    od "$file"
                fi
                data_only="false"
                ;;
        esac
        shift
	done
}

# Open a file with O_DIRECT and write a byte into a range
_dwrite_byte() {
	local pattern="$1"
	local offset="$2"
	local len="$3"
	local file="$4"
	local xfs_io_args="$5"

	$XFS_IO_PROG $xfs_io_args -f -c "pwrite -S $pattern $offset $len" "$file"
}

_mwrite_byte_and_msync() {
	local pattern="$1"
	local offset="$2"
	local len="$3"
	local mmap_len="$4"
	local file="$5"

	$XFS_IO_PROG -f -c "mmap -rw 0 $mmap_len" -c "mwrite -S $pattern $offset $len" "$file" -c "msync -s"
}

check_consistency()
{
	before=$(general_stat "$@")
	_flakey_drop_and_remount
	after=$(general_stat "$@")

	if [ "$before" != "$after" ]; then
		echo -e "Before:\n$before"
		echo -e "After:\n$after"
	fi
}

# Using _scratch_mkfs instead of cleaning up the  working directory,
# adds about 10 seconds of delay in total for the 37 tests.
clean_dir()
{
	rm -rf $(find $SCRATCH_MNT/* | grep -v "lost+found")
	sync
	_unmount_flakey
}

# Test cases

# Success, all done
echo "Silence is golden"
status=0
exit


text:
extern crate fourcc;

fn main() {
    let val = fourcc!(foo); //~ ERROR non-literal in fourcc!
}


text:
import sys

def suggest_by_compound(compounds, reactions, reactions2run, max_reactions, verbose=False):
    """
    Identify a set of reactions that you should add to your model for growth because they contain orphan compounds

    This is a slightly different approach to suggesting by compound.
    We look for "orphan" compounds that only have a few connections to
    other reactions, and then add those to our network to see what
    happens.

    Note: that our notion of two compounds being equal normally
    includes their location (and str(c) includes the location).
    However, we probably have several instances of:

        cpd [e] -> cpd [c]
        and
        cpd [c] -> products

    These should be considered to be the same, and we probably
    don't want to consider external compounds any way

    :param reactions: The reactions dictionary
    :type reactions: dict
    :param compounds: The compounds dictionary
    :type compounds: dict
    :param reactions2run: The set of reactions that we will already run
    :type reactions2run: set
    :param max_reactions: The maximum number of reactions that a compound can be associated with. Avoids, eg. H2O
    :type max_reactions: int
    :param verbose: Print more output
    :type verbose: bool
    :return: A set of proposed reactions that should be added to your model to see if it grows
    :rtype: set

    """

    cpd = {}
    for r in reactions2run:
        for c in reactions[r].all_compounds():
            cpd[str(c)] = cpd.get(str(c), 0) + 1

    ikeep = set()
    ekeep = set()

    external = 0
    internal = 0
    for c in compounds:
        if str(compounds[c]) in cpd and cpd[str(compounds[c])] <= max_reactions:
            if compounds[c].location == 'e':
                external += 1
                ekeep.update(compounds[c].all_reactions())
            else:
                internal += 1
                ikeep.update(compounds[c].all_reactions())

    if verbose:
        sys.stdout.write("{} | {} | {} | {} | {}\n".format(max_reactions, internal, len(ikeep), external, len(ekeep)))

    ikeep = {r for r in ikeep if r in reactions and r not in reactions2run}
    ekeep = {r for r in ekeep if r in reactions and r not in reactions2run}

    return ikeep


text:
#ifndef NETLINK_PKTLOC_H_
#define NETLINK_PKTLOC_H_

#include <netlink/netlink.h>
#include <netlink/cache.h>
#include <netlink/route/tc.h>

#include <linux/tc_ematch/tc_em_cmp.h>

#ifdef __cplusplus
extern "C" {
#endif

struct rtnl_pktloc
{
	char *			name;
	uint8_t			layer;
	uint8_t			shift;
	uint16_t		offset;
	uint16_t		align;
	uint32_t		mask;
	uint32_t		refcnt;

	struct nl_list_head	list;
};

extern int	rtnl_pktloc_lookup(const char *, struct rtnl_pktloc **);
extern struct rtnl_pktloc *rtnl_pktloc_alloc(void);
extern void	rtnl_pktloc_put(struct rtnl_pktloc *);
extern int	rtnl_pktloc_add(struct rtnl_pktloc *);
extern void	rtnl_pktloc_foreach(void (*cb)(struct rtnl_pktloc *, void *),
				    void *);

#ifdef __cplusplus
}
#endif

#endif


text:
use color::{Color, Colorable};
use graphics::character::CharacterCache;
use label::{self, FontSize};
use position::{Depth, HorizontalAlign, Position, Positionable, VerticalAlign};
use ui::{Ui, UiId};

/// Displays some given text centred within a rectangle.
pub struct Label<'a> {
    text: &'a str,
    pos: Position,
    maybe_h_align: Option<HorizontalAlign>,
    maybe_v_align: Option<VerticalAlign>,
    depth: Depth,
    size: FontSize,
    maybe_color: Option<Color>,
}

impl<'a> Label<'a> {

    /// Construct a new Label widget.
    pub fn new(text: &'a str) -> Label<'a> {
        Label {
            text: text,
            pos: Position::default(),
            maybe_h_align: None,
            maybe_v_align: None,
            depth: 0.0,
            size: 24u32,
            maybe_color: None,
        }
    }

    /// Set the font size for the label.
    #[inline]
    pub fn size(self, size: FontSize) -> Label<'a> {
        Label { size: size, ..self }
    }

    /// After building the Label, use this method to set its current state into the given `Ui`. It
    /// will use this state for rendering the next time `ui.draw(graphics)` is called.
    pub fn set<C>(self, ui_id: UiId, ui: &mut Ui<C>)
        where
            C: CharacterCache,
    {
        use elmesque::form::{text, collage};
        use elmesque::text::Text;
        let dim = [label::width(ui, self.size, self.text), self.size as f64];
        let h_align = self.maybe_h_align.unwrap_or(ui.theme.align.horizontal);
        let v_align = self.maybe_v_align.unwrap_or(ui.theme.align.vertical);
        let xy = ui.get_xy(self.pos, dim, h_align, v_align);
        let color = self.maybe_color.unwrap_or(ui.theme.label_color);
        let form = text(Text::from_string(self.text.to_string())
                            .color(color)
                            .height(self.size as f64)).shift(xy[0].floor(), xy[1].floor());
        let element = collage(dim[0] as i32, dim[1] as i32, vec![form]);
        // Store the label's new state in the Ui.
        ui.update_widget(ui_id, ::widget::Kind::Label, xy, self.depth, Some(element));
    }

}

impl<'a> Colorable for Label<'a> {
    fn color(mut self, color: Color) -> Self {
        self.maybe_color = Some(color);
        self
    }
}

impl<'a> Positionable for Label<'a> {
    fn position(mut self, pos: Position) -> Self {
        self.pos = pos;
        self
    }
    #[inline]
    fn horizontal_align(self, h_align: HorizontalAlign) -> Self {
        Label { maybe_h_align: Some(h_align), ..self }
    }
    #[inline]
    fn vertical_align(self, v_align: VerticalAlign) -> Self {
        Label { maybe_v_align: Some(v_align), ..self }
    }
}


text:
package org.snf4j.core;

import java.net.SocketAddress;

import org.snf4j.core.handler.IDatagramHandler;
import org.snf4j.core.logger.ILogger;
import org.snf4j.core.logger.LoggerFactory;
import org.snf4j.core.session.SSLEngineCreateException;

/**
 * The datagram-oriented session that handles DTLS connections.
 *

 * It uses {@link javax.net.ssl.SSLEngine SSLEngine} to handle the Datagram
 * Transport Layer Security protocol.
 *
 * @author SNF4J.ORG
 */
public class DTLSSession extends EngineDatagramSession {

	private final static ILogger LOGGER = LoggerFactory.getLogger(DTLSSession.class);

	/**
	 * Constructs a named DTLS session associated with a handler. It should be used
	 * for sessions that will be associated with a not connected datagram channel.
	 *
	 * @param name          the name for this session, or null if the
	 *                      handler's name should be used for this session's name
	 * @param remoteAddress the address of the remote peer
	 * @param handler       the handler that should be associated with this session
	 * @param clientMode    true if the engine should start its
	 *                      handshaking in "client" mode
	 * @throws SSLEngineCreateException when the SSL engine could not be created
	 * @throws IllegalStateException if no timer was configured. The exception can
	 *                               be ignored by setting the system property
	 *                               {@link org.snf4j.core.Constants#IGNORE_NO_SESSION_TIMER_EXCEPTION
	 *                               IGNORE_NO_SESSION_TIMER_EXCEPTION}
	 */
	public DTLSSession(String name, SocketAddress remoteAddress, IDatagramHandler handler, boolean clientMode) throws SSLEngineCreateException {
		super(name, new InternalSSLEngine(remoteAddress, handler.getConfig(), clientMode), remoteAddress, handler, LOGGER);
	}

	/**
	 * Constructs a DTLS session associated with a handler. It should be used for
	 * sessions that will be associated with a not connected datagram channel.
	 *
	 * @param remoteAddress the address of the remote peer
	 * @param handler       the handler that should be associated with this session
	 * @param clientMode    true if the engine should start its
	 *                      handshaking in "client" mode
	 * @throws SSLEngineCreateException when the SSL engine could not be created
	 * @throws IllegalStateException if no timer was configured. The exception can
	 *                               be ignored by setting the system property
	 *                               {@link org.snf4j.core.Constants#IGNORE_NO_SESSION_TIMER_EXCEPTION
	 *                               IGNORE_NO_SESSION_TIMER_EXCEPTION}
	 */
	public DTLSSession(SocketAddress remoteAddress, IDatagramHandler handler, boolean clientMode) throws SSLEngineCreateException {
		super(new InternalSSLEngine(remoteAddress, handler.getConfig(), clientMode), remoteAddress, handler, LOGGER);
	}

	/**
	 * Constructs a named DTLS session associated with a handler. It should be used
	 * for sessions that will be associated with a connected datagram channel.
	 *
	 * @param name       the name for this session, or null if the
	 *                   handler's name should be used for this session's name
	 * @param handler    the handler that should be associated with this session
	 * @param clientMode true if the engine should start its
	 *                   handshaking in "client" mode
	 * @throws SSLEngineCreateException when the SSL engine could not be created
	 * @throws IllegalStateException if no timer was configured. The exception can
	 *                               be ignored by setting the system property
	 *                               {@link org.snf4j.core.Constants#IGNORE_NO_SESSION_TIMER_EXCEPTION
	 *                               IGNORE_NO_SESSION_TIMER_EXCEPTION}
	 */
	public DTLSSession(String name, IDatagramHandler handler, boolean clientMode) throws SSLEngineCreateException {
		super(name, new InternalSSLEngine(null, handler.getConfig(), clientMode), handler, LOGGER);
	}

	/**
	 * Constructs a DTLS session associated with a handler. It should be used for
	 * sessions that will be associated with a connected datagram channel.
	 *
	 * @param handler    the handler that should be associated with this session
	 * @param clientMode true if the engine should start its
	 *                   handshaking in "client" mode
	 * @throws SSLEngineCreateException when the SSL engine could not be created
	 * @throws IllegalStateException if no timer was configured. The exception can
	 *                               be ignored by setting the system property
	 *                               {@link org.snf4j.core.Constants#IGNORE_NO_SESSION_TIMER_EXCEPTION
	 *                               IGNORE_NO_SESSION_TIMER_EXCEPTION}
	 */
	public DTLSSession(IDatagramHandler handler, boolean clientMode) throws SSLEngineCreateException {
		super(new InternalSSLEngine(null, handler.getConfig(), clientMode), handler, LOGGER);
	}

	/**
	 * Returns the {@link javax.net.ssl.SSLSession SSLSession} in use in the
	 * {@link javax.net.ssl.SSLEngine SSLEngine} driving this session.
	 *
	 * @return the {@code SSLSession}
	 */
	@Override
	public javax.net.ssl.SSLSession getEngineSession() {
		return (javax.net.ssl.SSLSession) super.getEngineSession();
	}
}


text:
package com.wallace.demo.app.utils

import java.util.Properties

import com.jcraft.jsch.{ChannelSftp, JSch}
import com.wallace.demo.app.common.Using
import org.apache.commons.net.ftp.{FTP, FTPClient}

import scala.util.{Failure, Success, Try}

/**
  * Created by wallace on 2018/7/5.
  */
case class FtpMetaData(hostIp: String, port: Int, userName: String, passWord: String, timeOut: Int = 6000, ftpType: String = "sftp")

class FtpUtils(ftpMetadata: FtpMetaData) extends Using {

  /** 规避多线程并发不断开问题 */
  private val sftpLocal: ThreadLocal[FtpUtils] = new ThreadLocal[FtpUtils]()

  /**
    * 连接SFTP服务器
    *
    * @return boolean
    */
  def createSftpChannel(): Option[ChannelSftp] = {
    Try(new JSch().getSession(ftpMetadata.userName, ftpMetadata.hostIp, ftpMetadata.port)).flatMap {
      session =>
        if (ftpMetadata.passWord != null) session.setPassword(ftpMetadata.passWord)
        val config: Properties = new Properties()
        config.put("StrictHostKeyChecking", "no")
        session.setConfig(config)
        session.setTimeout(ftpMetadata.timeOut)
        log.debug("sftp session connected")
        log.debug("opening channel")
        Try {
          session.connect()
          val channel = session.openChannel(ftpMetadata.ftpType).asInstanceOf[ChannelSftp]
          channel.connect()
          channel
        }
    }
  } match {
    case Success(ch) => Some(ch)
    case Failure(e) =>
      log.error("Failed to login sftp server", e)
      None
  }

  def createFtpClient(): Option[FTPClient] = {
    Try(new FTPClient()).flatMap {
      client =>
        Try {
          client.connect(ftpMetadata.hostIp, ftpMetadata.port)
          client.setControlEncoding("UTF-8")
          client.login(ftpMetadata.userName, ftpMetadata.passWord)
        }.flatMap {
          _ =>
            Try {
              client.setFileTransferMode(FTP.BINARY_FILE_TYPE)
              //client.listFiles().foreach(file => (file.getName, file.isFile, file.getTimestamp))
              client
            }
        }
    } match {
      case Success(client) => Some(client)
      case Failure(e) =>
        log.error("Failed to create FTP client", e)
        None
    }
  }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>Ilwis-Objects: Class Members - Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Ilwis-Objects
    1.0

GIS and Remote Sensing framework for data access and processing

Main Page

Classes

Files

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

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Enumerations

a

b

c

d

e

f

g

h

i

k

l

m

n

o

p

r

s

t

u

v

x

y

z

~

 All Classes Functions Enumerations Pages

- r -

range()
: Ilwis::ColorDomain
, Ilwis::CoordinateDomain
, Ilwis::Domain
, Ilwis::NumericItem
, Ilwis::TextDomain
, Ilwis::ItemDomain< D >
, Ilwis::DataDefinition
, Ilwis::NumericDomain
, Ilwis::NumericItem

RasterCoverage()
: Ilwis::RasterCoverage

raw()
: Ilwis::DomainItem
, Ilwis::IndexedIdentifier
, Ilwis::IndexedIdentifierRange

record()
: Ilwis::AttributeTable
, Ilwis::DatabaseTable
, Ilwis::FlatTable
, Ilwis::Table

recordCount()
: Ilwis::BaseTable
, Ilwis::Table

registerObject()
: Ilwis::MasterCatalog

remove()
: Ilwis::NumericItemRange
, Ilwis::ItemRange
, Ilwis::ColorPalette
, Ilwis::IndexedIdentifierRange
, Ilwis::NamedIdentifierRange

removeItem()
: Ilwis::ItemDomain< D >

removeItems()
: Ilwis::MasterCatalog

renumberer()
: Ilwis::DomainMerger

resolve()
: Ilwis::Catalog

Resource()
: Ilwis::Resource

<address class="footer">
Generated on Fri Mar 28 2014 13:51:05 for Ilwis-Objects by

 1.8.3.1
</address>


text:
import transaction
import unittest
import yaml

from datetime import datetime, timedelta
from pyramid import testing

from budget.models import (DBSession,
                           Base,
                           Openshift3Node,
                           Openshift3Pod,
                           Openshift3Project,
                           Openshift3User)

now = datetime.now()
today = datetime(now.year, now.month, now.day, 0, 0, 0)
yesterday = today - timedelta(days=1)

class TestInsert(unittest.TestCase):
    def setUp(self):
        self.config = testing.setUp()
        from sqlalchemy import create_engine
        engine = create_engine('sqlite://')
        DBSession.configure(bind=engine)
        Base.metadata.drop_all(engine)
        Base.metadata.create_all(engine)

    def tearDown(self):
        DBSession.remove()
        testing.tearDown()

    def runTest(self):
        from budget.scripts.openshift_v3_stats import update
        yml = yaml.load('''
apiVersion: v1
items:
- apiVersion: v1
  kind: Node
  metadata:
    creationTimestamp: 2001-01-01T12:00:00Z
    labels:
      color: red
      type: compute
    name: test
    uid: 12345678-1234-5678-1234-567812345678
  spec:
    externalID: i-123456789abcdef
    providerID: test:///test/i-123456789abcdef
  status:
    addresses:
    - address: 10.0.0.5
      type: InternalIP
    - address: 10.0.0.6
      type: ExternalIP
    allocatable:
      cpu: "2"
      memory: 2048Ki
      pods: "20"
    capacity:
      cpu: "2"
      memory: 2048Ki
      pods: "20"
    conditions:
    - lastHeartbeatTime: 2001-01-01T12:01:00Z
      lastTransitionTime: 2001-01-01T12:01:00Z
      message: kubelet is posting ready status
      reason: KubeletReady
      status: "True"
      type: Ready''')
        yaml_info = {'collection_date' : datetime.now(),
                     'cluster_id' : 'test'}
        lst = update(DBSession, Openshift3Node, yml, yaml_info)
        self.assertEqual(lst, ['12345678-1234-5678-1234-567812345678'])
        result = DBSession.query(Openshift3Node.uid).all()
        self.assertEqual(result, [(u'12345678-1234-5678-1234-567812345678',)])

class TestUpdate(unittest.TestCase):
    def setUp(self):
        self.config = testing.setUp()
        from sqlalchemy import create_engine
        engine = create_engine('sqlite://')
        DBSession.configure(bind=engine)
        Base.metadata.drop_all(engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            node = Openshift3Node(
                    collection_date = yesterday,
                    create_date = yesterday,
                    end_date = None,
                    uid = '12345678-1234-5678-1234-567812345678',
                    status = '''
status:
  addresses:
  - address: 10.0.0.1
    type: InternalIP
  - address: 10.0.0.2
    type: ExternalIP
  allocatable:
    cpu: "1"
    memory: 1024Ki
    pods: "10"
  capacity:
    cpu: "1"
    memory: 1024Ki
    pods: "10"
  conditions:
  - lastHeartbeatTime: 2001-01-01T12:01:00Z
    lastTransitionTime: 2001-01-01T12:01:00Z
    message: kubelet is posting ready status
    reason: KubeletReady
    status: "True"
    type: Ready
''',
                    meta = '''
metadata:
  creationTimestamp: 2001-01-01T12:00:00Z
  labels:
    color: red
    type: compute
  name: test
  uid: 12345678-1234-5678-1234-567812345678
                    ''',
                    cluster_id = 'test'
                    )
            DBSession.add(node)

    def tearDown(self):
        DBSession.remove()
        testing.tearDown()

    def runTest(self):
        from budget.scripts.openshift_v3_stats import update
        yml = yaml.load('''
apiVersion: v1
items:
- apiVersion: v1
  kind: Node
  metadata:
    creationTimestamp: 2001-01-01T12:00:00Z
    labels:
      color: red
      type: compute
    name: test
    uid: 12345678-1234-5678-1234-567812345678
  spec:
    externalID: i-123456789abcdef
    providerID: test:///test/i-123456789abcdef
  status:
    addresses:
    - address: 10.0.0.5
      type: InternalIP
    - address: 10.0.0.6
      type: ExternalIP
    allocatable:
      cpu: "2"
      memory: 2048Ki
      pods: "20"
    capacity:
      cpu: "2"
      memory: 2048Ki
      pods: "20"
    conditions:
    - lastHeartbeatTime: 2001-01-01T12:01:00Z
      lastTransitionTime: 2001-01-01T12:01:00Z
      message: kubelet is posting ready status
      reason: KubeletReady
      status: "True"
      type: Ready''')
        yaml_info = {'collection_date' : datetime.now(),
                     'cluster_id' : 'test'}
        lst = update(DBSession, Openshift3Node, yml, yaml_info)
        self.assertEqual(lst, ['12345678-1234-5678-1234-567812345678'])
        result = DBSession.query(Openshift3Node.uid).all()
        self.assertEqual(result, [(u'12345678-1234-5678-1234-567812345678',)])

class TestExpire(unittest.TestCase):
    def setUp(self):
        self.config = testing.setUp()
        from sqlalchemy import create_engine
        engine = create_engine('sqlite://')
        DBSession.configure(bind=engine)
        Base.metadata.drop_all(engine)
        Base.metadata.create_all(engine)
        with transaction.manager:
            node1 = Openshift3Node(
                    collection_date = yesterday,
                    create_date = yesterday,
                    end_date = None,
                    uid = '12345678-1234-5678-1234-567812345678',
                    status = '''
status:
  addresses:
  - address: 10.0.0.1
    type: InternalIP
  - address: 10.0.0.2
    type: ExternalIP
  allocatable:
    cpu: "1"
    memory: 1024Ki
    pods: "10"
  capacity:
    cpu: "1"
    memory: 1024Ki
    pods: "10"
  conditions:
  - lastHeartbeatTime: 2001-01-01T12:01:00Z
    lastTransitionTime: 2001-01-01T12:01:00Z
    message: kubelet is posting ready status
    reason: KubeletReady
    status: "True"
    type: Ready
''',
                    meta = '''
metadata:
  creationTimestamp: 2001-01-01T12:00:00Z
  labels:
    color: red
    type: compute
  name: test
  uid: 12345678-1234-5678-1234-567812345678
                    ''',
                    cluster_id = 'test'
                    )
            node2 = Openshift3Node(
                    collection_date = yesterday,
                    create_date = yesterday,
                    end_date = None,
                    uid = '23456789-2345-6789-2345-678923456789',
                    status = '''
status:
  addresses:
  - address: 10.0.0.3
    type: InternalIP
  - address: 10.0.0.4
    type: ExternalIP
  allocatable:
    cpu: "1"
    memory: 1024Ki
    pods: "10"
  capacity:
    cpu: "1"
    memory: 1024Ki
    pods: "10"
  conditions:
  - lastHeartbeatTime: 2001-01-01T12:01:00Z
    lastTransitionTime: 2001-01-01T12:01:00Z
    message: kubelet is posting ready status
    reason: KubeletReady
    status: "True"
    type: Ready
''',
                    meta = '''
metadata:
  creationTimestamp: 2001-01-01T12:00:00Z
  labels:
    color: red
    type: compute
  name: test
  uid: 23456789-2345-6789-2345-678923456789
                    ''',
                    cluster_id = 'test'
                    )

            DBSession.add(node1)
            DBSession.add(node2)

    def tearDown(self):
        DBSession.remove()
        testing.tearDown()

    def runTest(self):
        from budget.scripts.openshift_v3_stats import expire
        expire(DBSession, Openshift3Node, ['12345678-1234-5678-1234-567812345678'])
        result = DBSession.query(Openshift3Node.uid, Openshift3Node.end_date).all()
        self.assertEqual(result[0], ('12345678-1234-5678-1234-567812345678',None))
        self.assertEqual(result[1][0], '23456789-2345-6789-2345-678923456789')
        self.assertLessEqual((datetime.now()-result[1][1]).total_seconds(), 2)

class TestParseFilename(unittest.TestCase):
    def runTest(self):
        from budget.scripts.openshift_v3_stats import parse_filename
        result = parse_filename('pods-test-master-abcde-2001-01-01.yaml')
        self.assertEqual(result['type'], 'pods')
        self.assertEqual(result['cluster_id'], 'test')
        self.assertEqual(result['collection_date'], '2001-01-01')


text:
"""Setup some common test helper things."""
import functools
import logging
from unittest.mock import patch

import pytest
import requests_mock as _requests_mock

from homeassistant import util, bootstrap
from homeassistant.util import location
from homeassistant.components import mqtt

from .common import async_test_home_assistant
from .test_util.aiohttp import mock_aiohttp_client

logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

def test_real(func):
    """Force a function to require a keyword _test_real to be passed in."""
    @functools.wraps(func)
    def guard_func(*args, **kwargs):
        real = kwargs.pop('_test_real', None)

        if not real:
            raise Exception('Forgot to mock or pass "_test_real=True" to %s',
                            func.__name__)

        return func(*args, **kwargs)

    return guard_func

# Guard a few functions that would make network connections
location.detect_location_info = test_real(location.detect_location_info)
location.elevation = test_real(location.elevation)
util.get_local_ip = lambda: '127.0.0.1'

@pytest.fixture
def hass(loop):
    """Fixture to provide a test instance of HASS."""
    hass = loop.run_until_complete(async_test_home_assistant(loop))

    yield hass

    loop.run_until_complete(hass.async_stop())

@pytest.fixture
def requests_mock():
    """Fixture to provide a requests mocker."""
    with _requests_mock.mock() as m:
        yield m

@pytest.fixture
def aioclient_mock():
    """Fixture to mock aioclient calls."""
    with mock_aiohttp_client() as mock_session:
        yield mock_session

@pytest.fixture
def mqtt_mock(loop, hass):
    """Fixture to mock MQTT."""
    with patch('homeassistant.components.mqtt.MQTT') as mock_mqtt:
        loop.run_until_complete(bootstrap.async_setup_component(
            hass, mqtt.DOMAIN, {
                mqtt.DOMAIN: {
                    mqtt.CONF_BROKER: 'mock-broker',
                }
            }))
        client = mock_mqtt()
        client.reset_mock()
        return client


text:
var env    = require('../../test-environment'),
    helper = require('./test-helper');

describe('JSON Schema - parse byte params', function() {
  'use strict';

  it('should parse a valid byte param',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte',
        multipleOf: 5,
        minimum: 40,
        exclusiveMinimum: true,
        maximum: 45,
        exclusiveMaximum: false
      };

      var express = helper.integrationTest(schema, 45, done);

      express.post('/api/test', env.spy(function(req, res, next) {
        expect(req.header('Test')).to.equal(45);
      }));
    }
  );

  it('should parse an optional, unspecified byte param',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte'
      };

      var express = helper.integrationTest(schema, undefined, done);

      express.post('/api/test', env.spy(function(req, res, next) {
        expect(req.header('Test')).to.be.undefined;
      }));
    }
  );

  it('should parse the default value if no value is specified',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte',
        default: 255
      };

      var express = helper.integrationTest(schema, undefined, done);

      express.post('/api/test', env.spy(function(req, res, next) {
        expect(req.header('Test')).to.equal(255);
      }));
    }
  );

  it('should parse the default value if the specified value is blank',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte',
        default: 1
      };

      var express = helper.integrationTest(schema, '', done);

      express.post('/api/test', env.spy(function(req, res, next) {
        expect(req.header('Test')).to.equal(1);
      }));
    }
  );

  it('should throw an error if the value is blank',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte'
      };

      var express = helper.integrationTest(schema, '', done);

      express.use('/api/test', env.spy(function(err, req, res, next) {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.status).to.equal(400);
        expect(err.message).to.contain('"" is not a properly-formatted whole number');
      }));
    }
  );

  it('should throw an error if the value is not a valid byte',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte'
      };

      var express = helper.integrationTest(schema, 'hello world', done);

      express.use('/api/test', env.spy(function(err, req, res, next) {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.status).to.equal(400);
        expect(err.message).to.contain('"hello world" is not a properly-formatted whole number');
      }));
    }
  );

  it('should throw an error if the value fails schema validation',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte',
        multipleOf: 3
      };

      var express = helper.integrationTest(schema, '14', done);

      express.use('/api/test', env.spy(function(err, req, res, next) {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.status).to.equal(400);
        expect(err.message).to.contain('Value 14 is not a multiple of 3');
      }));
    }
  );

  it('should throw an error if the value is above the byte maximum',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte'
      };

      var express = helper.integrationTest(schema, '256', done);

      express.use('/api/test', env.spy(function(err, req, res, next) {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.status).to.equal(400);
        expect(err.message).to.contain('"256" is not a valid byte. Must be between 0 and 255');
      }));
    }
  );

  it('should throw an error if the value is below the byte minimum',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte'
      };

      var express = helper.integrationTest(schema, '-5', done);

      express.use('/api/test', env.spy(function(err, req, res, next) {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.status).to.equal(400);
        expect(err.message).to.contain('"-5" is not a valid byte. Must be between 0 and 255');
      }));
    }
  );

  it('should throw an error if required and not specified',
    function(done) {
      var schema = {
        type: 'string',
        format: 'byte',
        required: true
      };

      var express = helper.integrationTest(schema, undefined, done);

      express.use('/api/test', env.spy(function(err, req, res, next) {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.status).to.equal(400);
        expect(err.message).to.contain('Missing required header parameter "Test"');
      }));
    }
  );
});


text:
package com.pilaf.cs.common.api;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@RequiredArgsConstructor
public class GameState implements Cacheable {

	/**
	 *
	 */
	private static final long serialVersionUID = -30442168360010916L;

	@NonNull
	private String gameUUID;

	private String description;

}


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "IO#binmode" do
  it "does not raise any errors on closed stream" do
    lambda { IOSpecs.closed_file.binmode }.should_not raise_error()
  end
end


text:
#include "gm.h"
#if SK_SUPPORT_GPU
#include "GrTest.h"
#include "effects/GrRRectEffect.h"
#include "SkDevice.h"
#include "SkRRect.h"

namespace skiagm {

///////////////////////////////////////////////////////////////////////////////

class BigRRectAAEffectGM : public GM {
public:
    BigRRectAAEffectGM() {
        this->setBGColor(sk_tool_utils::color_to_565(0xFFDDDDDD));
        this->setUpRRects();
    }

protected:
    SkString onShortName() override {
        return SkString("big_rrect_aa_effect");
    }

    SkISize onISize() override { return SkISize::Make(kImageWidth, kImageHeight); }

    void onDraw(SkCanvas* canvas) override {
        GrRenderTarget* rt = canvas->internal_private_accessTopLayerRenderTarget();
        GrContext* context = rt ? rt->getContext() : nullptr;
        if (!context) {
            skiagm::GM::DrawGpuOnlyMessage(canvas);
            return;
        }

        SkPaint paint;

#ifdef SK_DEBUG
        static const SkRect kMaxRRectBound = SkRect::MakeWH(SkIntToScalar(kMaxSize),
                                                            SkIntToScalar(kMaxSize));
        static const SkRect kMaxImageBound = SkRect::MakeWH(SkIntToScalar(kImageWidth),
                                                            SkIntToScalar(kImageHeight));
#endif

        int y = kPad;
        int x = kPad;
        static const GrPrimitiveEdgeType kEdgeTypes[] = {
            kFillAA_GrProcessorEdgeType,
            kInverseFillAA_GrProcessorEdgeType,
        };
        for (size_t et = 0; et < SK_ARRAY_COUNT(kEdgeTypes); ++et) {
            GrPrimitiveEdgeType edgeType = kEdgeTypes[et];
            for (int curRRect = 0; curRRect < fRRects.count(); ++curRRect) {
#ifdef SK_DEBUG
                SkASSERT(kMaxRRectBound.contains(fRRects[curRRect].getBounds()));
                SkRect imageSpaceBounds = fRRects[curRRect].getBounds();
                imageSpaceBounds.offset(SkIntToScalar(x), SkIntToScalar(y));
                SkASSERT(kMaxImageBound.contains(imageSpaceBounds));
#endif
                canvas->save();
                    canvas->translate(SkIntToScalar(x), SkIntToScalar(y));
                    GrTestTarget tt;
                    context->getTestTarget(&tt);
                    if (nullptr == tt.target()) {
                        SkDEBUGFAIL("Couldn't get Gr test target.");
                        return;
                    }
                    GrPipelineBuilder pipelineBuilder;

                    SkRRect rrect = fRRects[curRRect];
                    rrect.offset(SkIntToScalar(x), SkIntToScalar(y));
                    SkAutoTUnref<GrFragmentProcessor> fp(GrRRectEffect::Create(edgeType, rrect));
                    SkASSERT(fp);
                    if (fp) {
                        pipelineBuilder.addCoverageFragmentProcessor(fp);
                        pipelineBuilder.setRenderTarget(rt);

                        SkRect bounds = SkRect::MakeWH(SkIntToScalar(kMaxSize),
                                                       SkIntToScalar(kMaxSize));
                        bounds.outset(2.f, 2.f);
                        bounds.offset(SkIntToScalar(x), SkIntToScalar(y));

                        tt.target()->drawNonAARect(pipelineBuilder,
                                                   0xff000000,
                                                   SkMatrix::I(),
                                                   bounds);
                    }
                canvas->restore();
                x = x + kDrawOffset;
                if (x + kMaxSize> kImageWidth) {
                    x = kPad;
                    y += kDrawOffset;
                }
            }
        }
    }

    void setUpRRects() {
        SkScalar maxSize = SkIntToScalar(kMaxSize);
        fRRects.push()->setRect(SkRect::MakeWH(maxSize, maxSize));
        fRRects.push()->setOval(SkRect::MakeWH(maxSize, maxSize));
        fRRects.push()->setOval(SkRect::MakeWH(maxSize - 1.f, maxSize - 10.f));
        fRRects.push()->setRectXY(SkRect::MakeWH(maxSize - 1.f, maxSize - 10.f),
                                  maxSize/2.f - 10.f, maxSize/2.f - 10.f);
        fRRects.push()->setRectXY(SkRect::MakeWH(maxSize - 1.f, maxSize - 10),
                                  maxSize/2.f - 10.f, maxSize/2.f - 20.f);
    }

private:
    static const int kPad = 5;
    static const int kMaxSize = 300;
    static const int kDrawOffset = kMaxSize + kPad;

    static const int kImageWidth = 4 * kDrawOffset + kPad;
    static const int kImageHeight = 3 * kDrawOffset + kPad;

    SkTDArray<SkRRect> fRRects;
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

DEF_GM( return new BigRRectAAEffectGM (); )

}
#endif