text:
package com.leadscope.commanda.lambda;

import pl.joegreen.lambdaFromString.TypeReference;

/**
 * Some utility methods that get statically imported for lambda code
 */
public class LambdaUtil {
  public static final TypeReference<String> STRING_TYPE = new TypeReference<String>(){};

  /**
   * @param v value to check
   * @return true iff v is null or only whitespace
   */
  public static boolean empty(String v) {
    return v == null || v.trim().length() == 0;
  }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

(function() {
  // Declare app level module which depends on views, and components
  angular.module('bn', [
    'ngSanitize',
    'ngCookies',
    'templates',
    'ui.bootstrap',
    'ui.router',
    'monospaced.elastic',
    'bn.common',
    'bn.main',
    'bn.sentence',
    'bn.reading_note',
    'bn.login',
    'bn.ref',
    'bn.trans'
  ]).
  config(['$locationProvider', '$stateProvider', '$urlRouterProvider', function($locationProvider, $stateProvider, $urlRouterProvider){
    $locationProvider.hashPrefix('!');

    // For any unmatched url, send to /route1
    $urlRouterProvider.otherwise("/main");

    // $stateProvider
    //     .state('main', {
    //         url: "/main",
    //         templateUrl: "main/index.html",
    //         controller: 'MainCtrl'
    //     })
    //     .state('login', {
    //         url: "/login",
    //         templateUrl: "login/index.html",
    //         controller: 'LoginCtrl'
    //     })
  }])

  .run(['$rootScope', function($rootScope) {
    $rootScope.safeApply = function(fn) {
      if (!this.$root) {
        this.$apply(fn);
        return;
      }
      var phase = this.$root.$$phase;
      if(phase == '$apply' || phase == '$digest') {
          if(fn && (typeof(fn) === 'function')) {
              fn();
          }
      } else {
          this.$apply(fn);
      }
    };
  }])
}());


text:
FROM postgres

ADD postgres-init/* /docker-entrypoint-initdb.d/


text:
ROOT_PATH=`pwd`
buildscript_dir=${ROOT_PATH}/buildscripts

BUILD_PREFIX="SCRIPT: "
BUILD_PREFIX_ERROR="SCRIPT-ERROR: "
GRUNT=${ROOT_PATH}/node_modules/grunt-cli/bin/grunt
DIST=dist

cd ${buildscript_dir}/..

npm config set proxy http://proxy-mu.intel.com:911
npm config set https-proxy http://proxy-mu.intel.com:911
npm install
if [ $? -ne 0 ]; then
    echo "${BUILD_PREFIX_ERROR}You had an error installing Node Packages. Aborting."
    exit 1
fi

echo "${BUILD_PREFIX}I'll run grunt teamcity"

${GRUNT} teamcity_codevalidation

if [ $? -ne 0 ]; then
    echo "${BUILD_PREFIX_ERROR}Your grunt test failed again. Last command didn't work. Aborting now."
    exit 1
fi

echo "${BUILD_PREFIX}grunt test was executed without errors. You're lucky ... so far ..."


text:
<?php
namespace Aloha\Twilio\Support\Laravel;

use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

class L5ServiceProvider extends LaravelServiceProvider
{
    use ServiceProviderTrait;

    /**
     * Boot method.
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../../config/config.php' => config_path('twilio.php'),
        ]);

        $this->mergeConfigFrom(__DIR__.'/../../config/config.php', 'twilio');
    }

    /**
     * @return array
     */
    protected function config()
    {
        return $this->app['config']->get('twilio.twilio');
    }
}


text:
"use strict";

const fs = require("fs");
const path = require("path");
const uniqBy = require("lodash/uniqBy");
const partition = require("lodash/partition");
const globby = require("globby");
const mem = require("mem");
const internalPlugins = require("../languages.js");
const thirdParty = require("./third-party.js");
const resolve = require("./resolve.js");

const memoizedLoad = mem(load, { cacheKey: JSON.stringify });
const memoizedSearch = mem(findPluginsInNodeModules);
const clearCache = () => {
  mem.clear(memoizedLoad);
  mem.clear(memoizedSearch);
};

function load(plugins, pluginSearchDirs) {
  if (!plugins) {
    plugins = [];
  }

  if (!pluginSearchDirs) {
    pluginSearchDirs = [];
  }
  // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
  if (pluginSearchDirs.length === 0) {
    const autoLoadDir = thirdParty.findParentDir(__dirname, "node_modules");
    if (autoLoadDir) {
      pluginSearchDirs = [autoLoadDir];
    }
  }

  const [externalPluginNames, externalPluginInstances] = partition(
    plugins,
    (plugin) => typeof plugin === "string"
  );

  const externalManualLoadPluginInfos = externalPluginNames.map(
    (pluginName) => {
      let requirePath;
      try {
        // try local files
        requirePath = resolve(path.resolve(process.cwd(), pluginName));
      } catch {
        // try node modules
        requirePath = resolve(pluginName, { paths: [process.cwd()] });
      }

      return {
        name: pluginName,
        requirePath,
      };
    }
  );

  const externalAutoLoadPluginInfos = pluginSearchDirs.flatMap(
    (pluginSearchDir) => {
      const resolvedPluginSearchDir = path.resolve(
        process.cwd(),
        pluginSearchDir
      );

      const nodeModulesDir = path.resolve(
        resolvedPluginSearchDir,
        "node_modules"
      );

      // In some fringe cases (ex: files "mounted" as virtual directories), the
      // isDirectory(resolvedPluginSearchDir) check might be false even though
      // the node_modules actually exists.
      if (
        !isDirectory(nodeModulesDir) &&
        !isDirectory(resolvedPluginSearchDir)
      ) {
        throw new Error(
          `${pluginSearchDir} does not exist or is not a directory`
        );
      }

      return memoizedSearch(nodeModulesDir).map((pluginName) => ({
        name: pluginName,
        requirePath: resolve(pluginName, { paths: [resolvedPluginSearchDir] }),
      }));
    }
  );

  const externalPlugins = [
    ...uniqBy(
      [...externalManualLoadPluginInfos, ...externalAutoLoadPluginInfos],
      "requirePath"
    ).map((externalPluginInfo) => ({
      name: externalPluginInfo.name,
      ...require(externalPluginInfo.requirePath),
    })),
    ...externalPluginInstances,
  ];

  return [...internalPlugins, ...externalPlugins];
}

function findPluginsInNodeModules(nodeModulesDir) {
  const pluginPackageJsonPaths = globby.sync(
    [
      "prettier-plugin-*/package.json",
      "@*/prettier-plugin-*/package.json",
      "@prettier/plugin-*/package.json",
    ],
    {
      cwd: nodeModulesDir,
      expandDirectories: false,
    }
  );
  return pluginPackageJsonPaths.map(path.dirname);
}

function isDirectory(dir) {
  try {
    return fs.statSync(dir).isDirectory();
  } catch {
    return false;
  }
}

module.exports = {
  loadPlugins: memoizedLoad,
  clearCache,
};


text:
<?php

namespace AmpProject\Exception\Cli;

use AmpProject\Exception\AmpCliException;
use OutOfBoundsException;

/**
 * Exception thrown when an invalid option was provided to the CLI.
 *
 * @package ampproject/amp-toolbox
 */
final class InvalidOption extends OutOfBoundsException implements AmpCliException
{

    /**
     * Instantiate an InvalidOption exception for an unknown option that was passed to the CLI.
     *
     * @param string $option Unknown option that was passed to the CLI.
     * @return self
     */
    public static function forUnknownOption($option)
    {
        $message = "Unknown option: '{$option}'.";

        return new self($message, AmpCliException::E_UNKNOWN_OPT);
    }
}


text:
require 'attr_json/attribute_definition'
require 'attr_json/attribute_definition/registry'
require 'attr_json/type/container_attribute'

module AttrJson
  # The mix-in to provide AttrJson support to ActiveRecord::Base models.
  # We call it `Record` instead of `ActiveRecord` to avoid confusing namespace
  # shadowing errors, sorry!
  #
  # @example
  #       class SomeModel < ActiveRecord::Base
  #         include AttrJson::Record
  #
  #         attr_json :a_number, :integer
  #       end
  #
  module Record
    extend ActiveSupport::Concern

    included do
      unless self <= ActiveRecord::Base
        raise TypeError, "AttrJson::Record can only be used with an ActiveRecord::Base model. #{self} does not appear to be one. Are you looking for ::AttrJson::Model?"
      end

      class_attribute :attr_json_registry, instance_accessor: false
      self.attr_json_registry = AttrJson::AttributeDefinition::Registry.new
    end

    protected

    # adapted from ActiveRecord query_attribute method
    # https://github.com/rails/rails/blob/v5.2.3/activerecord/lib/active_record/attribute_methods/query.rb#L12
    #
    # Sadly we could not re-use Rails code here, becuase the built-in method assumes attribute
    # can be obtained with `self[attr_name]`, which you can not with attr_json (is that bad?), as
    # well as `self.class.columns_hash[attr_name]` which you definitely can not (which is probably not bad),
    # and has no way to use the value-translation semantics independently of that. May be a problem if
    # ActiveRecord changes it's query method semantics in the future, will have to be sync'd here.
    #
    # Used to implement query methods on attr_json attributes, like `attr_json :foo, :string`, method `#foo?`
    def self.attr_json_query_method(record, attribute)
      value = record.send(attribute)

      case value
      when true
        true
      when false, nil, ActiveModel::Type::Boolean::FALSE_VALUES
        false
      else
        if value.respond_to?(:to_i) && ( Numeric === value || value.to_s !~ /[^0-9]/ )
          !value.to_i.zero?
        elsif value.respond_to?(:zero?)
          !value.zero?
        else
          !value.blank?
        end
      end
    end

    class_methods do
      # Access or set class-wide json_attribute_config. Inherited by sub-classes,
      # but setting on sub-classes is unique to subclass. Similar to how
      # rails class_attribute's are used.
      #
      # @example access config
      #   SomeClass.attr_json_config
      #
      # @example set config variables
      #    class SomeClass < ActiveRecordBase
      #       include JsonAttribute::Record
      #
      #       attr_json_config(default_container_attribute: "some_column")
      #    end
      # TODO make Model match please.
      def attr_json_config(new_values = {})
        if new_values.present?
          # get one without new values, then merge new values into it, and
          # set it locally for this class.
          @attr_json_config = attr_json_config.merge(new_values)
        else
          if instance_variable_defined?("@attr_json_config")
            # we have a custom one for this class, return it.
            @attr_json_config
          elsif superclass.respond_to?(:attr_json_config)
            # return superclass without setting it locally, so changes in superclass
            # will continue effecting us.
            superclass.attr_json_config
          else
            # no superclass, no nothing, set it to blank one.
            @attr_json_config = Config.new(mode: :record)
          end
        end
      end

      # Type can be a symbol that will be looked up in `ActiveModel::Type.lookup`,
      # or an ActiveModel:::Type::Value).
      #
      # @param name [Symbol,String] name of attribute
      #
      # @param type [ActiveModel::Type::Value] An instance of an ActiveModel::Type::Value (or subclass)
      #
      # @option options [Boolean] :array (false) Make this attribute an array of given type.
      #
      # @option options [Object] :default (nil) Default value, if a Proc object it will be #call'd
      #   for default.
      #
      # @option options [String,Symbol] :store_key (nil) Serialize to JSON using
      #   given store_key, rather than name as would be usual.
      #
      # @option options [Symbol,String] :container_attribute (attr_json_config.default_container_attribute, normally `json_attributes`) The real
      #   json(b) ActiveRecord attribute/column to serialize as a key in. Defaults to
      #  `attr_json_config.default_container_attribute`, which defaults to `:json_attributes`
      #
      # @option options [Boolean] :validate (true) Create an ActiveRecord::Validations::AssociatedValidator so
      #   validation errors on the attributes post up to self.
      #
      # @option options [Boolean] :rails_attribute (false) Create an actual ActiveRecord
      #    `attribute` for name param. A Rails attribute isn't needed for our functionality,
      #    but registering thusly will let the type be picked up by simple_form and
      #    other tools that may look for it via Rails attribute APIs. Default can be changed
      #    with `attr_json_config(default_rails_attribute: true)`
      def attr_json(name, type, **options)
        options = {
          rails_attribute: self.attr_json_config.default_rails_attribute,
          validate: true,
          container_attribute: self.attr_json_config.default_container_attribute,
          accepts_nested_attributes: self.attr_json_config.default_accepts_nested_attributes
        }.merge!(options)
        options.assert_valid_keys(AttributeDefinition::VALID_OPTIONS + [:validate, :rails_attribute, :accepts_nested_attributes])
        container_attribute = options[:container_attribute]

        # TODO arg check container_attribute make sure it exists. Hard cause
        # schema isn't loaded yet when class def is loaded. Maybe not.

        # Want to lazily add an attribute cover to the json container attribute,
        # only if it hasn't already been done. WARNING we are using internal
        # Rails API here, but only way to do this lazily, which I thought was
        # worth it. On the other hand, I think .attribute is idempotent, maybe we don't need it...
        #
        # We set default to empty hash, because that 'tricks' AR into knowing any
        # application of defaults is a change that needs to be saved.
        unless attributes_to_define_after_schema_loads[container_attribute.to_s] &&
               attributes_to_define_after_schema_loads[container_attribute.to_s].first.is_a?(AttrJson::Type::ContainerAttribute) &&
               attributes_to_define_after_schema_loads[container_attribute.to_s].first.model == self
           # If this is already defined, but was for superclass, we need to define it again for
           # this class.
           attribute container_attribute.to_sym, AttrJson::Type::ContainerAttribute.new(self, container_attribute), default: -> { {} }
        end

        self.attr_json_registry = attr_json_registry.with(
          AttributeDefinition.new(name.to_sym, type, options.except(:rails_attribute, :validate, :accepts_nested_attributes))
        )

        # By default, automatically validate nested models
        if type.kind_of?(AttrJson::Type::Model) && options[:validate]
          self.validates_with ActiveRecord::Validations::AssociatedValidator, attributes: [name.to_sym]
        end

        # We don't actually use this for anything, we provide our own covers. But registering
        # it with usual system will let simple_form and maybe others find it.
        if options[:rails_attribute]
          attr_json_definition = attr_json_registry[name]

          attribute_args = attr_json_definition.has_default? ? { default: attr_json_definition.default_argument } : {}
          self.attribute name.to_sym, attr_json_definition.type, **attribute_args

          # Ensure that rails attributes tracker knows about value we just fetched
          # for this particular attribute. Yes, we are registering an after_find for each
          # attr_json registered with rails_attribute:true, using the `name` from above under closure. .
          after_find do
            value = public_send(name)
            if value && has_attribute?(name.to_sym)
              write_attribute(name.to_sym, value)
              self.send(:clear_attribute_changes, [name.to_sym])
            end
          end
        end

        _attr_jsons_module.module_eval do
          # For getter and setter, we used to use read_store_attribute/write_store_attribute
          # copied from Rails store_accessor implementation.
          # https://github.com/rails/rails/blob/74c3e43fba458b9b863d27f0c45fd2d8dc603cbc/activerecord/lib/active_record/store.rb#L90-L96
          #
          # But in fact just getting/setting in the hash provided to us by ActiveRecord json type
          # container works BETTER for dirty tracking. We had a test that only passed doing it
          # this simple way.

          define_method("#{name}=") do |value|
            super(value) if defined?(super)
            attribute_def = self.class.attr_json_registry.fetch(name.to_sym)
            public_send(attribute_def.container_attribute)[attribute_def.store_key] = attribute_def.cast(value)
          end

          define_method("#{name}") do
            attribute_def = self.class.attr_json_registry.fetch(name.to_sym)
            public_send(attribute_def.container_attribute)[attribute_def.store_key]
          end

          define_method("#{name}?") do
            # implementation of `query_store_attribute` is based on Rails `query_attribute` implementation
            AttrJson::Record.attr_json_query_method(self, name)
          end
        end

        # Default attr_json_accepts_nested_attributes_for values
        if options[:accepts_nested_attributes]
          options = options[:accepts_nested_attributes] == true ? {} : options[:accepts_nested_attributes]
          self.attr_json_accepts_nested_attributes_for name, **options
        end
      end

      private

      # Define an anonymous module and include it, so can still be easily
      # overridden by concrete class. Design cribbed from ActiveRecord::Store
      # https://github.com/rails/rails/blob/4590d7729e241cb7f66e018a2a9759cb3baa36e5/activerecord/lib/active_record/store.rb
      def _attr_jsons_module # :nodoc:
        @_attr_jsons_module ||= begin
          mod = Module.new
          include mod
          mod
        end
      end
    end
  end
end


text:
import pika
connection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.1.10"))
channel=connection.channel()   #创建频道
channel.exchange_declare(exchange="logs",type="fanout")
message="hiiiiii"
channel.basic_publish(exchange="logs",routing_key="",body=message)
connection.close()


text:
use rustc_serialize::json;
use std::path::Path;

use dao::ProtonDao;
use error::Error;
use project_types::{FileLayout, FilePatch};
use utils;

/// Patches a layout's channels based on a provided patch file
pub fn patch_layout<P: AsRef<Path>, PD: ProtonDao> (
    dao: &PD,
    layout_id: u32,
    patch_file_path: P
) -> Result<(), Error> {

    // Load patch file
    let patch_json = try!(utils::file_as_string(patch_file_path.as_ref()));
    let patch_file: FilePatch = try!(json::decode(&patch_json).map_err(Error::JsonDecode));

    // Make sure patch is valid
    try!(patch_file.validate());

    // Apply patch
    for patch in patch_file.patches.iter() {
        match dao.patch_channel(layout_id, patch.internalChannel, patch.dmxChannel) {
            Ok(1) => {},
            Ok(0) => println!("No channels patched. vix: {}, dmx: {}", patch.internalChannel, patch.dmxChannel),
            Ok(num_ch) => println!("Patched {} channels.", num_ch),
            Err(e) => println!("Error: {}", e),
        }
    }

    Ok(())
}

/// Creates a new layout
pub fn new_layout<P: AsRef<Path>, PD: ProtonDao>(
    dao: &PD,
    layout_path: P,
) -> Result<u32, Error> {

    // Load layout from file
    let layout_json = try!(utils::file_as_string(layout_path.as_ref()));
    let file_layout: FileLayout = try!(json::decode(&layout_json).map_err(Error::JsonDecode));

    // Make sure layout is valid
    try!(file_layout.validate());

    // Create new channels and fixtures from layout and add to storage
    let (_, fixtures) = try!(file_layout.create_new_parts(dao));

    // Create new layout from fixtures
    let fix_ids = fixtures.iter()
        .map(|fixture| fixture.fixid)
        .collect::<Vec<u32>>();
    let layout = try!(dao.new_layout(&file_layout.layoutName, fix_ids));

    // Return layout id
    Ok(layout.layout_id)
}

/// Set a layout's sequence
pub fn set_sequence_layout<PD: ProtonDao>(
    dao: &PD,
    layout_id: u32,
    seqid: u32
) -> Result<(), Error> {

    // Check that sequence exists
    let sequence = try!(dao.get_sequence(seqid));

    // Check that current layout exists
    try!(dao.layout_exists(sequence.layout_id));

    // Check that new layout exists
    try!(dao.layout_exists(layout_id));

    // Set sequence layout id
    try!(dao.set_layout(seqid, layout_id));

    Ok(())
}


text:
#pragma once
#include <aws/kms/KMS_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace KMS
{
namespace Model
{
  enum class KeyState
  {
    NOT_SET,
    Enabled,
    Disabled,
    PendingDeletion
  };

namespace KeyStateMapper
{
AWS_KMS_API KeyState GetKeyStateForName(const Aws::String& name);

AWS_KMS_API Aws::String GetNameForKeyState(KeyState value);
} // namespace KeyStateMapper
} // namespace Model
} // namespace KMS
} // namespace Aws


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<?php $this->load->view( 'header' , $datos ); ?>

	            		<?php $this->load->view( 'menu_izquierdo',$datos ); ?>

									<?php $this->load->view( 'navegacion' ); ?>

									<?php $this->load->view( 'catalogos/configuraciones/detalle_configuracion'); ?>

	                	<?php $this->load->view( 'barra_lateral_rapida_menu' ); ?>

<?php $this->load->view( 'footer' ); ?>


text:
package com.netflix.spinnaker.kork.tomcat;

import org.apache.catalina.connector.Connector;
import org.apache.coyote.ProtocolHandler;
import org.apache.coyote.http11.AbstractHttp11JsseProtocol;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.apache.tomcat.util.net.SSLHostConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.Ssl;
import org.springframework.util.StringUtils;

class DefaultTomcatConnectorCustomizer implements TomcatConnectorCustomizer {

  private final Logger log = LoggerFactory.getLogger(getClass());

  private final TomcatConfigurationProperties tomcatConfigurationProperties;

  DefaultTomcatConnectorCustomizer(TomcatConfigurationProperties tomcatConfigurationProperties) {
    this.tomcatConfigurationProperties = tomcatConfigurationProperties;
  }

  @Override
  public void customize(Connector connector) {
    this.applySSLSettings(connector);
    this.applyRelaxedURIProperties(connector);
  }

  Ssl copySslConfigurationWithClientAuth(TomcatServletWebServerFactory tomcat) {
    Ssl ssl = new Ssl();

    BeanUtils.copyProperties(tomcat.getSsl(), ssl);
    ssl.setClientAuth(Ssl.ClientAuth.NEED);
    ssl.setCiphers(
        tomcatConfigurationProperties
            .getCipherSuites()
            .toArray(new String[tomcatConfigurationProperties.getCipherSuites().size()]));
    return ssl;
  }

  void applySSLSettings(Connector connector) {
    ProtocolHandler handler = connector.getProtocolHandler();
    if (handler instanceof AbstractHttp11JsseProtocol) {
      if (((AbstractHttp11JsseProtocol) handler).isSSLEnabled()) {
        SSLHostConfig[] sslConfigs = connector.findSslHostConfigs();
        if (sslConfigs.length != 1) {
          throw new RuntimeException(
              String.format("Ssl configs: found %d, expected 1.", sslConfigs.length));
        }
        SSLHostConfig sslHostConfig = sslConfigs[0];
        sslHostConfig.setHonorCipherOrder(true);
        sslHostConfig.setCiphers(String.join(",", tomcatConfigurationProperties.getCipherSuites()));
        sslHostConfig.setProtocols(
            String.join(",", tomcatConfigurationProperties.getTlsVersions()));
      }
    }
  }

  void applyRelaxedURIProperties(Connector connector) {
    if (StringUtils.isEmpty(tomcatConfigurationProperties.getRelaxedPathCharacters())
        && StringUtils.isEmpty(tomcatConfigurationProperties.getRelaxedQueryCharacters())) {
      return;
    }

    ProtocolHandler protocolHandler = connector.getProtocolHandler();
    if (protocolHandler instanceof AbstractHttp11Protocol) {
      if (!StringUtils.isEmpty(tomcatConfigurationProperties.getRelaxedPathCharacters())) {
        ((AbstractHttp11Protocol) protocolHandler)
            .setRelaxedPathChars(tomcatConfigurationProperties.getRelaxedPathCharacters());
      }
      if (!StringUtils.isEmpty(tomcatConfigurationProperties.getRelaxedQueryCharacters())) {
        ((AbstractHttp11Protocol) protocolHandler)
            .setRelaxedPathChars(tomcatConfigurationProperties.getRelaxedPathCharacters());
      }
    } else {
      log.warn(
          "Can't apply relaxedPath/Query config to connector of type $connector.protocolHandlerClassName");
    }
  }
}


text:
@protocol TestProtocol <NSObject>

@end

@protocol AnyProtocol <NSObject>

@property (nonatomic, assign, readonly) NSInteger anyTest;

@property (nonatomic, assign, readonly) id<TestProtocol> test;

@property (nonatomic, strong) NSNumber *num;

@end


text:
package org.apache.ivy;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.report.ResolveReport;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.plugins.repository.file.FileResource;
import org.apache.ivy.plugins.resolver.DependencyResolver;
import org.apache.ivy.plugins.resolver.util.ResolvedResource;

/**
 * Fixture easing the development of tests requiring to set up a simple repository with some
 * modules, using micro ivy format to describe the repository.
 *

 * Example of use:
 *

 *

 * public class MyTest {
 *     private TestFixture fixture;
 *
 *     @Before
 *     public void setUp() throws Exception {
 *         fixture = new TestFixture();
 *         // additional setup here
 *     }
 *
 *     @After
 *     public void tearDown() throws Exception {
 *         fixture.clean();
 *     }
 *
 *     @Test
 *     public void testXXX() throws Exception {
 *         fixture.addMD("#A;1-> { #B;[1.5,1.6] #C;2.5 }").addMD("#B;1.5->#D;2.0")
 *                 .addMD("#B;1.6->#D;2.0").addMD("#C;2.5->#D;[1.0,1.6]").addMD("#D;1.5")
 *                 .addMD("#D;1.6").addMD("#D;2.0").init();
 *         ResolveReport r = fixture.resolve("#A;1");
 *         // assertions go here
 *     }
 * }
 *

 */
public class TestFixture {

    private final Collection<ModuleDescriptor> mds = new ArrayList<>();

    private Ivy ivy;

    public TestFixture() {
        try {
            this.ivy = new Ivy();
            IvySettings settings = new IvySettings();
            settings.defaultInit();
            ivy.setSettings(settings);
            TestHelper.loadTestSettings(ivy.getSettings());
            ivy.bind();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public TestFixture addMD(String microIvy) {
        mds.add(TestHelper.parseMicroIvyDescriptor(microIvy));
        return this;
    }

    public TestFixture init() throws IOException {
        TestHelper.fillRepository(getTestRepository(), mds);
        return this;
    }

    private DependencyResolver getTestRepository() {
        return ivy.getSettings().getResolver("test");
    }

    public IvySettings getSettings() {
        return ivy.getSettings();
    }

    public Ivy getIvy() {
        return ivy;
    }

    public void clean() {
        TestHelper.cleanTest();
    }

    public File getIvyFile(String mrid) {
        ResolvedResource r = getTestRepository().findIvyFileRef(
            new DefaultDependencyDescriptor(ModuleRevisionId.parse(mrid), false),
            TestHelper.newResolveData(getSettings()));
        if (r == null) {
            throw new IllegalStateException("module not found: " + mrid);
        }
        return ((FileResource) r.getResource()).getFile();
    }

    public ResolveReport resolve(String mrid) throws ParseException,
            IOException {
        return ivy.resolve(getIvyFile(mrid), TestHelper.newResolveOptions(getSettings()));
    }

}


text:
package com.drivers.entity;

import lombok.Data;

import java.time.ZonedDateTime;
import java.util.Date;
import javax.persistence.*;

@Table(name = "suggestion_feekback")
@Data
public class SuggestionFeekback {
    /**
     * 数据ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 投诉建议数据ID
     */
    @Column(name = "suggestion_id")
    private Long suggestionId;
    /**
     * 操作类型(1:接受,2:拒绝,3:消息回复,4:关闭)
     */
    @Column(name = "op_type")
    private Integer opType;
    /**
     * 操作名称
     */
    @Column(name = "op_name")
    private String opName;
    /**
     * 反馈信息
     */
    private String content;
    /**
     * 数据创建者
     */
    @Column(name = "data_creator")
    private String dataCreator;

    /**
     * 数据更新者
     */
    @Column(name = "data_updater")
    private String dataUpdater;

    /**
     * 数据创建日期时间
     */
    @Column(name = "data_create_datetime")
    private ZonedDateTime dataCreateDatetime;

    /**
     * 数据更新日期时间
     */
    @Column(name = "data_update_datetime")
    private ZonedDateTime dataUpdateDatetime;
}


text:
  Apply an async function to each Array element in series

## Installation

  Install with [npm](https://www.npmjs.org):

    $ npm install async-each-series

  Install with [component(1)](http://component.io):

    $ component install jb55/async-each-series

## Examples

### Node.js

```javascript
var each = require('async-each-series');
each(['foo','bar','baz'], function(el, next) {
  setTimeout(function () {
    console.log(el);
    next();
  }, Math.random() * 5000);
}, function (err) {
  console.log('finished');
});
//=> foo
//=> bar
//=> baz
//=> finished
```

## API

### eachSeries(array, iterator(elem, cb(err, elem)), finishedCb(err))

## License

  The MIT License (MIT)

  Copyright (c) 2014 William Casarin

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

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

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


text:
package org.apache.sqoop.manager.oracle;

import org.apache.sqoop.testcategories.sqooptest.UnitTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;

@Category(UnitTest.class)
public class TestOraOopDBInputSplitGetDebugDetails {
    private OraOopDBInputSplit firstSplit;
    private OraOopDBInputSplit secondSplit;
    private String firstSplitResult;

    @Before
    public void initialize() {
        List<OraOopOracleDataChunk> dataChunkList = new ArrayList<>();
        OraOopOracleDataChunkExtent firstDataChunkExtent = new OraOopOracleDataChunkExtent("firstExtent",
                666,1, 10500, 10507);
        OraOopOracleDataChunkExtent secondDataChunkExtent = new OraOopOracleDataChunkExtent("secondExtent",
                666,1, 10508, 10515);
        OraOopOracleDataChunkExtent thirdDataChunkExtent = new OraOopOracleDataChunkExtent("thirdExtent",
                666,1, 10516, 10523);
        OraOopOracleDataChunkExtent fourthDataChunkExtent = new OraOopOracleDataChunkExtent("fourthExtent",
                787,2, 11434, 11450);
        OraOopOracleDataChunkPartition firstDataChunkPartition = new OraOopOracleDataChunkPartition("firstPartition",
                true, 14);
        OraOopOracleDataChunkPartition secondDataChunkPartition = new OraOopOracleDataChunkPartition("secondPartition",
                false, 4);
        OraOopOracleDataChunkPartition thirdDataChunkPartition = new OraOopOracleDataChunkPartition("thirdPartition",
                false, 43);
        dataChunkList.addAll(Arrays.asList(firstDataChunkExtent, secondDataChunkExtent, thirdDataChunkExtent,
                fourthDataChunkExtent, firstDataChunkPartition, secondDataChunkPartition, thirdDataChunkPartition));
        firstSplit = new OraOopDBInputSplit(dataChunkList);
        secondSplit = new OraOopDBInputSplit();
        firstSplitResult = "Split[0] includes the Oracle data-chunks:" +
                "\n\t Data chunk info:" +
                "\n\t\t id = firstExtent" +
                "\n\t\t oracleDataObjectId = 666" +
                "\n\t\t relativeDatafileNumber = 1" +
                "\n\t\t startBlockNumber = 10500" +
                "\n\t\t finishBlockNumber = 10507" +
                "\n\t Data chunk info:" +
                "\n\t\t id = secondExtent" +
                "\n\t\t oracleDataObjectId = 666" +
                "\n\t\t relativeDatafileNumber = 1" +
                "\n\t\t startBlockNumber = 10508" +
                "\n\t\t finishBlockNumber = 10515" +
                "\n\t Data chunk info:" +
                "\n\t\t id = thirdExtent" +
                "\n\t\t oracleDataObjectId = 666" +
                "\n\t\t relativeDatafileNumber = 1" +
                "\n\t\t startBlockNumber = 10516" +
                "\n\t\t finishBlockNumber = 10523" +
                "\n\t Data chunk info:" +
                "\n\t\t id = fourthExtent" +
                "\n\t\t oracleDataObjectId = 787" +
                "\n\t\t relativeDatafileNumber = 2" +
                "\n\t\t startBlockNumber = 11434" +
                "\n\t\t finishBlockNumber = 11450" +
                "\n\t Data chunk info:" +
                "\n\t\t id = firstPartition" +
                "\n\t\t isSubPartition = true" +
                "\n\t\t blocks = 14" +
                "\n\t Data chunk info:" +
                "\n\t\t id = secondPartition" +
                "\n\t\t isSubPartition = false" +
                "\n\t\t blocks = 4" +
                "\n\t Data chunk info:" +
                "\n\t\t id = thirdPartition" +
                "\n\t\t isSubPartition = false" +
                "\n\t\t blocks = 43";
    }

    @Test
    public void testGetDebugDetails() {
        assertEquals(firstSplitResult, firstSplit.getDebugDetails());
    }

    @Test
    public void testEmptySplitDebugDetails(){
        assertEquals("Split[-1] does not contain any Oracle data-chunks.", secondSplit.getDebugDetails());
    }
}


text:
using NUnit.Framework;

namespace Tauco.Dicom.Tests.Integration
{
    [TestFixture]
    public class SettingsProviderTests
    {
        [Test]
        public void CalledApplicationEntity_ReturnsExpectedValue()
        {
            // Arrange
            SettingsProvider settingsProvider = new SettingsProvider();

            // Act
            var result = settingsProvider.CalledApplicationEntity;

            // Assert
            Assert.That(result, Is.EqualTo("ORTHANC"));
        }

        [Test]
        public void CallingApplicationEntity_ReturnsExpectedValue()
        {
            // Arrange
            SettingsProvider settingsProvider = new SettingsProvider();

            // Act
            var result = settingsProvider.CallingApplicationEntity;

            // Assert
            Assert.That(result, Is.EqualTo("TAUCO"));
        }

        [Test]
        public void DestinationApplicationEntity_ReturnsExpectedValue()
        {
            // Arrange
            SettingsProvider settingsProvider = new SettingsProvider();

            // Act
            var result = settingsProvider.DestinationApplicationEntity;

            // Assert
            Assert.That(result, Is.EqualTo("TAUCO"));
        }

        [Test]
        public void LocalAddress_ReturnsExpectedValue()
        {
            // Arrange
            SettingsProvider settingsProvider = new SettingsProvider();

            // Act
            var result = settingsProvider.LocalAddress;

            // Assert
            Assert.That(result, Is.EqualTo("127.0.0.1"));
        }

        [Test]
        public void LocalPort_ReturnsExpectedValue()
        {
            // Arrange
            SettingsProvider settingsProvider = new SettingsProvider();

            // Act
            var result = settingsProvider.LocalPort;

            // Assert
            Assert.That(result, Is.EqualTo(104));
        }

        [Test]
        public void RemoteAddress_ReturnsExpectedValue()
        {
            // Arrange
            SettingsProvider settingsProvider = new SettingsProvider();

            // Act
            var result = settingsProvider.RemoteAddress;

            // Assert
            Assert.That(result, Is.EqualTo("127.0.0.1"));
        }

        [Test]
        public void RemotePort_ReturnsExpectedValue()
        {
            // Arrange
            SettingsProvider settingsProvider = new SettingsProvider();

            // Act
            var result = settingsProvider.RemotePort;

            // Assert
            Assert.That(result, Is.EqualTo(4242));
        }
    }
}


text:
package com.example.EECS_581.ecc_android_app;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

/**
 * Created by Jiaxiang Li on 11/25/2014.
 */
public class GetPassword extends Activity {
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.get_password);
    }
}


text:
<?php
namespace common\models;

use yii\base\Model;

class EntryForm extends Model
{
    public $quantity;
    public $variant;
    public $size;
    public $color;
    public $quantityColor1;
    public $quantityColor2;

    public function rules()
    {
        return [
            [['quantity', 'variant', 'size', 'color', 'quantityColor1', 'quantityColor2'], 'required'],
        ];
    }
}


text:
module LocalizableModel
  # = LocalizableModel::ActiveRecordExtension
  #
  # Extends ActiveRecord::Base with the localizable setup method.
  #
  module ActiveRecordExtension
    # Extends the model with Localizable features.
    # It takes an optional block as argument, which yields an instance of
    # LocalizableModel::Configuration.
    #
    # Example:
    #
    #  class Page < ActiveRecord::Base
    #    localizable do
    #      attribute :name
    #      attribute :body
    #    end
    #  end
    #
    def localizable(&block)
      unless is_a?(LocalizableModel::ClassMethods)
        send :extend,  LocalizableModel::ClassMethods
        send :include, LocalizableModel::InstanceMethods
        has_many(:localizations,
                 as: :localizable,
                 dependent: :destroy,
                 autosave: true)
        before_save :cleanup_localizations!
      end
      localizable_configuration.instance_eval(&block) if block_given?
      define_localizable_methods!
    end
  end
end

ActiveRecord::Base.send(:extend, LocalizableModel::ActiveRecordExtension)


text:
"use strict";

const [{resolve}, co] = [require("path"), require("co")];
const services = resolve(__dirname, "..", "services");
const goodsService = require(resolve(services, "goodsService"));

describe("goodsService", () => {

  before(done => {
    co(function* (){
      return goodsService.cleanDocuments();
    }).then(() => done()).catch(err => done(err));
  });
});


text:
"""Export the files needed by the KIM api."""

import os
import glob
import shutil
import string
from copy import copy
import subprocess
if not hasattr(subprocess, 'check_output'):
    # Pre-2.7 hack
    print "WARNING: Fixing pre Python 2.7 compatibility"
    from subprocess_py27 import check_output
    subprocess.check_output = check_output

# List all models to be exported, and the files that are specific to that model.
# The keys are the models, the values the list of files.  If the list of files is
# an empty list, it is assumed that only the common files are to be exported.  If
# the list of files is False, no files except the directory is copied, this is for
# models depending on a model driver.

emtfilelist = ['EMT.cpp', 'EMTDefaultParameterProvider.cpp', 'EMTParameterProvider.h']
model_files = {
               'EMT_Asap__MD_128315414717_002': emtfilelist,     # Model driver
               'EMT_Asap_Standard_Jacobsen_Stoltze_Norskov_AlAgAuCuNiPdPt__MO_118428466217_002': False, # Based on EMT_Asap driver
               'EMT_Asap_MetalGlass_CuMgZr__MO_655725647552_002': False,       # Based on EMT_Asap driver
               }

# List all model drivers, so the script can distinguish between model drivers and models.
all_drivers = ['EMT_Asap__MD_128315414717_002']

# List all files from the Basics directory.  If a .cpp file is given, the corresponding
# .h file does not need to be specified, it is added automatically.
basic_files = ['NeighborLocator.h', 'NeighborCellLocator.cpp', 'Asap.h',
               'AsapObject.cpp', 'Vec.cpp', 'TinyMatrix.h', 'Potential.cpp', 'SymTensor.h',
               'Exception.cpp', 'IVec.h', 'Timing.cpp', 'mass.h', 'Debug.h',
               'Matrix3x3.cpp', 'TimingResults.h']

fake_headers = ['AsapPython.h', 'Atoms.h', 'Templates.h']

fake_header_template = """
// Fake header replacing an Asap header file.

#include "Kim%s"
"""

svnrevision = None
asapversion = None

def main():
    global svnrevision, asapversion
    svnrevision = subprocess.check_output('svnversion .', shell=True).strip()
    asapversion = subprocess.check_output('python ../Python/asap3/version.py', shell=True).strip()
    models = model_files.keys()
    try:
        kimdir = os.environ['ASAP_KIM_DIR']
    except KeyError:
        if os.path.isdir('../../kim-api'):
            kimdir = '../../kim-api'
        else:
            raise RuntimeError("Cannot locate the openkim-api directory - please set $ASAP_KIM_DIR.")
    kimmodeldir = os.path.join(kimdir, 'src', 'models')
    kimdriverdir = os.path.join(kimdir, 'src', 'model_drivers')
    # Add header files
    local_files = glob.glob('*.h') + glob.glob('*.cpp')
    for model in models:
        isdriver = model in all_drivers
        dependent_model = model_files[model] is False
        if dependent_model:
            my_basic_files = copy(basic_files)
        else:
            my_basic_files = basic_files + model_files[model]
        hdr = []
        for f in my_basic_files:
            if f.endswith('.cpp'):
                hdr.append(f[:-4]+'.h')
        my_basic_files.extend(hdr)
        if isdriver:
            model_dir = os.path.join(kimdriverdir, model)
        else:
            model_dir = os.path.join(kimmodeldir, model)
        print "Populating", model_dir
        if not os.path.exists(model_dir):
            os.mkdir(model_dir)
        populate(model_dir, model, os.listdir(model))
        if not dependent_model:
            populate(model_dir, '../Basics', my_basic_files)
            populate(model_dir, '.', local_files)
            for fake in fake_headers:
                fn = os.path.join(model_dir, fake)
                if not os.path.exists(fn):
                    print "Creating", fn
                    f = open(fn, "w")
                    f.write(fake_header_template % (fake,))
                    f.close()
            shutil.copy('Makefiletemplate.mk', os.path.join(model_dir, 'Makefile'))
            # Create model definition include file
            incfilename = os.path.join(model_dir, 'Modeldefinition.mk')
            incfile = open(incfilename, 'w')
            if isdriver:
                incfile.write('MODEL_DRIVER_NAME := %s\n' % (model,))
                # There should be exactly one *.kim.tpl file
                template = glob.glob('%s/*.kim.tpl' % (model,))
                if len(template) != 1:
                    raise RuntimeError('Expected one template file, found %i: %s' % (len(template), str(template)))
                incfile.write('MODEL_DRIVER_KIM_FILE_TEMPLATE := %s\n' % (os.path.basename(template[0]),))
                incfile.write('MODEL_DRIVER_INIT_FUNCTION_NAME := model_driver_init\n')
            else:
                incfile.write('MODEL_NAME := %s\n' % (model,))
            allfiles = os.listdir(model_dir)
            cppfiles = []
            objfiles = []
            for f in allfiles:
                if f.endswith('.cpp'):
                    cppfiles.append(f)
            incfile.write('MODEL_SOURCES := %s\n' % (' '.join(cppfiles)),)
            incfile.close()
            # Make the file with the dependencies
            cmd = '''cd %s && bash -c "g++ -MM -I'%s/src' *.cpp > Depend.tmp"''' % (model_dir, kimdir)
            print cmd
            subprocess.check_call(cmd, shell=True)
            infile = os.path.join(model_dir, 'Depend.tmp')
            outfile = os.path.join(model_dir, 'Depend.mk')
            out = open(outfile, "w")
            for line in open(infile):
                words = line.split(' ')
                words = [x for x in words if '/' not in x]
                keep = False
                for w in words:
                    if w != '' and w != '\\' and w != '\\\n' and w != '\n':
                        keep = True
                if keep:
                    out.write(" ".join(words))
            out.close()
            os.remove(infile)
    print "\nAsap svn version:", svnrevision
    if 'M' in svnrevision or ':' in svnrevision:
        print "\nWARNING: SVN is not up to date (locally modified files or mixed revision)."
        print "This is OK for daily use, but not when submitting to OpenKIM.org"

def populate(targetdir, sourcedir, files):
    for f in files:
        if f == '.svn':
            continue
        sourcefile = os.path.join(sourcedir, f)
        targetfile = os.path.join(targetdir, f)
        if f == 'README':
            # README file is a template that should always be updated
            readme = string.Template(open(sourcefile).read())
            ff = open(targetfile, 'w')
            ff.write(readme.substitute(svnrevision=svnrevision, version=asapversion))
            ff.close()
            print "Updated (and substituted)", targetfile
        else:
            if not os.path.exists(targetfile):
                newer = True
            else:
                newer = (os.stat(sourcefile).st_mtime > os.stat(targetfile).st_mtime)
            if newer:
                shutil.copy(os.path.join(sourcedir, f), targetfile)
                print "Updated", targetfile

main()


text:
.. index::
    single: Canvas

.. highlight:: javascript

.. _Canvas:

-----------------
The Canvas Object
-----------------

Implements the Canvas API.

For more information about the standard please read the
`canvas element specification <http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element>`_.

This article will only document the differences between the Turbulenz Engine implementation and browser implementations;
all methods and properties are supported as defined by the specification unless documented otherwise.

**Required scripts**

The Canvas object requires::

    /*{{ javascript("jslib/canvas.js") }}*/

Turbulenz Engine Canvas vs Browser Canvas
=========================================

There are several differences between the Turbulenz Engine canvas implementation and browser implementations:

Performance
-----------

The performance of the Turbulenz Engine implementation of canvas is generally better than the implementation provided by
the browser. Early browser canvas implementations did not use the GPU to render the canvas commands hence the
performance was poor. Most newer browsers do use the GPU and performance is much better but, based on our limited tests,
the Turbulenz Engine implementation is still faster.

Some potential reasons for the performance difference are that:

* Browsers follow the standard closely.
    * Turbulenz Canvas deviates from the standard in a couple of cases for performance reasons. The `Behavior` section documents these deviations.
* Browsers enable anti-aliasing by default.
    * When using Turbulenz Canvas you would need to use super-sampling or create the GraphicsDevice with multi-sampling enabled to get similar results - performance will not be severely affected.
* The canvas element is transparent by default, which may force additional blending with the background.
    * The Turbulenz element in the page is always opaque.
* Browsers may need to do complex composition to render the canvas element as part of the page.
    * The Turbulenz element is rendered independently of the page.

Behavior
--------

As well as performance differences, there are also behavioral differences when using the Turbulenz Engine Canvas.

**SVG paths**

Turbulenz Canvas provides support for drawing `SVG path strings <http://www.w3.org/TR/SVG/paths.html>`_ directly
with the method :ref:`CanvasContext.path <CanvasContext_path>`. SVG paths are a really good compact way of storing
complex shapes. This feature is not yet part of the standard.

**Anti-aliasing**

Turbulenz Canvas does not provide anti-aliasing by default. You would need to use super-sampling or create the
GraphicsDevice with multi-sampling enabled to get some form of anti-aliasing.

**Shadows Blur**

Turbulenz Canvas does not support blurring of shapes shadows.

**Complex Clipping**

Turbulenz Canvas only provides clipping for the intersection of the combined rectangular extents of the shapes on the
path. It uses the :ref:`scissor rectangle <graphicsdevice_setscissor>` provided by the GPU for fast clipping.

**Global composition**

Turbulenz Canvas supports all the global composition modes on the global alpha value but only applied locally to the
current shape, hence the composition is more 'local' than 'global'.

Full support for global composition of the most complex modes would require the use of temporary render targets and it
would severely impact performance.

**Non-zero winding number rule**

Turbulenz Canvas does not implement the non-zero winding number rule of the specification,
thus if two overlapping but otherwise independent subpaths have opposite windings, they will both be filled, as opposed
to what the standard requires.

**Filling concave polygons**

Turbulenz Canvas uses the `ear clipping <http://en.wikipedia.org/wiki/Polygon_triangulation#Ear_clipping_method>`_
algorithm to fill concave polygons. This method is suboptimal and only works on polygons without holes, but it is easy
to implement and requires less amount code to be written.

**Text rendering**

Turbulenz Canvas offers limited support for
`fillText <http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-filltext>`_
when a :ref:`FontManager <FontManager>` object is provided with :ref:`Canvas.setFontManager <Canvas_setFontManager>`:

* Pattern and gradient styles are not supported, only colors.
* Only `alphabetic` and `top` are supported for `textBaseline`.
* `left` and `start` are equivalent, `right` and `end` are also equivalent for `textAlign`.

Turbulenz Canvas does not support
`strokeText <http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-stroketext>`_.

**Begin/End Of Frame**

Turbulenz 2D Context Canvas requires calls to :ref:`CanvasContext.beginFrame <CanvasContext_beginFrame>` and
:ref:`CanvasContext.endFrame <CanvasContext_endFrame>` in order to support mixing of other 2D or 3D rendering to the
same rendering targets.

.. NOTE::

    Only the Turbulenz Canvas API should be used for rendering between
    :ref:`CanvasContext.beginFrame <CanvasContext_beginFrame>` and
    :ref:`CanvasContext.endFrame <CanvasContext_endFrame>`,
    using any other rendering API between those two calls will result in visual artifacts.

**Changing width or height**

Changing the width or height attributes of a browser canvas element resizes the HTML element on the page. In contrast,
changing the width or height attributes of a Turbulenz canvas object only scales the coordinate system used and leaves
the render-target size unchanged. The dimensions of the render target itself are defined by, and can be changed using,
:ref:`CanvasContext.beginFrame <CanvasContext_beginFrame>`.

**drawSystemFocusRing / drawCustomFocusRing / scrollPathIntoView**

Turbulenz Canvas does not support `drawSystemFocusRing`, `drawCustomFocusRing` or `scrollPathIntoView`.

**lineJoin / lineCap**

Turbulenz Canvas only supports `butt` for `lineCap` and `miter` for `lineJoin`.

**Graphics/Math device required**

When using the Turbulenz Canvas implementation, you are required to provide a graphicsDevice object.
This is so the implementation can setup the canvas element.
When running in plugin mode, this will use the plugin object. In canvas mode, this will attempt to create a WebGL 3D context.

.. NOTE::

    If using the Turbulenz Canvas with either plugin or canvas (WebGL), you will not be able to request the canvas context directly i.e.::

        var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});

        var canvasElem = TurbulenzEngine.canvas;
        var canvas = Canvas.create(graphicsDevice);

        //BAD: ctx === null
        var ctx = canvasElem.getContext('2d');

    since a context has already been created by the graphics device. To access it call::

        var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});

        var canvasElem = TurbulenzEngine.canvas;
        var canvas = Canvas.create(graphicsDevice);

        //OK: ctx === Turbulenz Canvas Context
        var ctx = canvas.getContext('2d');

Constructor
===========

.. index::
    pair: Canvas; create

.. _Canvas_create:

`create`
--------

**Summary**

Creates and returns a Canvas object with default state.

**Syntax** ::

    var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});
    var canvas = Canvas.create(graphicsDevice);

Methods
=======

.. index::
    pair: Canvas; setFontManager

.. _Canvas_setFontManager:

`setFontManager`
----------------

**Summary**

Sets the :ref:`FontManager <FontManager>` object to be used by the :ref:`CanvasContext <CanvasContext>` object to render
text.

**Syntax** ::

    canvas.setFontManager(fontManager);

``fontManager``
    A :ref:`FontManager <FontManager>` object.

Properties
==========

.. index::
    pair: Canvas; version

`version`
---------

**Summary**

The version number of the Canvas implementation.

**Syntax** ::

    var canvasVersionNumber = canvas.version;

.. index::
    single: CanvasContext

.. _CanvasContext:

------------------------
The CanvasContext Object
------------------------

Implements the 2D Context Canvas API.

For more information about the standard please read the
`2D context specification <http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#2dcontext>`_.

This article will only document the differences between the Turbulenz Engine implementation and the browser
implementation; all methods and properties are supported as defined by the specification unless documented otherwise.

To get a CanvasContext object you have to request a '2d' context from a :ref:`Canvas <Canvas>` object::

    var canvas2dContext = canvas.getContext('2d');

Methods
=======

.. index::
    pair: CanvasContext; beginFrame

.. _CanvasContext_beginFrame:

`beginFrame`
------------

**Summary**

Signals the beginning of a new render frame.

.. NOTE::

    Only the Turbulenz Canvas API should be used for rendering between
    :ref:`CanvasContext.beginFrame <CanvasContext_beginFrame>` and
    :ref:`CanvasContext.endFrame <CanvasContext_endFrame>`,
    using any other rendering API between those two calls will result in visual artifacts.

**Syntax** ::

    var viewportRect = [x, y, width, height];
    canvas2dContext.beginFrame(target, viewportRect);

``target``
    A :ref:`GraphicsDevice <GraphicsDevice>` object or a :ref:`Texture <Texture>` object.
    This will inform the 2D context of the rendering target for the drawing commands,
    it is needed in order to adjust the viewport and scissor rectangles.
    If not specified it will assume the target is the GraphicsDevice which was passed to
    :ref:`Canvas.create <Canvas_create>`.

``viewportRect``
    An optional array of numbers specifying the destination viewport rectangle on the target.
    The format is similar to that used by :ref:`setViewport  <graphicsdevice_setviewport>`.
    It defaults to the size of ``target``.

.. index::
    pair: CanvasContext; path

.. _CanvasContext_path:

`path`
------

**Summary**

Adds the given `SVG path string <http://www.w3.org/TR/SVG/paths.html>`_ to the current path.

**Syntax** ::

    canvas2dContext.beginPath();
    canvas2dContext.path("M 100 100 L 300 100 L 200 300 z");
    canvas2dContext.fillStyle = "red";
    canvas2dContext.fill();

.. index::
    pair: CanvasContext; endFrame

.. _CanvasContext_endFrame:

`endFrame`
----------

**Summary**

Signals the end of a render frame.

**Syntax** ::

    if (canvas2dContext.beginFrame(target, viewportRect))
    {
        canvas2dContext.endFrame();
    }

Properties
==========

.. index::
    pair: CanvasContext; version

`version`
---------

**Summary**

The version number of the CanvasContext implementation.

**Syntax** ::

    var ctxVersionNumber = ctx.version;

.. index::
    pair: canvascontext; imageColor

`imageColor`
------------

**summary**

The tint color to be applied to images when using `drawImage`,
opaque white by default.

**syntax** ::

    ctx.imageColor = "red";
    ctx.drawImage(image, 100, 100);


text:
import java.util.function.Function;

class Example {
  void test() {
    Function<? super Integer, Float> firstFunction = null;
    Function<Float, String> secondFunction = null;
    Function<? super Integer, String> function = firstFunction.andThen(secondFunction);
  }
}


text:
import unittest
from cpuinfo import *
import helpers

class TestCLI(unittest.TestCase):
	def setUp(self):
		helpers.backup_data_source(cpuinfo)

	def tearDown(self):
		helpers.restore_data_source(cpuinfo)

	def test_json(self):
		from subprocess import Popen, PIPE
		import json

		command = [sys.executable, 'cpuinfo/cpuinfo.py', '--json']
		p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
		output = p1.communicate()[0]

		self.assertEqual(0, p1.returncode)

		output = output.decode(encoding='UTF-8')

		info = json.loads(output, object_hook = cpuinfo._utf_to_str)

		self.assertEqual(list(cpuinfo.CPUINFO_VERSION), info['cpuinfo_version'])
		self.assertEqual(cpuinfo.CPUINFO_VERSION_STRING, info['cpuinfo_version_string'])

	def test_version(self):
		from subprocess import Popen, PIPE

		command = [sys.executable, 'cpuinfo/cpuinfo.py', '--version']
		p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
		output = p1.communicate()[0]

		self.assertEqual(0, p1.returncode)

		output = output.decode(encoding='UTF-8')
		output = output.strip()

		self.assertEqual(cpuinfo.CPUINFO_VERSION_STRING, output)

	def test_trace(self):
		import os
		import re
		from subprocess import Popen, PIPE

		# Get all log files before test
		before_log_files = [f for f in os.listdir('.') if os.path.isfile(f) and re.match(r'^cpuinfo_trace_\d+-\d+-\d+_\d+-\d+-\d+-\d+.trace$', f)]
		#print('\n', before_log_files)

		# Run with trace to generate new log file
		command = [sys.executable, 'cpuinfo/cpuinfo.py', '--trace']
		p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
		output = p1.communicate()[0]
		self.assertEqual(0, p1.returncode)

		# Get all log files after test
		after_log_files = [f for f in os.listdir('.') if os.path.isfile(f) and re.match(r'^cpuinfo_trace_\d+-\d+-\d+_\d+-\d+-\d+-\d+.trace$', f)]
		#print('\n', after_log_files)

		# Read the new log file into a string
		new_log_file = list(set(after_log_files) - set(before_log_files))[0]
		with open(new_log_file, 'r') as f:
			output = f.read().strip()

		# Remove the new log file
		os.remove(new_log_file)

		self.assertTrue(len(output) > 200)
		self.assertTrue(output.startswith('!' * 80))
		self.assertTrue(output.endswith('!' * 80))

	def test_default(self):
		from subprocess import Popen, PIPE

		command = [sys.executable, 'cpuinfo/cpuinfo.py']
		p1 = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE)
		output = p1.communicate()[0]

		self.assertEqual(0, p1.returncode)

		output = output.decode(encoding='UTF-8')

		version = output.split('Cpuinfo Version: ')[1].split('\n')[0].strip()

		self.assertEqual(cpuinfo.CPUINFO_VERSION_STRING, version)


text:
<?php

namespace Sylius\Bundle\ContentBundle\Form\Type;

use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * MenuNode block type.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class MenuNodeType extends AbstractResourceType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array(
                'required' => true,
                'label' => 'sylius.form.menu_node_block.internal_name'
            ))
            ->add('label', 'text', array(
                'required' => true,
                'label' => 'sylius.form.menu_node_block.label'
            ))
            ->add('display', null, array(
                'label' => 'sylius.form.menu_node_block.display'
            ))
            ->add('displayChildren', null, array(
                'label' => 'sylius.form.menu_node_block.display_children'
            ))
            ->add('linkType', 'choice', array(
                'required' => false,
                'choices' => array (
                        'auto' => 'auto',
                        'uri' => 'sylius.form.menu_node_block.uri',
                        'route' => 'route',
                        'content' => 'sylius.form.menu_node_block.content'
                ),
                'label'    => 'sylius.form.menu_node_block.link_type',
            ))
            ->add('publishable', null, array(
                'required' => false,
                'label'    => 'sylius.form.menu_node_block.publishable',
            ))
            ->add('publishStartDate', 'text', array(
                'attr'      => array('class'=> 'datepicker'),
                'required'  => false,
                'label'     => 'sylius.form.menu_node_block.publish_start_date',
            ))
            ->add('publishEndDate', 'text', array(
                'required' => false,
                'label'    => 'sylius.form.menu_node_block.publish_end_date',
            ))
            ->add('route', null, array(
                'label' => 'sylius.form.menu_node_block.route'
            ))
            ->add('content', null, array(
                'class' => 'Symfony\Cmf\Bundle\ContentBundle\Model\StaticContent',
                'property' => 'title',
                'label' => 'sylius.form.menu_node_block.content',
                'required' => false
             ))
            ->add('uri', null, array(
                'label' => 'sylius.form.menu_node_block.uri'
            ))
            ;

    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sylius_menu_node';
    }
}


text:
@interface GosConfigWaiting : UIViewController

@end


text:
@interface MaskViewController : EditorViewController <UIGestureRecognizerDelegate, UIScrollViewDelegate>

- (id)initWithImage:(UIImage*)image;

@end


text:
EXECUTABLE	:= SobolQRNG

# CUDA source files (compiled with cudacc)
CUFILES         := sobol_gpu.cu

# CUDA dependency files
CU_DEPS		:= \
	sobol_gpu.h \
	sobol.h

# C/C++ source files (compiled with gcc / c++)
CCFILES		:= sobol.cpp sobol_gold.cpp sobol_primitives.cpp

################################################################################
# Rules and targets

include ../../common/common.mk


text:
package androidx.room;

import androidx.annotation.RestrictTo;
import androidx.arch.core.executor.ArchTaskExecutor;

import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.Maybe;
import io.reactivex.MaybeSource;
import io.reactivex.Scheduler;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;

/**
 * Helper class to add RxJava2 support to Room.
 */
@SuppressWarnings("WeakerAccess")
public class RxRoom {
    /**
     * Data dispatched by the publisher created by {@link #createFlowable(RoomDatabase, String...)}.
     */
    public static final Object NOTHING = new Object();

    /**
     * Creates a {@link Flowable} that emits at least once and also re-emits whenever one of the
     * observed tables is updated.
     *

     * You can easily chain a database operation to downstream of this {@link Flowable} to ensure
     * that it re-runs when database is modified.
     *

     * Since database invalidation is batched, multiple changes in the database may results in just
     * 1 emission.
     *
     * @param database   The database instance
     * @param tableNames The list of table names that should be observed
     * @return A {@link Flowable} which emits {@link #NOTHING} when one of the observed tables
     * is modified (also once when the invalidation tracker connection is established).
     */
    public static Flowable<Object> createFlowable(final RoomDatabase database,
            final String... tableNames) {
        return Flowable.create(new FlowableOnSubscribe<Object>() {
            @Override
            public void subscribe(final FlowableEmitter<Object> emitter) throws Exception {
                final InvalidationTracker.Observer observer = new InvalidationTracker.Observer(
                        tableNames) {
                    @Override
                    public void onInvalidated(@androidx.annotation.NonNull Set<String> tables) {
                        if (!emitter.isCancelled()) {
                            emitter.onNext(NOTHING);
                        }
                    }
                };
                if (!emitter.isCancelled()) {
                    database.getInvalidationTracker().addObserver(observer);
                    emitter.setDisposable(Disposables.fromAction(new Action() {
                        @Override
                        public void run() throws Exception {
                            database.getInvalidationTracker().removeObserver(observer);
                        }
                    }));
                }

                // emit once to avoid missing any data and also easy chaining
                if (!emitter.isCancelled()) {
                    emitter.onNext(NOTHING);
                }
            }
        }, BackpressureStrategy.LATEST);
    }

    /**
     * Helper method used by generated code to bind a Callable such that it will be run in
     * our disk io thread and will automatically block null values since RxJava2 does not like null.
     *
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static <T> Flowable<T> createFlowable(final RoomDatabase database,
            final String[] tableNames, final Callable<T> callable) {
        final Maybe<T> maybe = Maybe.fromCallable(callable);
        return createFlowable(database, tableNames).observeOn(sAppToolkitIOScheduler)
                .flatMapMaybe(new Function<Object, MaybeSource<T>>() {
                    @Override
                    public MaybeSource<T> apply(Object o) throws Exception {
                        return maybe;
                    }
                });
    }

    private static Scheduler sAppToolkitIOScheduler = new Scheduler() {
        @Override
        public Worker createWorker() {
            final AtomicBoolean mDisposed = new AtomicBoolean(false);
            return new Worker() {
                @Override
                public Disposable schedule(@NonNull Runnable run, long delay,
                        @NonNull TimeUnit unit) {
                    DisposableRunnable disposable = new DisposableRunnable(run, mDisposed);
                    ArchTaskExecutor.getInstance().executeOnDiskIO(run);
                    return disposable;
                }

                @Override
                public void dispose() {
                    mDisposed.set(true);
                }

                @Override
                public boolean isDisposed() {
                    return mDisposed.get();
                }
            };
        }
    };

    private static class DisposableRunnable implements Disposable, Runnable {
        private final Runnable mActual;
        private volatile boolean mDisposed = false;
        private final AtomicBoolean mGlobalDisposed;

        DisposableRunnable(Runnable actual, AtomicBoolean globalDisposed) {
            mActual = actual;
            mGlobalDisposed = globalDisposed;
        }

        @Override
        public void dispose() {
            mDisposed = true;
        }

        @Override
        public boolean isDisposed() {
            return mDisposed || mGlobalDisposed.get();
        }

        @Override
        public void run() {
            if (!isDisposed()) {
                mActual.run();
            }
        }
    }

    /** @deprecated This type should not be instantiated as it contains only static methods. */
    @Deprecated
    @SuppressWarnings("PrivateConstructorForUtilityClass")
    public RxRoom() {
    }
}


text:
RSpec.describe DataSource do
  describe 'name' do
    let(:data_source) { build(:data_source_odk) }

    it 'saves a valid data source' do
      data_source.save!
    end

    it 'requires a name' do
      data_source.name = nil
      expect(data_source).not_to be_valid
    end

    it 'strips the name after save' do
      name = data_source.name
      data_source.name += " \t\n"
      data_source.save!
      expect(data_source.name).to eq(name)
    end

    it 'invalidates unsupported settings' do
      data_source.settings['unsupported_setting'] = 'invalid'
      expect(data_source).not_to be_valid
    end
  end

  describe 'Odk' do
    let(:data_source) { build(:data_source_odk) }

    it 'saves a valid data source' do
      data_source.save!
    end

    it 'requires a form ID' do
      data_source.form_id = nil
      expect(data_source).not_to be_valid
    end
  end
end


text:
package org.hisp.dhis.user;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.MergeMode;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.schema.annotation.PropertyRange;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Nguyen Hong Duc
 */
@JacksonXmlRootElement( localName = "userRole", namespace = DxfNamespaces.DXF_2_0 )
public class UserAuthorityGroup
    extends BaseIdentifiableObject
{
    public static final String AUTHORITY_ALL = "ALL";

    public static final String[] CRITICAL_AUTHS = { "ALL", "F_SCHEDULING_ADMIN", "F_SYSTEM_SETTING",
        "F_SQLVIEW_PUBLIC_ADD", "F_SQLVIEW_PRIVATE_ADD", "F_SQLVIEW_DELETE", "F_SQLVIEW_EXECUTE",
        "F_SQLVIEW_MANAGEMENT", "F_USERROLE_PUBLIC_ADD", "F_USERROLE_PRIVATE_ADD", "F_USERROLE_DELETE",
        "F_USERROLE_LIST" };

    /**
     * Required and unique.
     */
    private String description;

    private Set<String> authorities = new HashSet<>();

    private Set<UserCredentials> members = new HashSet<>();

    private Set<DataSet> dataSets = new HashSet<>();

    private Set<Program> programs = new HashSet<>();

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    public UserAuthorityGroup()
    {

    }

    // -------------------------------------------------------------------------
    // Logic
    // -------------------------------------------------------------------------

    public void addUserCredentials( UserCredentials userCredentials )
    {
        members.add( userCredentials );
        userCredentials.getUserAuthorityGroups().add( this );
    }

    public void removeUserCredentials( UserCredentials userCredentials )
    {
        members.remove( userCredentials );
        userCredentials.getUserAuthorityGroups().remove( this );
    }

    public boolean isSuper()
    {
        return authorities != null && authorities.contains( AUTHORITY_ALL );
    }

    public boolean hasCriticalAuthorities()
    {
        return authorities != null && CollectionUtils.containsAny( authorities, Sets.newHashSet( CRITICAL_AUTHS ) );
    }

    public void addProgam( Program program )
    {
        programs.add( program );
        program.getUserRoles().add( this );
    }

    public boolean removeProgam( Program program )
    {
        programs.remove( program );
        return program.getUserRoles().remove( this );
    }

    // -------------------------------------------------------------------------
    // Getters and setters
    // -------------------------------------------------------------------------

    @Override
    public boolean isAutoGenerated()
    {
        return name != null && name.equals( "Superuser" );
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    @PropertyRange( min = 2 )
    public String getDescription()
    {
        return description;
    }

    public void setDescription( String description )
    {
        this.description = description;
    }

    @JsonProperty
    @JacksonXmlElementWrapper( localName = "authorities", namespace = DxfNamespaces.DXF_2_0 )
    @JacksonXmlProperty( localName = "authority", namespace = DxfNamespaces.DXF_2_0 )
    public Set<String> getAuthorities()
    {
        return authorities;
    }

    public void setAuthorities( Set<String> authorities )
    {
        this.authorities = authorities;
    }

    public Set<UserCredentials> getMembers()
    {
        return members;
    }

    public void setMembers( Set<UserCredentials> members )
    {
        this.members = members;
    }

    @JsonProperty
    @JsonSerialize( contentAs = BaseIdentifiableObject.class )
    @JacksonXmlElementWrapper( localName = "users", namespace = DxfNamespaces.DXF_2_0 )
    @JacksonXmlProperty( localName = "userObject", namespace = DxfNamespaces.DXF_2_0 )
    public List<User> getUsers()
    {
        List<User> users = new ArrayList<>();

        for ( UserCredentials userCredentials : members )
        {
            if ( userCredentials.getUserInfo() != null )
            {
                users.add( userCredentials.getUserInfo() );
            }
        }

        return users;
    }

    @JsonProperty
    @JsonSerialize( contentAs = BaseIdentifiableObject.class )
    @JacksonXmlElementWrapper( localName = "dataSets", namespace = DxfNamespaces.DXF_2_0 )
    @JacksonXmlProperty( localName = "dataSet", namespace = DxfNamespaces.DXF_2_0 )
    public Set<DataSet> getDataSets()
    {
        return dataSets;
    }

    public void setDataSets( Set<DataSet> dataSets )
    {
        this.dataSets = dataSets;
    }

    public void removeAllDataSets()
    {
        dataSets.clear();
    }

    private void removeAllAuthorities()
    {
        authorities.clear();
    }

    public void removeAllPrograms()
    {
        programs.clear();
    }

    @JsonProperty
    @JsonSerialize( contentAs = BaseIdentifiableObject.class )
    @JacksonXmlElementWrapper( localName = "programs", namespace = DxfNamespaces.DXF_2_0 )
    @JacksonXmlProperty( localName = "programs", namespace = DxfNamespaces.DXF_2_0 )
    public Set<Program> getPrograms()
    {
        return programs;
    }

    public void setPrograms( Set<Program> programs )
    {
        this.programs = programs;
    }

    @Override
    public void mergeWith( IdentifiableObject other, MergeMode mergeMode )
    {
        super.mergeWith( other, mergeMode );

        if ( other.getClass().isInstance( this ) )
        {
            UserAuthorityGroup userAuthorityGroup = (UserAuthorityGroup) other;

            if ( mergeMode.isReplace() )
            {
                description = userAuthorityGroup.getDescription();
            }
            else if ( mergeMode.isMerge() )
            {
                description = userAuthorityGroup.getDescription() == null ? description : userAuthorityGroup.getDescription();
            }

            removeAllAuthorities();
            authorities.addAll( ((UserAuthorityGroup) other).getAuthorities() );

            removeAllDataSets();
            dataSets.addAll( userAuthorityGroup.getDataSets() );

            removeAllPrograms();
            programs.addAll( userAuthorityGroup.getPrograms() );
        }
    }
}


text:
/*global define,dojo,esri */
/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */
/*
 | Copyright 2013 Esri
 |
 | Licensed under the Apache License, Version 2.0 (the "License");
 | you may not use this file except in compliance with the License.
 | You may obtain a copy of the License at
 |
 |    http://www.apache.org/licenses/LICENSE-2.0
 |
 | Unless required by applicable law or agreed to in writing, software
 | distributed under the License is distributed on an "AS IS" BASIS,
 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | See the License for the specific language governing permissions and
 | limitations under the License.
 */
//============================================================================================================================//
define([
    "dojo/_base/declare",
    "dojo/dom-construct",
    "dojo/_base/lang",
    "dojo/on",
    "dojo/dom",
    "dojo/text!./templates/baseMapGalleryTemplate.html",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin"

], function (declare, domConstruct, lang, on, dom, template, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin) {

    //========================================================================================================================//

    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
        templateString: template,

        /**
        * create baseMapGallery widget
        *
        * @class
        * @name widgets/baseMapGallery/baseMapGallery
        */
        postCreate: function () {
            var i, basemapContainer, layer,
                baseMapURL = 0,
                baseMapURLCount = 0,
                baseMapLayers = dojo.configData.BaseMapLayers;

            for (i = 0; i < baseMapLayers.length; i++) {
                if (baseMapLayers[i].MapURL) {
                    this.map.addLayer(this._createBaseMapLayer(baseMapLayers[i].MapURL, baseMapLayers[i].Key));
                    if (baseMapURLCount === 0) {
                        baseMapURL = i;
                    }
                    baseMapURLCount++;
                }
            }
            basemapContainer = domConstruct.create("div", {}, dom.byId("esriCTParentDivContainer"));
            basemapContainer.appendChild(this.esriCTDivLayerContainer);
            this.layerList.appendChild(this._createBaseMapElement(baseMapURL, baseMapURLCount));

            if (baseMapURLCount >= 1) {
                layer = this.map.getLayer(baseMapLayers[baseMapURL].Key);
                layer.show();
            }
        },

        /**
        * Create basemap layer on the map
        * @param {string} layer url for the basemap
        * @param {string} layer id for the basemap
        * @memberOf widgets/baseMapGallery/baseMapGallery
        */
        _createBaseMapLayer: function (layerURL, layerId) {
            var layer = new esri.layers.ArcGISTiledMapServiceLayer(layerURL, { id: layerId, visible: false });
            return layer;
        },

        /**
        * Create basemap images with respective titles
        * @param {string} layer url for the basemap
        * @param {integer} count of the basemaps configured in the config file
        * @return {object} divcontainer contains visible basemap image with respective title
        * @memberOf widgets/baseMapGallery/baseMapGallery
        */
        _createBaseMapElement: function (baseMapURL, baseMapURLCount) {
            var divContainer, imgThumbnail, i;

            divContainer = domConstruct.create("div", { "class": "esriCTbaseMapContainerNode" });
            imgThumbnail = domConstruct.create("img", { "class": "esriCTBasemapThumbnail", "src": dojo.configData.BaseMapLayers[baseMapURL + 1].ThumbnailSource }, null);
            imgThumbnail.setAttribute("index", 1);
            //Fix for creating basemap gallery as per configuration
            on(imgThumbnail, "click", lang.hitch(this, function () {
                for (i = 0; i < dojo.configData.BaseMapLayers.length; i++) {
                    if (parseInt(imgThumbnail.getAttribute("index"), 10) === i) {
                        this._changeBaseMap(dojo.configData.BaseMapLayers[i]);
                        if (i >= baseMapURLCount - 1) {
                            imgThumbnail.src = dojo.configData.BaseMapLayers[0].ThumbnailSource;
                            imgThumbnail.setAttribute("index", 0);
                        } else {
                            imgThumbnail.src = dojo.configData.BaseMapLayers[i + 1].ThumbnailSource;
                            imgThumbnail.setAttribute("index", i + 1);
                        }
                        break;
                    }
                }
            }));
            divContainer.appendChild(imgThumbnail);
            return divContainer;
        },

        /**
        * Toggle basemap layer
        * @param {object} contains current basemap object
        * @memberOf widgets/baseMapGallery/baseMapGallery
        */
        _changeBaseMap: function (basemap) {
            var baseMapLayer, allLayer = this.map.getLayersVisibleAtScale(), i;
            this._hideMapLayers();
            baseMapLayer = this.map.getLayer(basemap.Key);
            //Add boolean flag which will be used to identify the current basemap on map
            for (i = 0; i < allLayer.length; i++) {
                if (allLayer[i].url && baseMapLayer.url === allLayer[i].url) {
                    allLayer[i].isSelectedBaseMap = true;
                } else {
                    if (allLayer[i].hasOwnProperty("isSelectedBaseMap")) {
                        //If the basemap is not loaded, set flag to false
                        allLayer[i].isSelectedBaseMap = false;
                    }
                }
            }
            baseMapLayer.show();
        },

        /**
        * Hide layers
        * @memberOf widgets/baseMapGallery/baseMapGallery
        */
        _hideMapLayers: function () {
            var i, layer;

            for (i = 0; i < dojo.configData.BaseMapLayers.length; i++) {
                if (dojo.configData.BaseMapLayers[i].MapURL) {
                    layer = this.map.getLayer(dojo.configData.BaseMapLayers[i].Key);
                    if (layer) {
                        layer.hide();
                    }
                }
            }
        }

    });
});


text:
<bill session="115" type="sr" number="61" updated="2017-09-29T05:09:17Z">
  <state datetime="2017-02-15">REFERRED</state>
  <status>
    <introduced datetime="2017-02-15"/>
  </status>
  <introduced datetime="2017-02-15"/>
  <titles>
    <title type="official" as="introduced">A resolution calling on the Department of Defense, other elements of the Federal Government, and foreign governments to intensify efforts to investigate, recover, and identify all missing and unaccounted-for personnel of the United States.</title>
    <title type="display">A resolution calling on the Department of Defense, other elements of the Federal Government, and foreign governments to intensify efforts to investigate, recover, and identify all missing and unaccounted-for personnel of the United States.</title>
  </titles>
  <sponsor bioguide_id="M000303"/>
  <cosponsors>
    <cosponsor bioguide_id="C001056" joined="2017-09-12"/>
    <cosponsor bioguide_id="C001095" joined="2017-09-28"/>
    <cosponsor bioguide_id="C000880" joined="2017-06-29"/>
    <cosponsor bioguide_id="K000383" joined="2017-05-16"/>
    <cosponsor bioguide_id="P000595" joined="2017-09-11"/>
  </cosponsors>
  <actions>
    <action datetime="2017-02-15">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-02-15" state="REFERRED">
      <text>Referred to the Committee on Foreign Relations.</text>
      <reference ref="CR S1220-1221" label="text of measure as introduced"/>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSFR" name="Senate Foreign Relations" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="hr" session="115" relation="identical" number="129"/>
  </relatedbills>
  <subjects>
    <term name="Armed forces and national security"/>
    <term name="Conflicts and wars"/>
    <term name="Government studies and investigations"/>
    <term name="International organizations and cooperation"/>
    <term name="Military personnel and dependents"/>
  </subjects>
  <amendments/>
  <summary date="2017-02-15T05:00:00Z" status="Introduced in Senate">Calls upon: (1) the Defense POW/MIA Accounting Agency, other elements of the Department of Defense and the federal government, and all foreign governments to intensify efforts to investigate, recover, identify and account for all missing and unaccounted-for U.S. personnel; and (2) all foreign governments with information on missing U.S. personnel, or with missing U.S. personnel within their territories, to cooperate fully with the U.S. government to provide the fullest possible accounting for all missing U.S. personnel.</summary>
  <committee-reports/>
</bill>


text:
var Bear = require('./app/models/bear');

// db connection
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test'); // connect to our database

// call the packages we need
var express = require('express');        // call express
var app = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// middleware for all requests
router.use(function (req, res, next) {
    // log some shit
    console.log('SOMETHING IS HAPPENING');
    next(); // make sure we continue onto the next routes
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function (req, res) {
    res.json({message: 'hooray! welcome to ze api!'});
});

// more routes for our API will happen here

// on on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
// create a bear (POST http://localhost:8080/api/bears)
    .post(function (req, res) {
        var bear = new Bear(); // init a bear
        bear.name = req.body.name; // set bear's name
        // save bear, error check
        bear.save(function (err) {
            if (err)
                res.send(err);

            res.json({message: 'Bear created!'});
        });
    })

    // get all the bears (accessed at GET http://localhost:8080/api/bears)
    .get(function (req, res) {
        Bear.find(function (err, bears) {
            if (err)
                res.send(err);

            res.json(bears);
        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);


text:
#ifndef VIENNAFEM_LOG_INTERFACE_HPP
#define VIENNAFEM_LOG_INTERFACE_HPP

#include <vector>
#include "viennafem/forwards.h"

/** @file  viennafem/log/interface.hpp
    @brief Defines the runtime interface for a logger
*/

namespace viennafem
{
  /** @brief The common interface for all loggers
   *
   * @tparam InterfaceType   The ViennaMath runtime expression interface
   */
  template <typename InterfaceType>
  class logger_interface
  {
    protected:
      typedef viennamath::rt_equation<InterfaceType>  EquationType;

    public:
      virtual void write_strong_form(std::vector<EquationType> const & pdes) = 0;
      virtual void write_weak_form(std::vector<EquationType> const & pdes) = 0;
      virtual void write_coordinated_weak_form(std::vector<EquationType> const & pdes) = 0;
      virtual void write_transformed_weak_form(std::vector<EquationType> const & pdes) = 0;
      virtual void write_test_and_trial_space(std::vector<viennamath::expr> const & test_space,
                                      std::vector<viennamath::expr> const & trial_space) = 0;
      //void write_linear_solver_stats(solver_stats const & solver) = 0;
  };

}

#endif


text:
package org.tap4j.parser.issueGitHub17;

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

import java.io.File;

import org.junit.Test;
import org.tap4j.consumer.TapConsumer;
import org.tap4j.consumer.TapConsumerFactory;
import org.tap4j.model.TestResult;
import org.tap4j.model.TestSet;
import org.tap4j.parser.issue3406964.TestDirectives;

/*When parsing the TAP Stream below with a TAPConsumerFactory.makeTap13YamlConsumer, it seems that tap4j (using 4.0.4) does not hold onto the YAML diagnostic for anotherDummyTest. Note that it finds it correctly when there are no subtests, and the subtests themselves are handled correctly in the presence of the yaml, but it is not placing this value into the Map when there are subtests.

TAP version 13
1..2
  ---
    datetime: 20100101T000000
  ...
ok 1 - someDummyTest
  ---
    datetime: 20100101T000002
  ...
  1..5
  ok
  ok
  ok
  ok
  ok
ok 2 - anotherDummyTest
  ---
    datetime: 20100101T000005
  ...
  1..1
  ok*/
/**
 * Stream with subtests chopping off last yaml diagnostic
 * @since 4.0.5
 */
public class TestLastYamlishBeingCut {

    @Test
    public void testLastYamlishBeingCut() {
        TapConsumer tapConsumer = TapConsumerFactory.makeTap13YamlConsumer();
        TestSet testSet = tapConsumer.load(new File(TestDirectives.class
            .getResource("/org/tap4j/parser/issueGitHub17/issue-17-tap-stream.tap")
            .getFile()));

        assertEquals(2, testSet.getTestResults().size());

        TestResult tr1 = testSet.getTestResult(1);
        TestSet tr1Subtest = tr1.getSubtest();
        assertNotNull(tr1Subtest);
        assertEquals(5, tr1Subtest.getTestResults().size());

        TestResult tr2 = testSet.getTestResult(2);
        TestSet tr2Subtest = tr2.getSubtest();
        assertNotNull(tr2Subtest);
        assertEquals(1, tr2Subtest.getTestResults().size());

        assertEquals(1, tr2.getDiagnostic().size());

        TestResult tr2_1 = tr2Subtest.getTestResult(1);
        assertNotNull(tr2_1);
    }

}


text:
(function (app) {
  'use strict';

  app.registerModule('portfolios');
})(ApplicationConfiguration);