text:
package com.netflix.spinnaker.orca.clouddriver.tasks.manifest;

import static java.util.Collections.emptyList;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import com.netflix.spinnaker.kork.core.RetrySupport;
import com.netflix.spinnaker.orca.ExecutionStatus;
import com.netflix.spinnaker.orca.TaskResult;
import com.netflix.spinnaker.orca.clouddriver.KatoService;
import com.netflix.spinnaker.orca.clouddriver.OortService;
import com.netflix.spinnaker.orca.clouddriver.model.TaskId;
import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware;
import com.netflix.spinnaker.orca.pipeline.expressions.PipelineExpressionEvaluator;
import com.netflix.spinnaker.orca.pipeline.model.Stage;
import com.netflix.spinnaker.orca.pipeline.util.ArtifactUtils;
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import retrofit.client.Response;

@Component
@Slf4j
@RequiredArgsConstructor
public class ManifestEvaluator implements CloudProviderAware {
  private static final ThreadLocal<Yaml> yamlParser =
      ThreadLocal.withInitial(() -> new Yaml(new SafeConstructor()));

  private final ArtifactUtils artifactUtils;
  private final OortService oort;
  private final ObjectMapper objectMapper;
  private final ContextParameterProcessor contextParameterProcessor;
  private final KatoService kato;

  private final RetrySupport retrySupport = new RetrySupport();

  @RequiredArgsConstructor
  @Getter
  public static class Result {
    private final List<Map<Object, Object>> manifests;
    private final List<Artifact> requiredArtifacts;
    private final List<Artifact> optionalArtifacts;
  }

  public Result evaluate(Stage stage, ManifestContext context) {
    Iterable<Object> rawManifests;
    List<Map<Object, Object>> manifests = Collections.emptyList();
    if (ManifestContext.Source.Artifact.equals(context.getSource())) {
      Artifact manifestArtifact =
          artifactUtils.getBoundArtifactForStage(
              stage, context.getManifestArtifactId(), context.getManifestArtifact());

      if (manifestArtifact == null) {
        throw new IllegalArgumentException("No manifest artifact was specified.");
      }

      // Once the legacy artifacts feature is removed, all trigger expected artifacts will be
      // required to define an account up front.
      if (context.getManifestArtifactAccount() != null) {
        manifestArtifact.setArtifactAccount(context.getManifestArtifactAccount());
      }

      if (manifestArtifact.getArtifactAccount() == null) {
        throw new IllegalArgumentException("No manifest artifact account was specified.");
      }

      log.info("Using {} as the manifest", manifestArtifact);

      rawManifests =
          retrySupport.retry(
              () -> {
                Response manifestText = oort.fetchArtifact(manifestArtifact);
                try (InputStream body = manifestText.getBody().in()) {
                  return yamlParser.get().loadAll(body);
                } catch (Exception e) {
                  log.warn("Failure fetching/parsing manifests from {}", manifestArtifact, e);
                  // forces a retry
                  throw new IllegalStateException(e);
                }
              },
              10,
              200,
              true); // retry 10x, starting at .2s intervals);

      List<Object> unevaluatedManifests =
          StreamSupport.stream(rawManifests.spliterator(), false)
              .map(
                  m -> {
                    try {
                      return Collections.singletonList(objectMapper.convertValue(m, Map.class));
                    } catch (Exception e) {
                      return objectMapper.convertValue(
                          m, new TypeReference<List<Map<Object, Object>>>() {});
                    }
                  })
              .flatMap(Collection::stream)
              .collect(Collectors.toList());

      if (!unevaluatedManifests.isEmpty()) {
        Map<String, Object> manifestWrapper = new HashMap<>();
        manifestWrapper.put("manifests", unevaluatedManifests);

        if (!context.isSkipExpressionEvaluation()) {
          manifestWrapper =
              contextParameterProcessor.process(
                  manifestWrapper, contextParameterProcessor.buildExecutionContext(stage), true);

          if (manifestWrapper.containsKey(PipelineExpressionEvaluator.SUMMARY)) {
            throw new IllegalStateException(
                "Failure evaluating manifest expressions: "
                    + manifestWrapper.get(PipelineExpressionEvaluator.SUMMARY));
          }
        }
        manifests = (List<Map<Object, Object>>) manifestWrapper.get("manifests");
      }
    } else {
      manifests = context.getManifests();
    }

    List<Artifact> requiredArtifacts = new ArrayList<>();
    for (String id : Optional.ofNullable(context.getRequiredArtifactIds()).orElse(emptyList())) {
      Artifact requiredArtifact = artifactUtils.getBoundArtifactForId(stage, id);
      if (requiredArtifact == null) {
        throw new IllegalStateException(
            "No artifact with id '" + id + "' could be found in the pipeline context.");
      }

      requiredArtifacts.add(requiredArtifact);
    }

    // resolve SpEL expressions in artifacts defined inline in the stage
    for (ManifestContext.BindArtifact artifact :
        Optional.ofNullable(context.getRequiredArtifacts()).orElse(emptyList())) {
      Artifact requiredArtifact =
          artifactUtils.getBoundArtifactForStage(
              stage, artifact.getExpectedArtifactId(), artifact.getArtifact());

      if (requiredArtifact == null) {
        throw new IllegalStateException(
            "No artifact with id '"
                + artifact.getExpectedArtifactId()
                + "' could be found in the pipeline context.");
      }

      requiredArtifacts.add(requiredArtifact);
    }

    log.info("Artifacts {} are bound to the manifest", requiredArtifacts);

    return new Result(manifests, requiredArtifacts, artifactUtils.getArtifacts(stage));
  }

  public TaskResult buildTaskResult(String taskName, Stage stage, Map<String, Object> task) {
    Map<String, Map> operation =
        new ImmutableMap.Builder<String, Map>().put(taskName, task).build();

    TaskId taskId =
        kato.requestOperations(getCloudProvider(stage), Collections.singletonList(operation))
            .toBlocking()
            .first();

    Map<String, Object> outputs =
        new ImmutableMap.Builder<String, Object>()
            .put("kato.result.expected", true)
            .put("kato.last.task.id", taskId)
            .put("deploy.account.name", getCredentials(stage))
            .build();

    return TaskResult.builder(ExecutionStatus.SUCCEEDED).context(outputs).build();
  }
}


text:
using System;
using System.Composition;

namespace Microsoft.CodeAnalysis.Organizing.Organizers
{
    [MetadataAttribute]
    [AttributeUsage(AttributeTargets.Class)]
    internal class ExportSyntaxNodeOrganizerAttribute : ExportAttribute
    {
        public ExportSyntaxNodeOrganizerAttribute(string languageName) :
            base(typeof(ISyntaxOrganizer))
        {
            this.Language = languageName;
        }

        public string Language { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
<head></head>
<body>
    <script src="a.js" nobundle="nobundle"></script>
    <script src="b.js"></script>
    <script src="c.js"></script>
    <script src="d.js" nobundle="nobundle"></script>
    <script src="e.js"></script>
</body>
</html>


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

router.get("/data", (req, res)=> {
    var domains = ["http://localhost:63342", "http://localhost"];

    if (domains.indexOf(req.headers.origin) != -1) {
        res.header("Access-Control-Allow-Origin", req.headers.origin);
    }
    res.send("HelloWorld");
});

module.exports = router;


text:
package org.tuxdevelop.test.configuration;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.tuxdevelop.spring.batch.lightmin.batch.annotation.EnableLightminBatchJpa;

@Configuration
@EnableLightminBatchJpa
@EnableAutoConfiguration
@Import(value = {ITPersistenceConfiguration.class, ITJobConfiguration.class})
public class ITJpaConfiguration {
}


text:
package eu.chargetime.ocpp.model.securityext.types;

import eu.chargetime.ocpp.model.securityext.SignedUpdateFirmwareConfirmation;

/**
 * UpdateFirmwareStatusEnumType is used by {@link SignedUpdateFirmwareConfirmation}
 */
public enum UpdateFirmwareStatusEnumType {
  /**
   * Accepted this firmware update request. This does not mean the firmware update is successful, the Charge Point will
   * now start the firmware update process.
   */
  Accepted,

  /**
   * Firmware update request rejected.
   */
  Rejected,

  /**
   * Accepted this firmware update request, but in doing this has canceled an ongoing firmware update.
   */
  AcceptedCanceled,

  /**
   * The certificate is invalid.
   */
  InvalidCertificate,

  /**
   * Failure end state. The Firmware Signing certificate has been revoked.
   */
  RevokedCertificate
}


text:
{% extends 'base.html' %}
{% from 'tantalus_paginator.html' import paginator_buttons with context %}

{% block container %}

Snapshots

        Name
        Date created
        Yearcode

      {% for snapshot in pagination.items %}

            {{ snapshot.name }}

          {{ snapshot.time_created | format_date }}
          {{ snapshot.yearcode }}

      {% else %}

∅

      {% endfor %}

  {{ paginator_buttons(pagination) }}

  <form action="{{ url_for('.create') }}" method="post" class="col-lg-12">
    <input id="_csrf_token" name="_csrf_token" type="hidden" value="{{ csrf_token() }}"/>

        <fieldset>
            <legend>Create Snapshot</legend>

              Snapshot creation is an involved process and can take a few minutes to complete in some scenarios.
              While the snapshot creation is running it is recommended that you do not perform any actions.
              A snapshot is not a backup and should not be treated as such. You cannot restore from a snapshot.
              POS-Sales are not part of a snapshot.

              Name

                <input type="text" class="form-control" id="name" name="name" placeholder="Name">

                    <button type="submit" class="btn btn-sm btn-primary">Create</button>

        </fieldset>

  </form>
{% endblock %}


text:
from flask import Flask
from flask_restful import Resource, Api
from app.resources.messages import MessageList, MessageSend, MessageById
from app.resources.health import Health
from structlog import get_logger
from app.data_model import database
from app import settings

logger = get_logger()

app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = settings.SECURE_MESSAGING_DATABASE_URL
database.db.init_app(app)

with app.app_context():
    database.db.create_all()
    database.db.session.commit()

api.add_resource(Health, '/health')
api.add_resource(MessageList, '/messages', )
api.add_resource(MessageSend, '/message/send')
api.add_resource(MessageById, '/message/<int:id>')


text:
NS_ASSUME_NONNULL_BEGIN

@implementation MMTabDragView

- (instancetype)initWithFrame:(NSRect)frame {
	if ((self = [super initWithFrame:frame])) {
		_alpha = 1.0;
	}
	return self;
}

- (void)drawRect:(NSRect)rect {
	//1.0 fade means show the primary image
	//0.0 fade means show the secondary image
	CGFloat primaryAlpha = _alpha + 0.001f, alternateAlpha = 1.001f - _alpha;
	NSRect srcRect;
	srcRect.origin = NSZeroPoint;
	srcRect.size = [_image size];

	[_image drawInRect:[self bounds] fromRect:srcRect operation:NSCompositeSourceOver fraction:primaryAlpha respectFlipped:YES hints:nil];
	srcRect.size = [_alternateImage size];
	[_alternateImage drawInRect:[self bounds] fromRect:srcRect operation:NSCompositeSourceOver fraction:alternateAlpha respectFlipped:YES hints:nil];
}

@end

NS_ASSUME_NONNULL_END


text:
.settings {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  position: relative;
}

.settings .settings-window {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 33rem;
  width: 100%;
}

.settings .settings-window .settings-content {
  width: 100%;
  padding: 20px;
  margin: auto;
  box-sizing: border-box;
}

.close-button {
  composes: circle-button from "../../utils.css";
  fill: #000;
  width: var(--circlebtn-size);
  height: var(--circlebtn-size);
}

.close-container {
  position: fixed;
  right: 20px;
  top: 20px;
}

.fp-close-button {
  composes: unbutton from "../../utils.css";
  height: var(--icon-size);
  color: #fff;
  margin: var(--bar-padding) var(--side-margin) !important;
  text-transform: uppercase;
}

.fp-close-container {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #000;
  min-height: min-content;
  z-index: 1;
}

.fp-close-container::before {
  content: "";
  height: 1px;
  transform-origin: 0 0;
  transform: scaleY(0.5);
  position: absolute;
  top: 0;
  left: var(--side-margin);
  right: var(--side-margin);
  background: white;
}

.keyshortcut {
  composes: keyshortcut from "../../utils.css";
}

.button-on,
.button-off {
  text-transform: uppercase;
  display: block;
  width: 100%;
  margin: 1.2rem 0 0 !important;
  font-size: 1.1rem;
  letter-spacing: 0.2rem;
}

.button-on {
  composes: button-on from "../../utils.css";
}

.button-off {
  composes: button-off from "../../utils.css";
}


text:
namespace formulate.app.Controllers
{

    // Namespaces.
    using core.Extensions;
    using Helpers;
    using Models.Requests;
    using Persistence;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    using Umbraco.Core;
    using Umbraco.Core.Logging;
    using Umbraco.Web;
    using Umbraco.Web.Editors;
    using Umbraco.Web.Mvc;
    using Umbraco.Web.WebApi.Filters;
    using Validations;
    using CoreConstants = Umbraco.Core.Constants;
    using ValidationConstants = formulate.app.Constants.Trees.Validations;

    /// <summary>
    /// Controller for Formulate validations.
    /// </summary>
    [PluginController("formulate")]
    [UmbracoApplicationAuthorize("formulate")]
    public class ValidationsController : UmbracoAuthorizedJsonController
    {

        #region Constants

        private const string UnhandledError = @"An unhandled error occurred. Refer to the error log.";
        private const string PersistValidationError = @"An error occurred while attempting to persist a Formulate validation.";
        private const string GetValidationInfoError = @"An error occurred while attempting to get the validation info for a Formulate validation.";
        private const string DeleteValidationError = @"An error occurred while attempting to delete the Formulate validation.";
        private const string GetKindsError = @"An error occurred while attempting to get the validation kinds.";
        private const string MoveValidationError = @"An error occurred while attempting to move a Formulate validation.";

        #endregion

        #region Properties

        private IValidationPersistence Persistence { get; set; }
        private IEntityPersistence Entities { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Primary constructor.
        /// </summary>
        /// <param name="entityPersistence">
        /// The entity Persistence.
        /// </param>
        /// <param name="validationPersistence">
        /// The validation Persistence.
        /// </param>
        public ValidationsController(IEntityPersistence entityPersistence, IValidationPersistence validationPersistence)
        {
            Persistence = validationPersistence;
            Entities = entityPersistence;
        }

        #endregion

        #region Web Methods

        /// <summary>
        /// Creates a validation.
        /// </summary>
        /// <param name="request">
        /// The request to create the validation.
        /// </param>
        /// <returns>
        /// An object indicating success or failure, along with some
        /// accompanying data.
        /// </returns>
        [HttpPost]
        public object PersistValidation(PersistValidationRequest request)
        {

            // Variables.
            var result = default(object);
            var rootId = CoreConstants.System.Root.ToInvariantString();
            var validationsRootId = GuidHelper.GetGuid(ValidationConstants.Id);
            var parentId = GuidHelper.GetGuid(request.ParentId);
            var kindId = GuidHelper.GetGuid(request.KindId);

            // Catch all errors.
            try
            {

                // Parse or create the validation ID.
                var validationId = string.IsNullOrWhiteSpace(request.ValidationId)
                    ? Guid.NewGuid()
                    : GuidHelper.GetGuid(request.ValidationId);

                // Get the ID path.
                var parent = parentId == Guid.Empty ? null : Entities.Retrieve(parentId);
                var path = parent == null
                    ? new[] { validationsRootId, validationId }
                    : parent.Path.Concat(new[] { validationId }).ToArray();

                // Create validation.
                var validation = new Validation()
                {
                    KindId = kindId,
                    Id = validationId,
                    Path = path,
                    Name = request.ValidationName,
                    Alias = request.ValidationAlias,
                    Data = JsonHelper.Serialize(request.Data)
                };

                // Persist validation.
                Persistence.Persist(validation);

                // Variables.
                var fullPath = new[] { rootId }
                    .Concat(path.Select(x => GuidHelper.GetString(x)))
                    .ToArray();

                // Success.
                result = new
                {
                    Success = true,
                    Id = GuidHelper.GetString(validationId),
                    Path = fullPath
                };

            }
            catch(Exception ex)
            {

                // Error.
                Logger.Error<ValidationsController>(ex, PersistValidationError);
                result = new
                {
                    Success = false,
                    Reason = UnhandledError
                };

            }

            // Return result.
            return result;

        }

        /// <summary>
        /// Returns info about the validation with the specified ID.
        /// </summary>
        /// <param name="request">
        /// The request to get the validation info.
        /// </param>
        /// <returns>
        /// An object indicating success or failure, along with some
        /// accompanying data.
        /// </returns>
        [HttpGet]
        public object GetValidationInfo(
            [FromUri] GetValidationInfoRequest request)
        {

            // Variables.
            var result = default(object);
            var rootId = CoreConstants.System.Root.ToInvariantString();

            // Catch all errors.
            try
            {

                // Variables.
                var id = GuidHelper.GetGuid(request.ValidationId);
                var validation = Persistence.Retrieve(id);
                var fullPath = new[] { rootId }
                    .Concat(validation.Path.Select(x => GuidHelper.GetString(x)))
                    .ToArray();
                var kinds = ValidationHelper.GetAllValidationKinds();
                var directive = kinds.Where(x => x.Id == validation.KindId)
                    .Select(x => x.Directive).FirstOrDefault();

                // Set result.
                result = new
                {
                    Success = true,
                    ValidationId = GuidHelper.GetString(validation.Id),
                    KindId = GuidHelper.GetString(validation.KindId),
                    Path = fullPath,
                    Alias = validation.Alias,
                    Name = validation.Name,
                    Directive = directive,
                    Data = JsonHelper.Deserialize<object>(validation.Data)
                };

            }
            catch (Exception ex)
            {

                // Error.
                Logger.Error<ValidationsController>(ex, GetValidationInfoError);
                result = new
                {
                    Success = false,
                    Reason = UnhandledError
                };

            }

            // Return result.
            return result;

        }

        /// <summary>
        /// Returns info about the validations with the specified IDs.
        /// </summary>
        /// <param name="request">
        /// The request to get the info on the validations.
        /// </param>
        /// <returns>
        /// An object indicating success or failure, along with some
        /// accompanying data.
        /// </returns>
        [HttpGet]
        public object GetValidationsInfo(
            [FromUri] GetValidationsInfoRequest request)
        {

            // Variables.
            var result = default(object);
            var rootId = CoreConstants.System.Root.ToInvariantString();
            var validations = new List<object>();

            // Catch all errors.
            try
            {

                // Variables.
                var ids = request.ValidationIds
                    .MakeSafe()
                    .Select(x => GuidHelper.GetGuid(x)).ToList();
                var kinds = ValidationHelper.GetAllValidationKinds();

                // Get information about each validation.
                foreach (var id in ids)
                {

                    // Get validation.
                    var validation = Persistence.Retrieve(id);
                    if (validation == null)
                    {
                        continue;
                    }

                    // Get path to validation.
                    var partialPath = validation.Path
                        .Select(x => GuidHelper.GetString(x));
                    var fullPath = new[] { rootId }
                        .Concat(partialPath).ToArray();

                    // Get directive.
                    var directive = kinds.Where(x => x.Id == validation.KindId)
                        .Select(x => x.Directive).FirstOrDefault();

                    // Store validation info.
                    validations.Add(new
                    {
                        ValidationId = GuidHelper.GetString(validation.Id),
                        KindId = GuidHelper.GetString(validation.KindId),
                        Path = fullPath,
                        Alias = validation.Alias,
                        Name = validation.Name,
                        Directive = directive,
                        Data = JsonHelper.Deserialize<object>(validation.Data)
                    });

                }

                // Set result.
                result = new
                {
                    Success = true,
                    Validations = validations.ToArray()
                };

            }
            catch (Exception ex)
            {

                // Error.
                Logger.Error<ValidationsController>(ex, GetValidationInfoError);
                result = new
                {
                    Success = false,
                    Reason = UnhandledError
                };

            }

            // Return result.
            return result;

        }

        /// <summary>
        /// Deletes the validation with the specified ID.
        /// </summary>
        /// <param name="request">
        /// The request to delete the validation.
        /// </param>
        /// <returns>
        /// An object indicating success or failure, along with some
        /// accompanying data.
        /// </returns>
        [HttpPost()]
        public object DeleteValidation(DeleteValidationRequest request)
        {

            // Variables.
            var result = default(object);

            // Catch all errors.
            try
            {

                // Variables.
                var validationId = GuidHelper.GetGuid(request.ValidationId);

                // Delete the validation.
                Persistence.Delete(validationId);

                // Success.
                result = new
                {
                    Success = true
                };

            }
            catch (Exception ex)
            {

                // Error.
                Logger.Error<ValidationsController>(ex, DeleteValidationError);
                result = new
                {
                    Success = false,
                    Reason = UnhandledError
                };

            }

            // Return the result.
            return result;

        }

        /// <summary>
        /// Returns the validation kinds.
        /// </summary>
        /// <returns>
        /// An object indicating success or failure, along with information
        /// about validation kinds.
        /// </returns>
        [HttpGet]
        public object GetValidationKinds()
        {

            // Variables.
            var result = default(object);

            // Catch all errors.
            try
            {

                // Variables.
                var kinds = ValidationHelper.GetAllValidationKinds();

                // Return results.
                result = new
                {
                    Success = true,
                    Kinds = kinds.Select(x => new
                    {
                        Id = GuidHelper.GetString(x.Id),
                        Name = x.Name,
                        Directive = x.Directive
                    }).ToArray()
                };

            }
            catch (Exception ex)
            {

                // Error.
                Logger.Error<ValidationsController>(ex, GetKindsError);
                result = new
                {
                    Success = false,
                    Reason = UnhandledError
                };

            }

            // Return result.
            return result;

        }

        /// <summary>
        /// Moves validation to a new parent.
        /// </summary>
        /// <param name="request">
        /// The request to move the validation.
        /// </param>
        /// <returns>
        /// An object indicating success or failure, along with information
        /// about the validation.
        /// </returns>
        [HttpPost]
        public object MoveValidation(MoveValidationRequest request)
        {

            // Variables.
            var result = default(object);
            var rootId = CoreConstants.System.Root.ToInvariantString();
            var parentId = GuidHelper.GetGuid(request.NewParentId);

            // Catch all errors.
            try
            {

                // Parse the validation ID.
                var validationId = GuidHelper.GetGuid(request.ValidationId);

                // Get the ID path.
                var path = Entities.Retrieve(parentId).Path
                    .Concat(new[] { validationId }).ToArray();

                // Get validation and update path.
                var validation = Persistence.Retrieve(validationId);
                validation.Path = path;

                // Persist validation.
                Persistence.Persist(validation);

                // Variables.
                var fullPath = new[] { rootId }
                    .Concat(path.Select(x => GuidHelper.GetString(x)))
                    .ToArray();

                // Success.
                result = new
                {
                    Success = true,
                    Id = GuidHelper.GetString(validationId),
                    Path = fullPath
                };

            }
            catch (Exception ex)
            {

                // Error.
                Logger.Error<ValidationsController>(ex, MoveValidationError);
                result = new
                {
                    Success = false,
                    Reason = UnhandledError
                };

            }

            // Return result.
            return result;

        }

        #endregion

    }

}


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

<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>twilio.rest.studio.v1.flow.execution.execution_step package — twilio-python 7.15.3 documentation</title>
<link href="../../../_static/alabaster.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>

<link href="../../../genindex.html" rel="index" title="Index"/>
<link href="../../../search.html" rel="search" title="Search"/>
<link href="twilio.rest.studio.v2.html" rel="next" title="twilio.rest.studio.v2 package"/>
<link href="twilio.rest.studio.v1.flow.execution.html" rel="prev" title="twilio.rest.studio.v1.flow.execution package"/>
<link href="../../../_static/custom.css" rel="stylesheet" type="text/css"/>
<meta content="width=device-width, initial-scale=0.9, maximum-scale=0.9" name="viewport"/>

twilio.rest.studio.v1.flow.execution.execution_step package¶

Submodules¶

twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context module¶

This code was generated by
/ _    _  _|   _  _

(_)/(_)(_|/| |(/_  v1.0.0
/       /

class twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext(version, flow_sid, execution_sid, step_sid)[source]¶

Bases: twilio.base.instance_context.InstanceContext

fetch()[source]¶

Fetch the ExecutionStepContextInstance

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

Returns:	The fetched ExecutionStepContextInstance

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance

class twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance(version, payload, flow_sid, execution_sid, step_sid)[source]¶

Bases: twilio.base.instance_resource.InstanceResource

account_sid¶

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

Returns:	The SID of the Account that created the resource

Return type:	unicode

context¶

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

Returns:	The current state of the flow

Return type:	dict

execution_sid¶

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

Returns:	The SID of the Execution

Return type:	unicode

fetch()[source]¶

Fetch the ExecutionStepContextInstance

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

Returns:	The fetched ExecutionStepContextInstance

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance

flow_sid¶

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

Returns:	The SID of the Flow

Return type:	unicode

step_sid¶

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

Returns:	Step SID

Return type:	unicode

url¶

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

Returns:	The absolute URL of the resource

Return type:	unicode

class twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList(version, flow_sid, execution_sid, step_sid)[source]¶

Bases: twilio.base.list_resource.ListResource

get()[source]¶

Constructs a ExecutionStepContextContext

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

Returns:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextContext

class twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextPage(version, response, solution)[source]¶

Bases: twilio.base.page.Page

get_instance(payload)[source]¶

Build an instance of ExecutionStepContextInstance

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

Parameters:	payload (dict) – Payload response from the API

Returns:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextInstance

Module contents¶

This code was generated by
/ _    _  _|   _  _

(_)/(_)(_|/| |(/_  v1.0.0
/       /

class twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext(version, flow_sid, execution_sid, sid)[source]¶

Bases: twilio.base.instance_context.InstanceContext

fetch()[source]¶

Fetch the ExecutionStepInstance

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

Returns:	The fetched ExecutionStepInstance

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance

step_context¶

Access the step_context

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

Returns:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList

class twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance(version, payload, flow_sid, execution_sid, sid=None)[source]¶

Bases: twilio.base.instance_resource.InstanceResource

account_sid¶

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

Returns:	The SID of the Account that created the resource

Return type:	unicode

context¶

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

Returns:	The current state of the flow

Return type:	dict

date_created¶

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

Returns:	The ISO 8601 date and time in GMT when the resource was created

Return type:	datetime

date_updated¶

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

Returns:	The ISO 8601 date and time in GMT when the resource was last updated

Return type:	datetime

execution_sid¶

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

Returns:	The SID of the Execution

Return type:	unicode

fetch()[source]¶

Fetch the ExecutionStepInstance

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

Returns:	The fetched ExecutionStepInstance

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance

flow_sid¶

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

Returns:	The SID of the Flow

Return type:	unicode

links¶

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

Returns:	The URLs of related resources

Return type:	unicode

name¶

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

Returns:	The event that caused the Flow to transition to the Step

Return type:	unicode

sid¶

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

Returns:	The unique string that identifies the resource

Return type:	unicode

step_context¶

Access the step_context

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

Returns:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context.ExecutionStepContextList

transitioned_from¶

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

Returns:	The Widget that preceded the Widget for the Step

Return type:	unicode

transitioned_to¶

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

Returns:	The Widget that will follow the Widget for the Step

Return type:	unicode

url¶

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

Returns:	The absolute URL of the resource

Return type:	unicode

class twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepList(version, flow_sid, execution_sid)[source]¶

Bases: twilio.base.list_resource.ListResource

get(sid)[source]¶

Constructs a ExecutionStepContext

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

Parameters:	sid – The unique string that identifies the resource

Returns:	twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext

get_page(target_url)[source]¶

Retrieve a specific page of ExecutionStepInstance records from the API.
Request is executed immediately

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

Parameters:	target_url (str) – API-generated URL for the requested results page

Returns:	Page of ExecutionStepInstance

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage

list(limit=None, page_size=None)[source]¶

Lists ExecutionStepInstance records from the API as a list.
Unlike stream(), this operation is eager and will load limit records into
memory before returning.

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

Parameters:

limit (int) – Upper limit for the number of records to return. list() guarantees
never to return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance]

page(page_token=<object object>, page_number=<object object>, page_size=<object object>)[source]¶

Retrieve a single page of ExecutionStepInstance records from the API.
Request is executed immediately

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

Parameters:

page_token (str) – PageToken provided by the API

page_number (int) – Page Number, this value is simply for client state

page_size (int) – Number of records to return, defaults to 50

Returns:
Page of ExecutionStepInstance

Return type:
twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage

stream(limit=None, page_size=None)[source]¶

Streams ExecutionStepInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.

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

Parameters:

limit (int) – Upper limit for the number of records to return. stream()
guarantees to never return more than limit.  Default is no limit

page_size (int) – Number of records to fetch per request, when not set will use
the default value of 50 records.  If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)

Returns:
Generator that will yield up to limit results

Return type:
list[twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance]

class twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepPage(version, response, solution)[source]¶

Bases: twilio.base.page.Page

get_instance(payload)[source]¶

Build an instance of ExecutionStepInstance

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

Parameters:	payload (dict) – Payload response from the API

Returns:	twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance

Return type:	twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance

About twilio-python

    A Python module for communicating with the Twilio API and generating TwiML.

Useful Links

Twilio's Python Helper Library Docs

twilio @ PyPI

twilio-python @ GitHub

Table of Contents

twilio.rest.studio.v1.flow.execution.execution_step package

Submodules

twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context module

Module contents

Related Topics

Documentation overview

twilio

twilio package

twilio.rest package

twilio.rest.studio package

twilio.rest.studio.v1 package

twilio.rest.studio.v1.flow package

twilio.rest.studio.v1.flow.execution package

Previous: twilio.rest.studio.v1.flow.execution package

Next: twilio.rest.studio.v2 package

This Page

Show Source

Quick search

<form action="../../../search.html" class="search" method="get">
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>
</form>

      ©2019, Twilio.

      |
      Powered by Sphinx 1.8.0
      & Alabaster 0.7.12

      |
      Page source


text:
import khmer
from khmer.khmer_args import optimal_size
import os
import argparse
import screed
import threading
import multiprocessing

def restricted_float(x):
	x = float(x)
	if x < 0.0 or x >= 1.0:
		raise argparse.ArgumentTypeError("%r not in range [0.0, 1.0)" % (x,))
	return x

def main():
	parser = argparse.ArgumentParser(
		description="This script will create node graph for a given k-mer size and query file (can be used as input to QueryDNADatabase.py)",
		formatter_class=argparse.ArgumentDefaultsHelpFormatter)
	parser.add_argument('-fp', '--fp_rate', type=restricted_float, help="False positive rate.", default=0.0001)
	parser.add_argument('-i', '--intersect_nodegraph',
						help="Location of Node Graph. Will only insert query k-mers in bloom filter if they appear anywhere in the training"
							 " database. Note that the Jaccard estimates will now be "
							 "J(query intersect union_i training_i, training_i) instead of J(query, training_i), "
							 "but will use significantly less space (unfortunately will also disable threading).")
	parser.add_argument('-k', '--k_size', type=int, help="K-mer size", default=21)
	parser.add_argument('-t', '--threads', type=int, help="Number of threads to use", default=multiprocessing.cpu_count())
	parser.add_argument('in_file', help="Input file: FASTQ/A file (can be gzipped).")
	parser.add_argument('out_dir', help='Output directory')

	# Parse and check args
	args = parser.parse_args()
	query_file = os.path.abspath(args.in_file)
	ksize = args.k_size
	num_threads = args.threads
	node_graph_out = os.path.join(os.path.abspath(args.out_dir), os.path.basename(query_file) + ".NodeGraph.K" + str(ksize))
	if args.intersect_nodegraph is not None:
		intersect_nodegraph_file = args.intersect_nodegraph
	else:
		intersect_nodegraph_file = None
	intersect_nodegraph = None
	if intersect_nodegraph_file is not None:
		if not os.path.exists(intersect_nodegraph_file):
			raise Exception("Intersection nodegraph does not exist. Please re-run MakeDNADatabase.py with the -i flag.")
		try:
			intersect_nodegraph = khmer.load_nodegraph(intersect_nodegraph_file)
			if intersect_nodegraph.ksize() != ksize:
				raise Exception("Given intersect nodegraph %s has K-mer size %d while the database K-mer size is %d"
								% (intersect_nodegraph_file, intersect_nodegraph.ksize(), ksize))
		except:
			raise Exception("Could not load given intersect nodegraph %s" % intersect_nodegraph_file)
	fprate = args.fp_rate
	hll = khmer.HLLCounter(0.01, ksize)
	hll.consume_seqfile(query_file)
	full_kmer_count_estimate = hll.estimate_cardinality()
	res = optimal_size(full_kmer_count_estimate, fp_rate=fprate)
	if intersect_nodegraph is None:  # If no intersect list was given, just populate the bloom filter
		sample_kmers = khmer.Nodegraph(ksize, res.htable_size, res.num_htables)
		#sample_kmers.consume_seqfile(query_file)
		rparser = khmer.ReadParser(query_file)
		threads = []
		for _ in range(num_threads):
			cur_thrd = threading.Thread(target=sample_kmers.consume_seqfile_with_reads_parser, args=(rparser,))
			threads.append(cur_thrd)
			cur_thrd.start()
		for thread in threads:
			thread.join()
	else:  # Otherwise, only put a k-mer in the bloom filter if it's in the intersect list
		# (WARNING: this will cause the Jaccard index to be calculated in terms of J(query\intersect hash_list, training)
		#  instead of J(query, training)
		# (TODO: fix this after khmer is updated)
		#intersect_nodegraph_kmer_count = intersect_nodegraph.n_unique_kmers()  # Doesnt work due to khmer bug
		intersect_nodegraph_kmer_count = intersect_nodegraph.n_occupied()  # Doesnt work due to khmer bug
		if intersect_nodegraph_kmer_count < full_kmer_count_estimate:  # At max, we have as many k-mers as in the union of the training database (But makes this always return 0)
			res = optimal_size(intersect_nodegraph_kmer_count, fp_rate=fprate)
			sample_kmers = khmer.Nodegraph(ksize, res.htable_size, res.num_htables)
		else:
			sample_kmers = khmer.Nodegraph(ksize, res.htable_size, res.num_htables)
		for record in screed.open(query_file):
			seq = record.sequence
			for i in range(len(seq) - ksize + 1):
				kmer = seq[i:i + ksize]
				if intersect_nodegraph.get(kmer) > 0:
					sample_kmers.add(kmer)
	# Save the sample_kmers
	sample_kmers.save(node_graph_out)

if __name__ == "__main__":
	main()


text:
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_MULTI_ALGORITHMS_NUM_INTERIOR_RINGS_HPP
#define BOOST_GEOMETRY_MULTI_ALGORITHMS_NUM_INTERIOR_RINGS_HPP

#include <cstddef>

#include <boost/range.hpp>

#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>

#include <boost/geometry/algorithms/num_interior_rings.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename MultiPolygon>
struct num_interior_rings<MultiPolygon, multi_polygon_tag>
{
    static inline std::size_t apply(MultiPolygon const& multi_polygon)
    {
        std::size_t n = 0;
        for (typename boost::range_iterator<MultiPolygon const>::type
            it = boost::begin(multi_polygon);
            it != boost::end(multi_polygon);
            ++it)
        {
            n += geometry::num_interior_rings(*it);
        }
        return n;
    }

};

} // namespace dispatch
#endif

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_MULTI_ALGORITHMS_NUM_INTERIOR_RINGS_HPP


text:
/*global unescape, module, define, window, global*/

/*
 UriTemplate Copyright (c) 2012-2013 Franz Antesberger. All Rights Reserved.
 Available via the MIT license.
*/

(function (exportCallback) {
    "use strict";

    var UriTemplateError = (function () {

        function UriTemplateError(options) {
            this.options = options;
        }

        UriTemplateError.prototype.toString = function () {
            if (JSON && JSON.stringify) {
                return JSON.stringify(this.options);
            }
            else {
                return this.options;
            }
        };

        return UriTemplateError;
    }());

    var objectHelper = (function () {
        function isArray(value) {
            return Object.prototype.toString.apply(value) === '[object Array]';
        }

        function isString(value) {
            return Object.prototype.toString.apply(value) === '[object String]';
        }

        function isNumber(value) {
            return Object.prototype.toString.apply(value) === '[object Number]';
        }

        function isBoolean(value) {
            return Object.prototype.toString.apply(value) === '[object Boolean]';
        }

        function join(arr, separator) {
            var
                result = '',
                first = true,
                index;
            for (index = 0; index < arr.length; index += 1) {
                if (first) {
                    first = false;
                }
                else {
                    result += separator;
                }
                result += arr[index];
            }
            return result;
        }

        function map(arr, mapper) {
            var
                result = [],
                index = 0;
            for (; index < arr.length; index += 1) {
                result.push(mapper(arr[index]));
            }
            return result;
        }

        function filter(arr, predicate) {
            var
                result = [],
                index = 0;
            for (; index < arr.length; index += 1) {
                if (predicate(arr[index])) {
                    result.push(arr[index]);
                }
            }
            return result;
        }

        function deepFreezeUsingObjectFreeze(object) {
            if (typeof object !== "object" || object === null) {
                return object;
            }
            Object.freeze(object);
            var property, propertyName;
            for (propertyName in object) {
                if (object.hasOwnProperty(propertyName)) {
                    property = object[propertyName];
                    // be aware, arrays are 'object', too
                    if (typeof property === "object") {
                        deepFreeze(property);
                    }
                }
            }
            return object;
        }

        function deepFreeze(object) {
            if (typeof Object.freeze === 'function') {
                return deepFreezeUsingObjectFreeze(object);
            }
            return object;
        }

        return {
            isArray: isArray,
            isString: isString,
            isNumber: isNumber,
            isBoolean: isBoolean,
            join: join,
            map: map,
            filter: filter,
            deepFreeze: deepFreeze
        };
    }());

    var charHelper = (function () {

        function isAlpha(chr) {
            return (chr >= 'a' && chr <= 'z') || ((chr >= 'A' && chr <= 'Z'));
        }

        function isDigit(chr) {
            return chr >= '0' && chr <= '9';
        }

        function isHexDigit(chr) {
            return isDigit(chr) || (chr >= 'a' && chr <= 'f') || (chr >= 'A' && chr <= 'F');
        }

        return {
            isAlpha: isAlpha,
            isDigit: isDigit,
            isHexDigit: isHexDigit
        };
    }());

    var pctEncoder = (function () {
        var utf8 = {
            encode: function (chr) {
                // see http://ecmanaut.blogspot.de/2006/07/encoding-decoding-utf8-in-javascript.html
                return unescape(encodeURIComponent(chr));
            },
            numBytes: function (firstCharCode) {
                if (firstCharCode <= 0x7F) {
                    return 1;
                }
                else if (0xC2 <= firstCharCode && firstCharCode <= 0xDF) {
                    return 2;
                }
                else if (0xE0 <= firstCharCode && firstCharCode <= 0xEF) {
                    return 3;
                }
                else if (0xF0 <= firstCharCode && firstCharCode <= 0xF4) {
                    return 4;
                }
                // no valid first octet
                return 0;
            },
            isValidFollowingCharCode: function (charCode) {
                return 0x80 <= charCode && charCode <= 0xBF;
            }
        };

        /**
         * encodes a character, if needed or not.
         * @param chr
         * @return pct-encoded character
         */
        function encodeCharacter(chr) {
            var
                result = '',
                octets = utf8.encode(chr),
                octet,
                index;
            for (index = 0; index < octets.length; index += 1) {
                octet = octets.charCodeAt(index);
                result += '%' + (octet < 0x10 ? '0' : '') + octet.toString(16).toUpperCase();
            }
            return result;
        }

        /**
         * Returns, whether the given text at start is in the form 'percent hex-digit hex-digit', like '%3F'
         * @param text
         * @param start
         * @return {boolean|*|*}
         */
        function isPercentDigitDigit(text, start) {
            return text.charAt(start) === '%' && charHelper.isHexDigit(text.charAt(start + 1)) && charHelper.isHexDigit(text.charAt(start + 2));
        }

        /**
         * Parses a hex number from start with length 2.
         * @param text a string
         * @param start the start index of the 2-digit hex number
         * @return {Number}
         */
        function parseHex2(text, start) {
            return parseInt(text.substr(start, 2), 16);
        }

        /**
         * Returns whether or not the given char sequence is a correctly pct-encoded sequence.
         * @param chr
         * @return {boolean}
         */
        function isPctEncoded(chr) {
            if (!isPercentDigitDigit(chr, 0)) {
                return false;
            }
            var firstCharCode = parseHex2(chr, 1);
            var numBytes = utf8.numBytes(firstCharCode);
            if (numBytes === 0) {
                return false;
            }
            for (var byteNumber = 1; byteNumber < numBytes; byteNumber += 1) {
                if (!isPercentDigitDigit(chr, 3 * byteNumber) || !utf8.isValidFollowingCharCode(parseHex2(chr, 3 * byteNumber + 1))) {
                    return false;
                }
            }
            return true;
        }

        /**
         * Reads as much as needed from the text, e.g. '%20' or '%C3%B6'. It does not decode!
         * @param text
         * @param startIndex
         * @return the character or pct-string of the text at startIndex
         */
        function pctCharAt(text, startIndex) {
            var chr = text.charAt(startIndex);
            if (!isPercentDigitDigit(text, startIndex)) {
                return chr;
            }
            var utf8CharCode = parseHex2(text, startIndex + 1);
            var numBytes = utf8.numBytes(utf8CharCode);
            if (numBytes === 0) {
                return chr;
            }
            for (var byteNumber = 1; byteNumber < numBytes; byteNumber += 1) {
                if (!isPercentDigitDigit(text, startIndex + 3 * byteNumber) || !utf8.isValidFollowingCharCode(parseHex2(text, startIndex + 3 * byteNumber + 1))) {
                    return chr;
                }
            }
            return text.substr(startIndex, 3 * numBytes);
        }

        return {
            encodeCharacter: encodeCharacter,
            isPctEncoded: isPctEncoded,
            pctCharAt: pctCharAt
        };
    }());

    var rfcCharHelper = (function () {

        /**
         * Returns if an character is an varchar character according 2.3 of rfc 6570
         * @param chr
         * @return (Boolean)
         */
        function isVarchar(chr) {
            return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '_' || pctEncoder.isPctEncoded(chr);
        }

        /**
         * Returns if chr is an unreserved character according 1.5 of rfc 6570
         * @param chr
         * @return {Boolean}
         */
        function isUnreserved(chr) {
            return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '-' || chr === '.' || chr === '_' || chr === '~';
        }

        /**
         * Returns if chr is an reserved character according 1.5 of rfc 6570
         * or the percent character mentioned in 3.2.1.
         * @param chr
         * @return {Boolean}
         */
        function isReserved(chr) {
            return chr === ':' || chr === '/' || chr === '?' || chr === '#' || chr === '[' || chr === ']' || chr === '@' || chr === '!' || chr === '$' || chr === '&' || chr === '(' ||
                chr === ')' || chr === '*' || chr === '+' || chr === ',' || chr === ';' || chr === '=' || chr === "'";
        }

        return {
            isVarchar: isVarchar,
            isUnreserved: isUnreserved,
            isReserved: isReserved
        };

    }());

    /**
     * encoding of rfc 6570
     */
    var encodingHelper = (function () {

        function encode(text, passReserved) {
            var
                result = '',
                index,
                chr = '';
            if (typeof text === "number" || typeof text === "boolean") {
                text = text.toString();
            }
            for (index = 0; index < text.length; index += chr.length) {
                chr = text.charAt(index);
                result += rfcCharHelper.isUnreserved(chr) || (passReserved && rfcCharHelper.isReserved(chr)) ? chr : pctEncoder.encodeCharacter(chr);
            }
            return result;
        }

        function encodePassReserved(text) {
            return encode(text, true);
        }

        function encodeLiteralCharacter(literal, index) {
            var chr = pctEncoder.pctCharAt(literal, index);
            if (chr.length > 1) {
                return chr;
            }
            else {
                return rfcCharHelper.isReserved(chr) || rfcCharHelper.isUnreserved(chr) ? chr : pctEncoder.encodeCharacter(chr);
            }
        }

        function encodeLiteral(literal) {
            var
                result = '',
                index,
                chr = '';
            for (index = 0; index < literal.length; index += chr.length) {
                chr = pctEncoder.pctCharAt(literal, index);
                if (chr.length > 1) {
                    result += chr;
                }
                else {
                    result += rfcCharHelper.isReserved(chr) || rfcCharHelper.isUnreserved(chr) ? chr : pctEncoder.encodeCharacter(chr);
                }
            }
            return result;
        }

        return {
            encode: encode,
            encodePassReserved: encodePassReserved,
            encodeLiteral: encodeLiteral,
            encodeLiteralCharacter: encodeLiteralCharacter
        };

    }());

    // the operators defined by rfc 6570
    var operators = (function () {

        var
            bySymbol = {};

        function create(symbol) {
            bySymbol[symbol] = {
                symbol: symbol,
                separator: (symbol === '?') ? '&' : (symbol === '' || symbol === '+' || symbol === '#') ? ',' : symbol,
                named: symbol === ';' || symbol === '&' || symbol === '?',
                ifEmpty: (symbol === '&' || symbol === '?') ? '=' : '',
                first: (symbol === '+') ? '' : symbol,
                encode: (symbol === '+' || symbol === '#') ? encodingHelper.encodePassReserved : encodingHelper.encode,
                toString: function () {
                    return this.symbol;
                }
            };
        }

        create('');
        create('+');
        create('#');
        create('.');
        create('/');
        create(';');
        create('?');
        create('&');
        return {
            valueOf: function (chr) {
                if (bySymbol[chr]) {
                    return bySymbol[chr];
                }
                if ("=,!@|".indexOf(chr) >= 0) {
                    return null;
                }
                return bySymbol[''];
            }
        };
    }());

    /**
     * Detects, whether a given element is defined in the sense of rfc 6570
     * Section 2.3 of the RFC makes clear defintions:
     * * undefined and null are not defined.
     * * the empty string is defined
     * * an array ("list") is defined, if it is not empty (even if all elements are not defined)
     * * an object ("map") is defined, if it contains at least one property with defined value
     * @param object
     * @return {Boolean}
     */
    function isDefined(object) {
        var
            propertyName;
        if (object === null || object === undefined) {
            return false;
        }
        if (objectHelper.isArray(object)) {
            // Section 2.3: A variable defined as a list value is considered undefined if the list contains zero members
            return object.length > 0;
        }
        if (typeof object === "string" || typeof object === "number" || typeof object === "boolean") {
            // falsy values like empty strings, false or 0 are "defined"
            return true;
        }
        // else Object
        for (propertyName in object) {
            if (object.hasOwnProperty(propertyName) && isDefined(object[propertyName])) {
                return true;
            }
        }
        return false;
    }

    var LiteralExpression = (function () {
        function LiteralExpression(literal) {
            this.literal = encodingHelper.encodeLiteral(literal);
        }

        LiteralExpression.prototype.expand = function () {
            return this.literal;
        };

        LiteralExpression.prototype.toString = LiteralExpression.prototype.expand;

        return LiteralExpression;
    }());

    var parse = (function () {

        function parseExpression(expressionText) {
            var
                operator,
                varspecs = [],
                varspec = null,
                varnameStart = null,
                maxLengthStart = null,
                index,
                chr = '';

            function closeVarname() {
                var varname = expressionText.substring(varnameStart, index);
                if (varname.length === 0) {
                    throw new UriTemplateError({ expressionText: expressionText, message: "a varname must be specified", position: index });
                }
                varspec = { varname: varname, exploded: false, maxLength: null };
                varnameStart = null;
            }

            function closeMaxLength() {
                if (maxLengthStart === index) {
                    throw new UriTemplateError({ expressionText: expressionText, message: "after a ':' you have to specify the length", position: index });
                }
                varspec.maxLength = parseInt(expressionText.substring(maxLengthStart, index), 10);
                maxLengthStart = null;
            }

            operator = (function (operatorText) {
                var op = operators.valueOf(operatorText);
                if (op === null) {
                    throw new UriTemplateError({ expressionText: expressionText, message: "illegal use of reserved operator", position: index, operator: operatorText });
                }
                return op;
            }(expressionText.charAt(0)));
            index = operator.symbol.length;

            varnameStart = index;

            for (; index < expressionText.length; index += chr.length) {
                chr = pctEncoder.pctCharAt(expressionText, index);

                if (varnameStart !== null) {
                    // the spec says: varname =  varchar *( ["."] varchar )
                    // so a dot is allowed except for the first char
                    if (chr === '.') {
                        if (varnameStart === index) {
                            throw new UriTemplateError({ expressionText: expressionText, message: "a varname MUST NOT start with a dot", position: index });
                        }
                        continue;
                    }
                    if (rfcCharHelper.isVarchar(chr)) {
                        continue;
                    }
                    closeVarname();
                }
                if (maxLengthStart !== null) {
                    if (index === maxLengthStart && chr === '0') {
                        throw new UriTemplateError({ expressionText: expressionText, message: "A :prefix must not start with digit 0", position: index });
                    }
                    if (charHelper.isDigit(chr)) {
                        if (index - maxLengthStart >= 4) {
                            throw new UriTemplateError({ expressionText: expressionText, message: "A :prefix must have max 4 digits", position: index });
                        }
                        continue;
                    }
                    closeMaxLength();
                }
                if (chr === ':') {
                    if (varspec.maxLength !== null) {
                        throw new UriTemplateError({ expressionText: expressionText, message: "only one :maxLength is allowed per varspec", position: index });
                    }
                    if (varspec.exploded) {
                        throw new UriTemplateError({ expressionText: expressionText, message: "an exploeded varspec MUST NOT be varspeced", position: index });
                    }
                    maxLengthStart = index + 1;
                    continue;
                }
                if (chr === '*') {
                    if (varspec === null) {
                        throw new UriTemplateError({ expressionText: expressionText, message: "exploded without varspec", position: index });
                    }
                    if (varspec.exploded) {
                        throw new UriTemplateError({ expressionText: expressionText, message: "exploded twice", position: index });
                    }
                    if (varspec.maxLength) {
                        throw new UriTemplateError({ expressionText: expressionText, message: "an explode (*) MUST NOT follow to a prefix", position: index });
                    }
                    varspec.exploded = true;
                    continue;
                }
                // the only legal character now is the comma
                if (chr === ',') {
                    varspecs.push(varspec);
                    varspec = null;
                    varnameStart = index + 1;
                    continue;
                }
                throw new UriTemplateError({ expressionText: expressionText, message: "illegal character", character: chr, position: index });
            } // for chr
            if (varnameStart !== null) {
                closeVarname();
            }
            if (maxLengthStart !== null) {
                closeMaxLength();
            }
            varspecs.push(varspec);
            return new VariableExpression(expressionText, operator, varspecs);
        }

        function parse(uriTemplateText) {
            // assert filled string
            var
                index,
                chr,
                expressions = [],
                braceOpenIndex = null,
                literalStart = 0;
            for (index = 0; index < uriTemplateText.length; index += 1) {
                chr = uriTemplateText.charAt(index);
                if (literalStart !== null) {
                    if (chr === '}') {
                        throw new UriTemplateError({ templateText: uriTemplateText, message: "unopened brace closed", position: index });
                    }
                    if (chr === '{') {
                        if (literalStart < index) {
                            expressions.push(new LiteralExpression(uriTemplateText.substring(literalStart, index)));
                        }
                        literalStart = null;
                        braceOpenIndex = index;
                    }
                    continue;
                }

                if (braceOpenIndex !== null) {
                    // here just { is forbidden
                    if (chr === '{') {
                        throw new UriTemplateError({ templateText: uriTemplateText, message: "brace already opened", position: index });
                    }
                    if (chr === '}') {
                        if (braceOpenIndex + 1 === index) {
                            throw new UriTemplateError({ templateText: uriTemplateText, message: "empty braces", position: braceOpenIndex });
                        }
                        try {
                            expressions.push(parseExpression(uriTemplateText.substring(braceOpenIndex + 1, index)));
                        }
                        catch (error) {
                            if (error.prototype === UriTemplateError.prototype) {
                                throw new UriTemplateError({ templateText: uriTemplateText, message: error.options.message, position: braceOpenIndex + error.options.position, details: error.options });
                            }
                            throw error;
                        }
                        braceOpenIndex = null;
                        literalStart = index + 1;
                    }
                    continue;
                }
                throw new Error('reached unreachable code');
            }
            if (braceOpenIndex !== null) {
                throw new UriTemplateError({ templateText: uriTemplateText, message: "unclosed brace", position: braceOpenIndex });
            }
            if (literalStart < uriTemplateText.length) {
                expressions.push(new LiteralExpression(uriTemplateText.substr(literalStart)));
            }
            return new UriTemplate(uriTemplateText, expressions);
        }

        return parse;
    }());

    var VariableExpression = (function () {
        // helper function if JSON is not available
        function prettyPrint(value) {
            return (JSON && JSON.stringify) ? JSON.stringify(value) : value;
        }

        function isEmpty(value) {
            if (!isDefined(value)) {
                return true;
            }
            if (objectHelper.isString(value)) {
                return value === '';
            }
            if (objectHelper.isNumber(value) || objectHelper.isBoolean(value)) {
                return false;
            }
            if (objectHelper.isArray(value)) {
                return value.length === 0;
            }
            for (var propertyName in value) {
                if (value.hasOwnProperty(propertyName)) {
                    return false;
                }
            }
            return true;
        }

        function propertyArray(object) {
            var
                result = [],
                propertyName;
            for (propertyName in object) {
                if (object.hasOwnProperty(propertyName)) {
                    result.push({ name: propertyName, value: object[propertyName] });
                }
            }
            return result;
        }

        function VariableExpression(templateText, operator, varspecs) {
            this.templateText = templateText;
            this.operator = operator;
            this.varspecs = varspecs;
        }

        VariableExpression.prototype.toString = function () {
            return this.templateText;
        };

        function expandSimpleValue(varspec, operator, value) {
            var result = '';
            value = value.toString();
            if (operator.named) {
                result += encodingHelper.encodeLiteral(varspec.varname);
                if (value === '') {
                    result += operator.ifEmpty;
                    return result;
                }
                result += '=';
            }
            if (varspec.maxLength !== null) {
                value = value.substr(0, varspec.maxLength);
            }
            result += operator.encode(value);
            return result;
        }

        function valueDefined(nameValue) {
            return isDefined(nameValue.value);
        }

        function expandNotExploded(varspec, operator, value) {
            var
                arr = [],
                result = '';
            if (operator.named) {
                result += encodingHelper.encodeLiteral(varspec.varname);
                if (isEmpty(value)) {
                    result += operator.ifEmpty;
                    return result;
                }
                result += '=';
            }
            if (objectHelper.isArray(value)) {
                arr = value;
                arr = objectHelper.filter(arr, isDefined);
                arr = objectHelper.map(arr, operator.encode);
                result += objectHelper.join(arr, ',');
            }
            else {
                arr = propertyArray(value);
                arr = objectHelper.filter(arr, valueDefined);
                arr = objectHelper.map(arr, function (nameValue) {
                    return operator.encode(nameValue.name) + ',' + operator.encode(nameValue.value);
                });
                result += objectHelper.join(arr, ',');
            }
            return result;
        }

        function expandExplodedNamed(varspec, operator, value) {
            var
                isArray = objectHelper.isArray(value),
                arr = [];
            if (isArray) {
                arr = value;
                arr = objectHelper.filter(arr, isDefined);
                arr = objectHelper.map(arr, function (listElement) {
                    var tmp = encodingHelper.encodeLiteral(varspec.varname);
                    if (isEmpty(listElement)) {
                        tmp += operator.ifEmpty;
                    }
                    else {
                        tmp += '=' + operator.encode(listElement);
                    }
                    return tmp;
                });
            }
            else {
                arr = propertyArray(value);
                arr = objectHelper.filter(arr, valueDefined);
                arr = objectHelper.map(arr, function (nameValue) {
                    var tmp = encodingHelper.encodeLiteral(nameValue.name);
                    if (isEmpty(nameValue.value)) {
                        tmp += operator.ifEmpty;
                    }
                    else {
                        tmp += '=' + operator.encode(nameValue.value);
                    }
                    return tmp;
                });
            }
            return objectHelper.join(arr, operator.separator);
        }

        function expandExplodedUnnamed(operator, value) {
            var
                arr = [],
                result = '';
            if (objectHelper.isArray(value)) {
                arr = value;
                arr = objectHelper.filter(arr, isDefined);
                arr = objectHelper.map(arr, operator.encode);
                result += objectHelper.join(arr, operator.separator);
            }
            else {
                arr = propertyArray(value);
                arr = objectHelper.filter(arr, function (nameValue) {
                    return isDefined(nameValue.value);
                });
                arr = objectHelper.map(arr, function (nameValue) {
                    return operator.encode(nameValue.name) + '=' + operator.encode(nameValue.value);
                });
                result += objectHelper.join(arr, operator.separator);
            }
            return result;
        }

        VariableExpression.prototype.expand = function (variables) {
            var
                expanded = [],
                index,
                varspec,
                value,
                valueIsArr,
                oneExploded = false,
                operator = this.operator;

            // expand each varspec and join with operator's separator
            for (index = 0; index < this.varspecs.length; index += 1) {
                varspec = this.varspecs[index];
                value = variables[varspec.varname];
                // if (!isDefined(value)) {
                // if (variables.hasOwnProperty(varspec.name)) {
                if (value === null || value === undefined) {
                    continue;
                }
                if (varspec.exploded) {
                    oneExploded = true;
                }
                valueIsArr = objectHelper.isArray(value);
                if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
                    expanded.push(expandSimpleValue(varspec, operator, value));
                }
                else if (varspec.maxLength && isDefined(value)) {
                    // 2.4.1 of the spec says: "Prefix modifiers are not applicable to variables that have composite values."
                    throw new Error('Prefix modifiers are not applicable to variables that have composite values. You tried to expand ' + this + " with " + prettyPrint(value));
                }
                else if (!varspec.exploded) {
                    if (operator.named || !isEmpty(value)) {
                        expanded.push(expandNotExploded(varspec, operator, value));
                    }
                }
                else if (isDefined(value)) {
                    if (operator.named) {
                        expanded.push(expandExplodedNamed(varspec, operator, value));
                    }
                    else {
                        expanded.push(expandExplodedUnnamed(operator, value));
                    }
                }
            }

            if (expanded.length === 0) {
                return "";
            }
            else {
                return operator.first + objectHelper.join(expanded, operator.separator);
            }
        };

        return VariableExpression;
    }());

    var UriTemplate = (function () {
        function UriTemplate(templateText, expressions) {
            this.templateText = templateText;
            this.expressions = expressions;
            objectHelper.deepFreeze(this);
        }

        UriTemplate.prototype.toString = function () {
            return this.templateText;
        };

        UriTemplate.prototype.expand = function (variables) {
            // this.expressions.map(function (expression) {return expression.expand(variables);}).join('');
            var
                index,
                result = '';
            for (index = 0; index < this.expressions.length; index += 1) {
                result += this.expressions[index].expand(variables);
            }
            return result;
        };

        UriTemplate.parse = parse;
        UriTemplate.UriTemplateError = UriTemplateError;
        return UriTemplate;
    }());

    exportCallback(UriTemplate);

}(function (UriTemplate) {
    "use strict";
    // export UriTemplate, when module is present, or pass it to window or global
    if (typeof module !== "undefined") {
        module.exports = UriTemplate;
    }
    else if (typeof define === "function") {
        define([], function () {
            return UriTemplate;
        });
    }
    else if (typeof window !== "undefined") {
        window.UriTemplate = UriTemplate;
    }
    else {
        global.UriTemplate = UriTemplate;
    }
}
));


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->
<resources>

    <dimen name="scrollbar_width">2dip</dimen>
</resources>


text:
package biz.orgin.minecraft.hothgenerator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import org.bukkit.Location;

/**
 * Handles region flags.
 * @author orgin
 *
 */
public abstract class RegionManager
{
		protected HothGeneratorPlugin plugin;

		private HashMap<String, RegionSet> regionSets;

		private FlagValue[] validFlags = new FlagValue[] {
			new FlagValue("dropice",              new String[]{"allow","deny", "[blank]"}),
			new FlagValue("droppackedice",        new String[]{"allow","deny", "[blank]"}),
			new FlagValue("dropsnow",             new String[]{"allow","deny", "[blank]"}),
			new FlagValue("freezewater",          new String[]{"allow","deny", "[blank]"}),
			new FlagValue("freezelava",           new String[]{"allow","deny", "[blank]"}),
			new FlagValue("plantsgrow",           new String[]{"allow","deny", "[blank]"}),
			new FlagValue("grassspread",          new String[]{"allow","deny", "[blank]"}),
			new FlagValue("stopmelt",             new String[]{"allow","deny", "[blank]"}),
			new FlagValue("limitslime",           new String[]{"allow","deny", "[blank]"}),
			new FlagValue("snowgravity",          new String[]{"allow","deny", "[blank]"}),
			new FlagValue("volcanoes",            new String[]{"allow","deny", "[blank]"}),
			new FlagValue("rfg.enable",           new String[]{"allow","deny", "[blank]"}),
			new FlagValue("rfg.coal",             new String[]{"[integer]", "[blank]"}),
			new FlagValue("rfg.redstone",         new String[]{"[integer]", "[blank]"}),
			new FlagValue("rfg.message1",         new String[]{"[text]", "[blank]"}),
			new FlagValue("rfg.message2",         new String[]{"[text]", "[blank]"}),
			new FlagValue("rfg.message3",         new String[]{"[text]", "[blank]"}),
			new FlagValue("rfg.message4",         new String[]{"[text]", "[blank]"}),
			new FlagValue("rfg.name",             new String[]{"[text]", "[blank]"}),
			new FlagValue("lavaburn",             new String[]{"allow","deny", "[blank]"}),
			new FlagValue("placewater",           new String[]{"allow","deny", "[blank]"}),
			new FlagValue("lessstone",            new String[]{"allow","deny", "[blank]"}),
			//new FlagValue("environment.period",      new String[]{"[integer]"}), // This is global only
			new FlagValue("environment.suit",     new String[]{"allow","deny", "[blank]"}),
			new FlagValue("freeze.damage",        new String[]{"[integer]", "[blank]"}),
			new FlagValue("freeze.stormdamage",   new String[]{"[integer]", "[blank]"}),
			new FlagValue("freeze.message",       new String[]{"[text]", "[blank]"}),
			new FlagValue("heat.damage",          new String[]{"[integer]", "[blank]"}),
			new FlagValue("heat.message1",        new String[]{"[text]", "[blank]"}),
			new FlagValue("heat.message2",        new String[]{"[text]", "[blank]"}),
			new FlagValue("heat.message3",        new String[]{"[text]", "[blank]"}),
			new FlagValue("heat.message4",        new String[]{"[text]", "[blank]"}),
			new FlagValue("mosquito.damage",      new String[]{"[integer]", "[blank]"}),
			new FlagValue("mosquito.rarity",      new String[]{"[integer]", "[blank]"}),
			new FlagValue("mosquito.runfree",     new String[]{"[integer]", "[blank]"}),
			new FlagValue("mosquito.message1",    new String[]{"[text]", "[blank]"}),
			new FlagValue("mosquito.message2",    new String[]{"[text]", "[blank]"}),
			new FlagValue("mosquito.message3",    new String[]{"[text]", "[blank]"}),
			new FlagValue("mosquito.message4",    new String[]{"[text]", "[blank]"}),
			new FlagValue("leech.damage",         new String[]{"[integer]", "[blank]"}),
			new FlagValue("leech.rarity",         new String[]{"[integer]", "[blank]"}),
			new FlagValue("leech.message1",       new String[]{"[text]", "[blank]"}),
			new FlagValue("leech.message2",       new String[]{"[text]", "[blank]"}),
			new FlagValue("leech.message3",       new String[]{"[text]", "[blank]"}),
			new FlagValue("leech.message4",       new String[]{"[text]", "[blank]"}),
			new FlagValue("leech.message5",       new String[]{"[text]", "[blank]"}),
			// new FlagValue("spawn.neutral.on",     new String[]{"allow","deny", "[blank]"}), // This is global only
			new FlagValue("spawn.neutral.rarity", new String[]{"[integer]", "[blank]"}),
			new FlagValue("spawn.neutral.mobs",   new String[]{"none", "[text]", "[blank]"})
		};

		public RegionManager(HothGeneratorPlugin plugin)
		{
			this.plugin = plugin;

			this.regionSets = new HashMap<String, RegionSet>();
		}

		/**
		 * Set a flag value for a specified region
		 * @param region
		 * @param flag
		 * @param value
		 * @return
		 */
		public boolean set(String region, String flag, String value)
		{
			// Check if there is such a flag
			RegionSet regionSet = this.regionSets.get(flag);
			if(regionSet==null)
			{
				return false;
			}

			if(value.equals(""))
			{
				regionSet.remove(region);
			}
			else
			{
				regionSet.set(region, value);
			}
			this.save(regionSet);
			return true;
		}

		/**
		 * remove a region from all region files
		 * @param region
		 */
		public void remove(String region)
		{
			for(int i=0;i<this.validFlags.length;i++)
			{
				String flag = this.validFlags[i].flag;

				RegionSet regionSet = this.regionSets.get(flag);

				if(regionSet!=null)
				{
					regionSet.remove(region);
					this.save(regionSet);
				}
			}
		}

		/**
		 * Check if a flag is set at the given location.
		 * @param flag
		 * @param location
		 * @return
		 */
		public boolean isSet(String flag, Location location)
		{
			// Check if there is a region at the location
			String region = this.getRegion(location);
			if(region==null)
			{
				return false;
			}

			// Check if there is such a flag
			RegionSet regionSet = this.regionSets.get(flag);
			if(regionSet==null)
			{
				return false;
			}

			// Check if the flag is set
			return regionSet.isSet(region);
		}

		/**
		 * Get the flag string value at the given location.
		 * @param flag
		 * @param location
		 * @param def Default value in case the flag is not set here.
		 * @return
		 */
		public String get(String flag, Location location, String def)
		{
			if(location==null)
			{
				return def;
			}

			// Check if there is a region at the location
			String region = this.getRegion(location);
			if(region==null)
			{
				return def;
			}

			// Check if there is such a flag
			RegionSet regionSet = this.regionSets.get(flag);
			if(regionSet==null)
			{
				return def;
			}

			// Get the flag value
			return regionSet.get(region, def);
		}

		/**
		 * Get the flag boolean value at the given location.
		 * @param flag
		 * @param location
		 * @param def Default value in case the flag is not set here.
		 * @return
		 */
		public boolean getBoolean(String flag, Location location, boolean def)
		{
			if(location==null)
			{
				return def;
			}

			// Check if there is a region at the location
			String region = this.getRegion(location);
			if(region==null)
			{
				return def;
			}

			// Check if there is such a flag
			RegionSet regionSet = this.regionSets.get(flag);
			if(regionSet==null)
			{
				return def;
			}

			// Get the flag value
			return regionSet.getBoolean(region, def);
		}

		/**
		 * Get the flag integer value at the given location.
		 * @param flag
		 * @param location
		 * @param def Default value in case the flag is not set here.
		 * @return
		 */
		public int getInt(String flag, Location location, int def)
		{
			if(location==null)
			{
				return def;
			}

			// Check if there is a region at the location
			String region = this.getRegion(location);
			if(region==null)
			{
				return def;
			}

			// Check if there is such a flag
			RegionSet regionSet = this.regionSets.get(flag);
			if(regionSet==null)
			{
				return def;
			}

			// Get the flag value
			return regionSet.getInt(region, def);
		}

		/**
		 * Get an applicable region name at the current position.
		 * regions with passthrough set to allow are ignored.
		 * @param location
		 * @return
		 */
		public abstract String getRegion(Location location);

		/**
		 * Get a string with all flag values for the specified region
		 * @param region
		 * @return
		 */

		public String getInfo(String region)
		{
			StringBuffer mySB = new StringBuffer();

			for(int i=0;i<this.validFlags.length;i++)
			{
				FlagValue flagValue = this.validFlags[i];

				RegionSet regionSet = this.regionSets.get(flagValue.flag);

				if(regionSet!=null)
				{
					if(regionSet.isSet(region))
					{
						if(mySB.length()!=0)
						{
							mySB.append("&f, ");
						}
						mySB.append("&f" + flagValue.flag + ": &9" + regionSet.get(region,""));
					}
				}
			}

			return mySB.toString();
		}

		/**
		 * Check if the specified region is actually a region
		 * @param region
		 * @return
		 */
		public abstract boolean isValidRegion(String region);

		/**
		 * Check if the specified flag is a valid flag
		 * @param flag
		 * @return
		 */
		public boolean isValidFlag(String flag)
		{
			for(int i=0;i<this.validFlags.length;i++)
			{
				if(flag.equals(validFlags[i].flag))
				{
					return true;
				}
			}

			return false;
		}

		/**
		 * Check if the specified value is valid for this flag
		 * @param flag
		 * @param value
		 * @return
		 */
		public boolean isValidFlagValue(String flag, String value)
		{
			for(int i=0;i<this.validFlags.length;i++)
			{
				if(flag.equals(this.validFlags[i].flag))
				{
					for(int j=0;j<this.validFlags[i].values.length;j++)
					{
						String _value = this.validFlags[i].values[j];
						if(_value.equals("[blank]"))
						{
							if(value.equals(""))
							{
								return true;
							}
						}
						else if(_value.equals("[integer]"))
						{
							try
							{
								Integer.parseInt(value);
								return true;
							}
							catch(NumberFormatException e)
							{
								return false;
							}
						}
						else if(_value.equals("[text]"))
						{
							return true;
						}
						else
						{
							if(_value.equals(value.toLowerCase()))
							{
								return true;
							}
						}
					}
				}
			}

			return false;
		}

		/**
		 * Get a string with all valid flags
		 * @return
		 */
		public String getValidFlags()
		{
			StringBuffer mySB = new StringBuffer();

			for(int i=0;i<this.validFlags.length;i++)
			{
				mySB.append(validFlags[i].flag);
				mySB.append(" ");
			}

			return mySB.toString();
		}

		/**
		 * Get a string with all the valid values for the given flag
		 * @param flag
		 * @return
		 */
		public String getValidFlagValues(String flag)
		{
			StringBuffer mySB = new StringBuffer();

			for(int i=0;i<this.validFlags.length;i++)
			{
				if(flag.equals(validFlags[i].flag))
				{
					for(int j=0;j<this.validFlags[i].values.length;j++)
					{
						mySB.append(this.validFlags[i].values[j]);
						mySB.append(" ");
					}
				}
			}

			return mySB.toString();

		}

		/**
		 * Load all flag files into memory
		 */
		public void load()
		{
			// First make sure that we have a directory
			File dataFolder = plugin.getDataFolder();
			String path = dataFolder.getAbsolutePath() + "/region";
			File regionFolder = new File(path);
			if(!regionFolder.exists())
			{
				regionFolder.mkdir();
			}

			for(int i=0;i<this.validFlags.length;i++)
			{
				String flag = validFlags[i].flag;

				RegionSet regionSet = new RegionSet(flag);

				File regionFile = new File(path + "/" + flag + ".cfg");

				try
				{
					if(regionFile.isFile())
					{
						BufferedReader reader = new BufferedReader(new FileReader(regionFile));

						String line;

						while( (line=reader.readLine())!=null)
						{
							String row = line.trim();
							if(row.length()>0 &&  row.charAt(0)!=';' && row.charAt(0)!='#')
							{
								// region:value
								String[] data = row.split(":",2);

								if(data.length==2 && data[1].length()>0)
								{
									regionSet.set(data[0].trim(), data[1].trim());
								}
							}
						}

						reader.close();

					}
				}
				catch(IOException e)
				{
					this.plugin.logMessage("Failed to load region file " + flag + ".cfg", true);
				}

				// open file
				// if file found read values into regionSet
				this.regionSets.put(flag, regionSet);
			}
		}

		/**
		 * Save a specific flag file
		 * @param regionSet
		 */
		public void save(RegionSet regionSet)
		{
			File dataFolder = plugin.getDataFolder();
			String path = dataFolder.getAbsolutePath() + "/region";

			try
			{
				String flag = regionSet.getFlag();

				File file = new File(path + "/" + flag + ".cfg");

				if(file.exists())
				{
					file.delete();
				}

				file.createNewFile();

				FileWriter writer = new FileWriter(file);

				writer.write("# Region flag file for " + flag + "\n");
				writer.write("#\n");

				String[] list = regionSet.getList();

				for(int j=0;j<list.length;j++)
				{
					writer.write(list[j] + "\n");
				}

				writer.flush();
				writer.close();
			}
			catch(IOException e)
			{
				this.plugin.logMessage("Failed to store regionSet + " + regionSet.getFlag(), true);
			}

		}

		private class FlagValue
		{
			public String flag;
			public String[] values;

			public FlagValue(String flag, String[] values)
			{
				this.flag = flag;
				this.values = values;
			}
		}

	}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>vaadin-upload Basic Examples</title>

  <link rel="import" href="common.html">
  <link rel="import" href="../../../bower_components/iron-icon/iron-icon.html">
  <link rel="import" href="../../../bower_components/iron-icons/iron-icons.html">
  <link rel="import" href="../../../bower_components/paper-toast/paper-toast.html">

Basic Examples

Advanced Usage

I18n

Things File Upload Examples

Basic Usage With Upload Request Properties

    <demo-snippet>
      <template>
        <things-file-upload target="upload" method="POST" timeout="300000" ></things-file-upload>
      </template>
    </demo-snippet>

Disabling Drag & Drop and Picking Multiple Files in the File Dialog

    <demo-snippet>
      <template>
        <things-file-upload nodrop nomultiple target="upload" method="POST" timeout="300000" ></things-file-upload>
      </template>
    </demo-snippet>

Custom Drop Label

    <demo-snippet>
      <template>
        <things-file-upload nodrop nomultiple target="upload" method="POST" timeout="300000" >

            <iron-icon icon="cloud-upload"></iron-icon>
            Drop files here...

        </things-file-upload>
      </template>
    </demo-snippet>


text:
package com.javarush.test.level24.lesson09.home01;

import java.util.LinkedList;
import java.util.List;

/* Рефакторинг
Сделайте так, чтобы метод getIterator возвращал анонимный класс.
Перенесите логику LocalIterator в анонимный класс.
Меняйте только тело метода getIterator.
*/
public class Solution {
    public static List<Iterator> iterators = new LinkedList<>();

    private int countItems;

    public Iterator getIterator(final String name) {
        return new Iterator() {
            String iteratorName;
            {
                iteratorName = name;
                countItems++;
                System.out.println(iteratorName + " item " + countItems);
            }

            public Iterator next() {
                return getIterator(name);
            }
        };
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        Iterator iterator = solution.getIterator("iterator");
        for (int i = 1; i < 5; i++) {
            iterators.add(iterator.next());
        }
    }
}