text:
{% load i18n %}
{% get_available_languages as languages %}

                    <button type="button" class="close" data-dismiss="modal">
                        ×
                    </button>

                        {% trans 'Create questionset' %}
                        {% trans 'Copy questionset' %}
                        {% trans 'Update questionset' %}

                            {% trans 'Please enter the values for the copy of the question set below and change at least the key.' %}

                            {% trans 'Other properties can be changed once the new question set is created.' %}

                                    {{ meta.Question.uri_prefix.verbose_name }}

                                    <input class="form-control"
                                           id="questionset_uri_prefix"
                                           type="text"
                                           ng-model="service.values.uri_prefix" />

                                        <button type="button" class="btn btn-default"
                                            title="{% trans 'Insert default URI Prefix' %}"
                                            ng-click="service.values.uri_prefix = service.settings.default_uri_prefix">

                                        </button>

                                    {{ meta.Question.uri_prefix.help_text }}

                                        {$ error $}

                            <formgroup
                                data-id="questionset_key"
                                data-type="text"
                                data-label="{{ meta.Question.key.verbose_name }}"
                                data-help="{% trans 'The internal identifier of this questionset.' %}"
                                data-model="service.values.key"
                                data-errors="service.errors.key">
                            </formgroup>

                        <formgroup
                            data-id="questionset_section"
                            data-type="selectnumber"
                            data-label="{{ meta.QuestionSet.section.verbose_name }}"
                            data-help="{{ meta.QuestionSet.section.help_text }}"
                            data-model="service.values.section"
                            data-errors="service.errors.section"
                            data-options="service.sections"
                            data-options-label="uri"
                            data-options-null="1"
                            data-quicksearch="true">
                        </formgroup>
                        <formgroup
                            data-id="questionset_questionset"
                            data-type="selectnumber"
                            data-label="{{ meta.QuestionSet.questionset.verbose_name }}"
                            data-help="{{ meta.QuestionSet.questionset.help_text }}"
                            data-model="service.values.questionset"
                            data-errors="service.errors.questionset"
                            data-options="service.questionsets"
                            data-options-label="uri"
                            data-options-null="1"
                            data-quicksearch="true">
                        </formgroup>

                        <formgroup
                            data-id="questionset_comment"
                            data-type="textarea"
                            data-label="{{ meta.QuestionSet.comment.verbose_name }}"
                            data-help="{% trans 'Additional internal information about this questionset.' %}"
                            data-model="service.values.comment"
                            data-errors="service.errors.comment">
                        </formgroup>
                        <formgroup
                            data-id="questionset_locked"
                            data-type="checkbox"
                            data-label="{{ meta.QuestionSet.locked.verbose_name }}"
                            data-help="{{ meta.QuestionSet.locked.help_text }}"
                            data-model="service.values.locked"
                            data-errors="service.errors.locked">
                        </formgroup>

                                        {% trans 'General' %}

                                {% for lang_code, lang in languages %}
                                <li role="presentation" ng-class="{
                                        'has-error':
                                            service.errors.title_{{ lang_code }} ||
                                            service.errors.help_{{ lang_code }} ||
                                            service.errors.verbose_name_{{ lang_code }} ||
                                            service.errors.verbose_name_plural_{{ lang_code }},
                                        'has-warning':
                                            service.values.id && !service.values.title_{{ lang_code }}
                                    }">

                                        {{ lang }}

                                {% endfor %}

                                        {% trans 'Conditions' %}

                                            <formgroup
                                                data-id="questionset_section"
                                                data-type="selectnumber"
                                                data-label="{{ meta.QuestionSet.section.verbose_name }}"
                                                data-help="{{ meta.QuestionSet.section.help_text }}"
                                                data-model="service.values.section"
                                                data-errors="service.errors.section"
                                                data-options="service.sections"
                                                data-options-label="uri"
                                                data-options-null="1"
                                                data-quicksearch="true">
                                            </formgroup>

                                            <formgroup
                                                data-id="questionset_order"
                                                data-type="number"
                                                data-label="{{ meta.QuestionSet.order.verbose_name }}"
                                                data-help="{{ meta.QuestionSet.order.help_text }}"
                                                data-model="service.values.order"
                                                data-errors="service.errors.order">
                                            </formgroup>

                                            <formgroup
                                                data-id="questionset_questionset"
                                                data-type="selectnumber"
                                                data-label="{{ meta.QuestionSet.questionset.verbose_name }}"
                                                data-help="{{ meta.QuestionSet.questionset.help_text }}"
                                                data-model="service.values.questionset"
                                                data-errors="service.errors.questionset"
                                                data-options="service.questionsets"
                                                data-options-label="uri"
                                                data-options-null="1"
                                                data-quicksearch="true">
                                            </formgroup>

                                            <formgroup
                                                data-id="questionset_attribute"
                                                data-type="selectnumber"
                                                data-label="{{ meta.QuestionSet.attribute.verbose_name }}"
                                                data-help="{{ meta.QuestionSet.attribute.help_text }}"
                                                data-model="service.values.attribute"
                                                data-errors="service.errors.attribute"
                                                data-options="service.attributes"
                                                data-options-label="uri"
                                                data-options-null="1"
                                                data-quicksearch="true">
                                            </formgroup>

                                            <formgroup
                                                data-id="questionset_is_collection"
                                                data-type="checkbox"
                                                data-label="{{ meta.QuestionSet.is_collection.verbose_name }}"
                                                data-help="{{ meta.QuestionSet.is_collection.help_text }}"
                                                data-model="service.values.is_collection"
                                                data-errors="service.errors.is_collection">
                                            </formgroup>

                                {% for lang_code, lang in languages %}

                                            <formgroup
                                                data-id="questionset_title_{{ lang_code }}"
                                                data-type="text"
                                                data-label="{% trans 'Title' %} ({{ lang }})"
                                                data-help="{% trans 'The title for this question set.' %}"
                                                data-model="service.values.title_{{ lang_code }}"
                                                data-errors="service.errors.title_{{ lang_code }}"
                                                data-warning="service.values.id && !service.values.title_{{ lang_code }}">
                                            </formgroup>

                                            <formgroup
                                                data-id="questionset_help_{{ lang_code }}"
                                                data-type="textarea"
                                                data-label="{% trans 'Help' %} ({{ lang }})"
                                                data-help="{% trans 'The help text for this question set.' %}"
                                                data-model="service.values.help_{{ lang_code }}"
                                                data-errors="service.errors.help_{{ lang_code }}">
                                            </formgroup>

                                            <formgroup
                                                data-id="questionset_verbose_name_{{ lang_code }}"
                                                data-type="text"
                                                data-label="{% trans 'Verbose name' %} ({{ lang }})"
                                                data-help="{% trans 'The verbose name for this question set.' %}"
                                                data-model="service.values.verbose_name_{{ lang_code }}"
                                                data-errors="service.errors.verbose_name_{{ lang_code }}">
                                            </formgroup>

                                            <formgroup
                                                data-id="questionset_verbose_name_plural_{{ lang_code }}"
                                                data-type="text"
                                                data-label="{% trans 'Verbose name plural' %} ({{ lang }})"
                                                data-help="{% trans 'The plural verbose name for this question set.' %}"
                                                data-model="service.values.verbose_name_plural_{{ lang_code }}"
                                                data-errors="service.errors.verbose_name_plural_{{ lang_code }}">
                                            </formgroup>

                                {% endfor %}

                                    <formgroup
                                        data-id="questionset_conditions"
                                        data-type="selectmultiple"
                                        data-label="{% trans 'Conditions' %}"
                                        data-model="service.values.conditions"
                                        data-errors="service.errors.conditions"
                                        data-options="service.conditions"
                                        data-options-label="uri"
                                        data-help="{% trans 'Hold down Control, or Command on a Mac, to select more than one.' %}">
                                    </formgroup>

                    <button type="button" class="btn btn-default" data-dismiss="modal">
                        {% trans 'Close' %}
                    </button>
                    <button type="button" class="btn btn-primary"
                            ng-click="service.submitFormModal('questionsets')">
                        {% trans 'Copy' %}
                        {% trans 'Save' %}
                    </button>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.amoraesdev.mobify</groupId>
	<artifactId>mobify-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>mobify-server</name>
	<description>Mobify is a enterprise mobile notification application. This module is the notification server. </description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-cassandra</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-oauth2</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.restdocs</groupId>
			<artifactId>spring-restdocs-mockmvc</artifactId>
		</dependency>
		<dependency>
			<groupId>com.datastax.cassandra</groupId>
			<artifactId>cassandra-driver-mapping</artifactId>
		</dependency>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
		<!-- runtime -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<!-- testing dependencies -->
		<dependency>
		    <groupId>com.jayway.jsonpath</groupId>
		    <artifactId>json-path</artifactId>
		    <scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Camden.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

redpajama_set_name: RedPajamaGithub


text:
require 'socket'
require 'chef/config'
require 'chef/exceptions'
require 'chef/log'
require 'chef/platform'
require 'mixlib/cli'
require 'tmpdir'
require 'rbconfig'

class Chef::Application
  include Mixlib::CLI

  class Wakeup < Exception
  end

  def initialize
    super

    trap("TERM") do
      Chef::Application.fatal!("SIGTERM received, stopping", 1)
    end

    trap("INT") do
      Chef::Application.fatal!("SIGINT received, stopping", 2)
    end

    unless Chef::Platform.windows?
      trap("QUIT") do
        Chef::Log.info("SIGQUIT received, call stack:\n  " + caller.join("\n  "))
      end

      trap("HUP") do
        Chef::Log.info("SIGHUP received, reconfiguring")
        reconfigure
      end
    end

    # Always switch to a readable directory. Keeps subsequent Dir.chdir() {}
    # from failing due to permissions when launched as a less privileged user.
  end

  # Reconfigure the application. You'll want to override and super this method.
  def reconfigure
    configure_chef
    configure_logging
  end

  # Get this party started
  def run
    reconfigure
    setup_application
    run_application
  end

  # Parse the configuration file
  def configure_chef
    parse_options

    begin
      case config[:config_file]
      when /^(http|https):\/\//
        Chef::REST.new("", nil, nil).fetch(config[:config_file]) { |f| apply_config(f.path) }
      else
        ::File::open(config[:config_file]) { |f| apply_config(f.path) }
      end
    rescue Errno::ENOENT => error
      Chef::Log.warn("*****************************************")
      Chef::Log.warn("Did not find config file: #{config[:config_file]}, using command line options.")
      Chef::Log.warn("*****************************************")

      Chef::Config.merge!(config)
    rescue SocketError => error
      Chef::Application.fatal!("Error getting config file #{Chef::Config[:config_file]}", 2)
    rescue Chef::Exceptions::ConfigurationError => error
      Chef::Application.fatal!("Error processing config file #{Chef::Config[:config_file]} with error #{error.message}", 2)
    rescue Exception => error
      Chef::Application.fatal!("Unknown error processing config file #{Chef::Config[:config_file]} with error #{error.message}", 2)
    end

  end

  # Initialize and configure the logger. If the configured log location is not
  # STDOUT, but stdout is a TTY and we're not daemonizing, we set up a secondary
  # logger with output to stdout. This way, we magically do the right thing when
  # the user has configured logging to a file but they're running chef in the
  # shell to debug something.
  #
  # If the user has configured a formatter, then we skip the magical logger to
  # keep the output pretty.
  def configure_logging
    require 'pp'
    Chef::Log.init(Chef::Config[:log_location])
    if ( Chef::Config[:log_location] != STDOUT ) && STDOUT.tty? && (!Chef::Config[:daemonize]) && (Chef::Config.formatter == "null")
      stdout_logger = Logger.new(STDOUT)
      STDOUT.sync = true
      stdout_logger.formatter = Chef::Log.logger.formatter
      Chef::Log.loggers <<  stdout_logger
    end
    Chef::Log.level = Chef::Config[:log_level]
  end

  # Called prior to starting the application, by the run method
  def setup_application
    raise Chef::Exceptions::Application, "#{self.to_s}: you must override setup_application"
  end

  # Actually run the application
  def run_application
    raise Chef::Exceptions::Application, "#{self.to_s}: you must override run_application"
  end

  private

  def apply_config(config_file_path)
    Chef::Config.from_file(config_file_path)
    Chef::Config.merge!(config)
  end

  class << self
    def debug_stacktrace(e)
      message = "#{e.class}: #{e}\n#{e.backtrace.join("\n")}"
      chef_stacktrace_out = "Generated at #{Time.now.to_s}\n"
      chef_stacktrace_out += message

      Chef::FileCache.store("chef-stacktrace.out", chef_stacktrace_out)
      Chef::Log.fatal("Stacktrace dumped to #{Chef::FileCache.load("chef-stacktrace.out", false)}")
      Chef::Log.debug(message)
      true
    end

    # Log a fatal error message to both STDERR and the Logger, exit the application
    def fatal!(msg, err = -1)
      Chef::Log.fatal(msg)
      Process.exit err
    end

    def exit!(msg, err = -1)
      Chef::Log.debug(msg)
      Process.exit err
    end
  end

end


text:
Utility for managing scores in a challenge/grest and presenting them as a PPT slideshow.

This is a personal project started long time ago and developed for many years. This repository has been recently created in order to start working on it again, perfectioning it and making it available for general use.

The original idea was to use it for keeping track of scores during Grest (Gruppi Estivi). Techinically this project can be used to manage scores in any type of tournament.

## Features
* Manage multiple Grests (tournaments):
  * Set up some players with name, identifying color, avatar
  * Manage scores organized by days and games (partials and penalties)
* Print reports
* Export/Import grests
* Generate a slideshow for showing how the Grest/Tournament is going on
* Easy-to-use GUI for managing the process

## Planned improvements
* Refactor the project in order to make it Maven-based
* Review presentation layer in order to simplify the creation of new slideshows
* Bug-fixing


text:
require 'open-uri'

module SpatialFeatures
  module Importers
    class File < SimpleDelegator
      INVALID_ARCHIVE = "Archive did not contain a .kml, .shp, .json, or .geojson file.".freeze
      SUPPORTED_FORMATS = "Supported formats are KMZ, KML, zipped ArcGIS shapefiles, ESRI JSON, and GeoJSON.".freeze

      FILE_PATTERNS = [/\.kml$/, /\.shp$/, /\.json$/, /\.geojson$/]
      def self.create_all(data, **options)
        Download.open_each(data, unzip: FILE_PATTERNS, downcase: true, tmpdir: options[:tmpdir]).map do |file|
          new(data, **options, current_file: file)
        end
      rescue Unzip::PathNotFound
        raise ImportError, INVALID_ARCHIVE + " " + SUPPORTED_FORMATS
      end

      # The File importer may be initialized multiple times by `::create_all` if it
      # receives ZIP data containing multiple KML or SHP files. We use `current_file`
      # to distinguish which file in the archive is currently being
      # processed.
      #
      # If no `current_file` is passed then we just take the first valid file that we find.
      def initialize(data, current_file: nil, **options)
        begin
          current_file ||= Download.open_each(data, unzip: FILE_PATTERNS, downcase: true, tmpdir: options[:tmpdir]).first
        rescue Unzip::PathNotFound
          raise ImportError, INVALID_ARCHIVE
        end

        case ::File.extname(current_file.path.downcase)
        when '.kml'
          __setobj__(KMLFile.new(current_file, **options))
        when '.shp'
          __setobj__(Shapefile.new(current_file, **options))
        when '.json', '.geojson'
          __setobj__(ESRIGeoJSON.new(current_file.path, **options))
        else
          raise ImportError, "Could not import file. " + SUPPORTED_FORMATS
        end
      end
    end
  end
end


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('immunization', 'Unit | Model | Immunization', {
  needs: [
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension',
    'model:identifier',
    'model:codeable-concept',
    'model:reference',
    'model:quantity',
    'model:immunization-practitioner',
    'model:annotation',
    'model:immunization-explanation',
    'model:immunization-reaction',
    'model:immunization-vaccination-protocol'
  ]
});

test('it exists', function(assert) {
  const model = this.subject();
  assert.ok(!!model);
});


text:
namespace viz {
class RendererSettings;
}  // namespace viz

namespace viz {

VIZ_HOST_EXPORT RendererSettings CreateRendererSettings();

}  // namespace viz

#endif  // COMPONENTS_VIZ_HOST_RENDERER_SETTINGS_CREATION_H_


text:
package net.unicon.cas.passwordmanager.flow;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.unicon.cas.passwordmanager.InvalidPasswordException;
import net.unicon.cas.passwordmanager.service.PasswordManagerService;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.ldap.NameNotFoundException;

/**
 *
Changes the user's password.

 */
public class ProcessChangePasswordAction {

	private final Log logger = LogFactory.getLog(this.getClass());
	private PasswordManagerService passwordManagerService;

	public boolean changePassword(String flowScopeUsername, String beanUsername, String oldPassword, String password,
			MessageContext messageContext) throws Exception {

		// prefer a username found in the flow scope to one found in the bean
		String username = flowScopeUsername != null ? flowScopeUsername : beanUsername;

		if(username == null) {
			messageContext.addMessage(new MessageBuilder().error().source("username")
					.code("cas.pm.username.empty")
					.defaultText("Please enter your NetID")
					.build());
			logger.debug("No username found changing password.");
			return false;
		}

		try {
			passwordManagerService.changeUserPassword(username, oldPassword, password);
		} catch(InvalidPasswordException ex) {
			messageContext.addMessage(new MessageBuilder().error().source("oldPassword")
					.code("cas.pm.oldPassword.invalid")
					.defaultText("Username/password combination incorrect")
					.build());
			logger.debug("InvalidPasswordException changing password for user.");
			return false;
		} catch(NameNotFoundException ex) {
			messageContext.addMessage(new MessageBuilder().error().source("oldPassword")
					.code("cas.pm.oldPassword.invalid")
					.defaultText("Username/password combination incorrect")
					.build());
			logger.debug("NameNotFoundException changing password for user " + username);
			return false;
		} catch(Exception ex) {
			logger.error("Unknown exception changing user's password.",ex);
			return false;
		}

		return true;
	}

	public boolean setPassword(String username, String password,
			MessageContext messageContext) throws Exception {

		try {
			passwordManagerService.setUserPassword(username, password);
		} catch(Exception ex) {
			logger.error("Unknown exception changing user's password.",ex);
			return false;
		}

		return true;
	}

	public boolean changePassword(String username, String oldPassword,
			String newPassword) throws Exception {

		try {
			passwordManagerService.changeUserPassword(username, oldPassword, newPassword);
		} catch(Exception ex) {
			logger.error("Exception changing user's password.");
			return false;
		}
		return true;
	}

	public void setPasswordManagerService(
			PasswordManagerService passwordManagerService) {
		this.passwordManagerService = passwordManagerService;
	}

}


text:
package com.mcxtzhang.commonadapter.rv;

import android.support.v7.widget.RecyclerView;

/**
 * 介绍:新HeaderFooter Adapter,优化头部数据绑定 参考DataBinding思想 分离数据绑定 和 View层
 * 作者:zhangxutong
 * 邮箱:mcxtzhang@163.com
 * 主页:http://blog.csdn.net/zxt0601
 * 时间: 17/01/08.
 */

public class HeaderFooterAdapter extends HeaderRecyclerAndFooterWrapperAdapter {
    public HeaderFooterAdapter(RecyclerView.Adapter mInnerAdapter) {
        super(mInnerAdapter);
    }

    /**
     * 添加HeaderView
     */
    public void addHeaderView(IHeaderHelper headerHelper) {
        mHeaderDatas.add(new HeaderData(headerHelper.getItemLayoutId(), headerHelper));
    }

    /**
     * 添加HeaderView
     *
     * @param cacheSize 该种headerView在缓存池中的缓存个数
     */
    public void addHeaderView(IHeaderHelper headerHelper, int cacheSize) {
        mHeaderDatas.add(new HeaderData(headerHelper.getItemLayoutId(), headerHelper, cacheSize));
    }

    /**
     * 设置某个位置的HeaderView
     *
     * @param headerPos 从0开始,如果pos过大 就是addHeaderview
     */
    public void setHeaderView(int headerPos, IHeaderHelper headerHelper) {
        if (mHeaderDatas.size() > headerPos) {
            mHeaderDatas.get(headerPos).setLayoutId(headerHelper.getItemLayoutId());
            mHeaderDatas.get(headerPos).setData(headerHelper);
        } else if (mHeaderDatas.size() == headerPos) {//调用addHeaderView
            addHeaderView(headerHelper);
        } else {
            //
            addHeaderView(headerHelper);
        }
    }

    /**
     * 设置某个位置的HeaderView
     *
     * @param headerPos 从0开始,如果pos过大 就是addHeaderview
     * @param cacheSize 该种headerView在缓存池中的缓存个数
     */
    public void setHeaderView(int headerPos, IHeaderHelper headerHelper, int cacheSize) {
        if (mHeaderDatas.size() > headerPos) {
/*            SparseArrayCompat headerContainer = new SparseArrayCompat();
            headerContainer.put(layoutId, data);
            mHeaderDatas.setValueAt(headerPos, headerContainer);*/
            mHeaderDatas.get(headerPos).setLayoutId(headerHelper.getItemLayoutId());
            mHeaderDatas.get(headerPos).setData(headerHelper);
            mHeaderDatas.get(headerPos).setCacheSize(cacheSize);
        } else if (mHeaderDatas.size() == headerPos) {//调用addHeaderView
            addHeaderView(headerHelper, cacheSize);
        } else {
            //
            addHeaderView(headerHelper, cacheSize);
        }
    }

    @Override
    protected void onBindHeaderHolder(ViewHolder holder, int headerPos, int layoutId, Object o) {
        if (o instanceof IHeaderHelper) {
            IHeaderHelper headerHelper = (IHeaderHelper) o;
            headerHelper.onBind(holder);
        }
    }
}


text:
This example deploys MPI operator into kubeflow cluster and runs an distributed training example using GPU.

## Steps

* Deploy [kubeflow cluster (version v0.7.0)](https://www.kubeflow.org/docs/gke/deploy/)
* Add GPU node pool to newly created kubeflow cluster (might need to increase quotas if needed):
```
export PROJECT=
export CLUSTER=
gcloud container node-pools create gpu-pool-mpi --accelerator=type=nvidia-tesla-k80,count=4 --cluster=$CLUSTER --project=$PROJECT --machine-type=n1-standard-8 --num-nodes=2
```
* Deploy MPI operator into kubeflow cluster: from [kubeflow manifests](https://github.com/kubeflow/manifests) repo, run
```
kustomize build mpi-job/mpi-operator/base/ | kubectl apply -f -
```
* Deploy the MPI exmaple job:
```
kubectl apply -f mpi-job.yaml -n kubeflow
```
* Once launcher pod is up and running, log will be available from:
```
POD_NAME=$(kubectl -n kubeflow get pods -l mpi_job_name=tf-resnet50-horovod-job,mpi_role_type=launcher -o name)
kubectl -n kubeflow logs -f ${POD_NAME}
```


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2015 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <org.chromium.components.browser_ui.settings.TextMessagePreference
        android:key="page_description"
        app:iconSpaceReserved="false"
        android:summary="@string/website_settings_permissions_description"/>
    <org.chromium.components.browser_ui.settings.ChromeBasePreference
        android:key="os_permissions_warning" />
    <org.chromium.components.browser_ui.settings.ChromeBasePreference
        android:key="os_permissions_warning_extra" />
    <Preference
        android:selectable="false"
        android:key="os_permissions_warning_divider"
        android:layout="@layout/divider_preference" />
    <org.chromium.components.browser_ui.settings.TextMessagePreference
        android:key="intrusive_ads_info"
        android:title="@string/intrusive_ads_information"
        android:icon="@drawable/btn_info"
        app:iconTint="@macro/default_icon_color" />
    <Preference
        android:selectable="false"
        android:key="intrusive_ads_info_divider"
        android:layout="@layout/divider_preference" />
    <PreferenceCategory
        android:key="site_heading"
        android:title="@string/website_settings_site_category" />
    <org.chromium.components.browser_ui.settings.TextMessagePreference
        android:key="site_title" />
    <PreferenceCategory
        android:key="site_usage"
        android:title="@string/website_settings_usage_category" />
    <org.chromium.components.browser_ui.site_settings.ClearWebsiteStorage
        android:key="clear_data"
        android:title="@string/webstorage_clear_data_dialog_title"
        android:positiveButtonText="@string/webstorage_clear_data_dialog_ok_button"
        android:negativeButtonText="@string/cancel"
        android:widgetLayout="@layout/clear_storage" />
    <PreferenceCategory
        android:key="related_sites_header"
        android:title="@string/website_settings_related_sites" />
    <org.chromium.components.browser_ui.settings.TextMessagePreference
        android:key="related_sites" />
    <PreferenceCategory
        android:key="site_permissions"
        android:title="@string/website_settings_permissions_category" />

    <org.chromium.components.browser_ui.settings.ButtonPreference
        android:key="reset_site_button" />
</PreferenceScreen>


text:
package com.zuoxiaolong.niubi.job.console.controller;

import com.zuoxiaolong.niubi.job.service.MasterSlaveNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Xiaolong Zuo
 * @since 0.9.3
 */
@Controller
@RequestMapping("/masterSlaveNodes")
public class MasterSlaveNodeController extends AbstractController {

    @Autowired
    private MasterSlaveNodeService masterSlaveNodeService;

    @RequestMapping(value = "")
    public String list(Model model) {
        model.addAttribute("nodes", masterSlaveNodeService.getAllNodes());
        return "master_slave_node_list";
    }

}


text:
mod.define('Identifier', function() {
  var
    objects,

  extend = function(arg) {
    Object.defineProperty(arg, '_id', {
      enumerable: false,
      value: function() {
        var id = this.__id__;
        if (id == undefined) {
          Object.defineProperty(this, '__id__', {
            enumerable: false,
            writable: false,
            value: (id = objects.length)
          });
          objects.push(this);
        }
        return id;
      }
    });
  };

  if (!window.top.__objects__) {
    Object.defineProperty(window.top, '__objects__', {
      enumerable: false,
      writable: false,
      value: [undefined]
    });
  }

  objects = window.top.__objects__;

  extend(Object.prototype);

  return {
    getobject: function(id) {
      if (typeof(id) == 'number') {
        return objects[id];
      }
    },
    objectid: function(object) {
      if (!object._id)
        extend(object);
      return object._id();
    }
  };
});


text:
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Totem.Timeline.Client
{
  /// <summary>
  /// Describes the notification of connections interested in changed queries
  /// </summary>
  public interface IQueryNotifier
  {
    Task NotifyChanged(QueryETag etag, IEnumerable<Id> connectionIds);

    Task NotifyStopped(QueryETag etag, string error, IEnumerable<Id> connectionIds);
  }
}


text:
<!-- ignore the following lines, they are not important to this demo -->
<jigsaw-demo-description [summary]="summary" [content]="description">
</jigsaw-demo-description>

<!-- start to learn the demo from here -->
<jigsaw-mobile-input #input [password]="true"
              placeholder="输入密码">
</jigsaw-mobile-input>


text:
package br.com.crescer.aula4.entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "PRODUTOMATERIAL")
@NamedQueries({
    @NamedQuery(name = "ProdutoMaterial.findAll",
            query = "SELECT prodMat FROM ProdutoMaterial prodMat")
})
public class ProdutoMaterial implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SQ_PRODUTOMATERIAL")
    @SequenceGenerator(name = "SQ_PRODUTOMATERIAL", sequenceName = "SQ_PRODUTOMATERIAL", allocationSize = 1)
    @Basic(optional = false)
    @Column(name = "IDPRODUTOMATERIAL")
    private Long idProdutoMaterial;

    @Basic(optional = false)
    @Column(name = "QUANTIDADE")
    private Integer quantidade;

    @ManyToOne(optional = false)
    @Basic(optional = false)
    @JoinColumn(name = "IDMATERIAL")
    private Material material;

    @ManyToOne(optional = false)
    @Basic(optional = false)
    @JoinColumn(name = "IDPRODUTO")
    private Produto produto;

    public Long getIdProdutoMaterial() {
        return idProdutoMaterial;
    }

    public void setIdProdutoMaterial(Long idProdutoMaterial) {
        this.idProdutoMaterial = idProdutoMaterial;
    }

    public Integer getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(Integer quantidade) {
        this.quantidade = quantidade;
    }

    public Material getMaterial() {
        return material;
    }

    public void setMaterial(Material material) {
        this.material = material;
    }

    public Produto getProduto() {
        return produto;
    }

    public void setProduto(Produto produto) {
        this.produto = produto;
    }

}


text:
namespace mscl {

public class PpsPulseInfo : global::System.IDisposable {
  private global::System.Runtime.InteropServices.HandleRef swigCPtr;
  protected bool swigCMemOwn;

  internal PpsPulseInfo(global::System.IntPtr cPtr, bool cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
  }

  internal static global::System.Runtime.InteropServices.HandleRef getCPtr(PpsPulseInfo obj) {
    return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
  }

  ~PpsPulseInfo() {
    Dispose(false);
  }

  public void Dispose() {
    Dispose(true);
    global::System.GC.SuppressFinalize(this);
  }

  protected virtual void Dispose(bool disposing) {
    lock(this) {
      if (swigCPtr.Handle != global::System.IntPtr.Zero) {
        if (swigCMemOwn) {
          swigCMemOwn = false;
          msclPINVOKE.delete_PpsPulseInfo(swigCPtr);
        }
        swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
      }
    }
  }

  public PpsPulseInfo() : this(msclPINVOKE.new_PpsPulseInfo(), true) {
    if (msclPINVOKE.SWIGPendingException.Pending) throw msclPINVOKE.SWIGPendingException.Retrieve();
  }

  public uint count {
    set {
      msclPINVOKE.PpsPulseInfo_count_set(swigCPtr, value);
      if (msclPINVOKE.SWIGPendingException.Pending) throw msclPINVOKE.SWIGPendingException.Retrieve();
    }
    get {
      uint ret = msclPINVOKE.PpsPulseInfo_count_get(swigCPtr);
      if (msclPINVOKE.SWIGPendingException.Pending) throw msclPINVOKE.SWIGPendingException.Retrieve();
      return ret;
    }
  }

  public uint lastTimeinMS {
    set {
      msclPINVOKE.PpsPulseInfo_lastTimeinMS_set(swigCPtr, value);
      if (msclPINVOKE.SWIGPendingException.Pending) throw msclPINVOKE.SWIGPendingException.Retrieve();
    }
    get {
      uint ret = msclPINVOKE.PpsPulseInfo_lastTimeinMS_get(swigCPtr);
      if (msclPINVOKE.SWIGPendingException.Pending) throw msclPINVOKE.SWIGPendingException.Retrieve();
      return ret;
    }
  }

}

}


text:
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.

using System;
using System.Text;
using System.Linq;

namespace UnitsNet
{
    /// <summary>
    ///     Represents the base dimensions of a quantity.
    /// </summary>
    public sealed class BaseDimensions
    {
        /// <inheritdoc />
        public BaseDimensions(int length, int mass, int time, int current, int temperature, int amount, int luminousIntensity)
        {
            Length = length;
            Mass = mass;
            Time = time;
            Current = current;
            Temperature = temperature;
            Amount = amount;
            LuminousIntensity = luminousIntensity;
        }

        /// <summary>
        /// Checks if the dimensions represent a base quantity.
        /// </summary>
        /// <returns>True if the dimensions represent a base quantity, otherwise false.</returns>
        public bool IsBaseQuantity()
        {
            var dimensionsArray = new[]{Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity};
            bool onlyOneEqualsOne = dimensionsArray.Where(dimension => dimension == 1).Take(2).Count() == 1;
            return onlyOneEqualsOne;
        }

        /// <summary>
        /// Checks if the dimensions represent a derived quantity.
        /// </summary>
        /// <returns>True if the dimensions represent a derived quantity, otherwise false.</returns>
        public bool IsDerivedQuantity()
        {
            return !IsBaseQuantity() && !IsDimensionless();
        }

        /// <summary>
        /// Checks if this base dimensions object represents a dimensionless quantity.
        /// </summary>
        /// <returns>True if this object represents a dimensionless quantity, otherwise false.</returns>
        public bool IsDimensionless()
        {
            return Equals(this, Dimensionless);
        }

        /// <inheritdoc />
        public override bool Equals(object obj)
        {
            if(!(obj is BaseDimensions))
                return false;

            var other = (BaseDimensions)obj;

            return Length == other.Length &&
                Mass == other.Mass &&
                Time == other.Time &&
                Current == other.Current &&
                Temperature == other.Temperature &&
                Amount == other.Amount &&
                LuminousIntensity == other.LuminousIntensity;
        }

        /// <inheritdoc />
        public override int GetHashCode()
        {
            return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode();
        }

        /// <summary>
        /// Get resulting dimensions after multiplying two dimensions, by performing addition of each dimension.
        /// </summary>
        /// <param name="right">Other dimensions.</param>
        /// <returns>Resulting dimensions.</returns>
        public BaseDimensions Multiply(BaseDimensions right)
        {
            if(right is null)
                throw new ArgumentNullException(nameof(right));

            return new BaseDimensions(
                Length + right.Length,
                Mass + right.Mass,
                Time + right.Time,
                Current + right.Current,
                Temperature + right.Temperature,
                Amount + right.Amount,
                LuminousIntensity + right.LuminousIntensity);
        }

        /// <summary>
        /// Get resulting dimensions after dividing two dimensions, by performing subtraction of each dimension.
        /// </summary>
        /// <param name="right">Other dimensions.</param>
        /// <returns>Resulting dimensions.</returns>
        public BaseDimensions Divide(BaseDimensions right)
        {
            if(right is null)
                throw new ArgumentNullException(nameof(right));

            return new BaseDimensions(
                Length - right.Length,
                Mass - right.Mass,
                Time - right.Time,
                Current - right.Current,
                Temperature - right.Temperature,
                Amount - right.Amount,
                LuminousIntensity - right.LuminousIntensity);
        }

        /// <inheritdoc />
        public override string ToString()
        {
            var sb = new StringBuilder();

            AppendDimensionString(sb, "Length", Length);
            AppendDimensionString(sb, "Mass", Mass);
            AppendDimensionString(sb, "Time", Time);
            AppendDimensionString(sb, "Current", Current);
            AppendDimensionString(sb, "Temperature", Temperature);
            AppendDimensionString(sb, "Amount", Amount);
            AppendDimensionString(sb, "LuminousIntensity", LuminousIntensity);

            return sb.ToString();
        }

        private static void AppendDimensionString(StringBuilder sb, string name, int value)
        {
            var absoluteValue = Math.Abs(value);

            if(absoluteValue > 0)
            {
                sb.AppendFormat("[{0}]", name);

                if(absoluteValue > 1)
                    sb.AppendFormat("^{0}", value);
            }
        }

        /// <summary>
        /// Gets the length dimensions (L).
        /// </summary>
        public int Length { get; }

        /// <summary>
        /// Gets the mass dimensions (M).
        /// </summary>
        public int Mass{ get; }

        /// <summary>
        /// Gets the time dimensions (T).
        /// </summary>
        public int Time{ get; }

        /// <summary>
        /// Gets the electric current dimensions (I).
        /// </summary>
        public int Current{ get; }

        /// <summary>
        /// Gets the temperature dimensions (Θ).
        /// </summary>
        public int Temperature{ get; }

        /// <summary>
        /// Gets the amount of substance dimensions (N).
        /// </summary>
        public int Amount{ get; }

        /// <summary>
        /// Gets the luminous intensity dimensions (J).
        /// </summary>
        public int LuminousIntensity{ get; }

        /// <summary>
        /// Represents a dimensionless (unitless) quantity.
        /// </summary>
        public static BaseDimensions Dimensionless { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 0);
    }
}


text:
require 'rails_admin/config/fields/types/has_many_association'

module RailsAdmin
  module Config
    module Fields
      module Types
        class HancockConnectable < RailsAdmin::Config::Fields::Types::HasManyAssociation

          RailsAdmin::Config::Fields::Types::register(self)
          include RailsAdmin::Engine.routes.url_helpers

          register_instance_option :partial do
            :hancock_connectable
          end

          register_instance_option :autocreate_page_attr do
            :hancock_connectable_autocreate_page
          end

          register_instance_option :allowed_methods do
            [method_name, autocreate_page_attr]
          end

          register_instance_option :associated_collection_scope do
            me = bindings[:object]
            Proc.new do |scope|
              scope.unconnected(me).enabled.sorted
            end
          end

        end
      end
    end
  end
end


text:
CREATE TABLE tpcds.inventory (
    inv_date_sk integer NOT NULL,
    inv_item_sk integer NOT NULL,
    inv_warehouse_sk integer NOT NULL,
    inv_quantity_on_hand integer
)
WITH (:E9_MEDIUM_STORAGE)
:DISTRIBUTED_BY
partition by range(inv_date_sk)
(start(2450815) INCLUSIVE end(2453005) INCLUSIVE every (28),
default partition outliers
);


text:
namespace llvm {
namespace orc {

/// @brief Compile-on-demand layer.
///
///   When a module is added to this layer a stub is created for each of its
/// function definitions. The stubs and other global values are immediately
/// added to the layer below. When a stub is called it triggers the extraction
/// of the function body from the original module. The extracted body is then
/// compiled and executed.
template <typename BaseLayerT, typename CompileCallbackMgrT,
          typename PartitioningFtor =
            std::function<std::set<Function*>(Function&)>>
class CompileOnDemandLayer {
private:

  // Utility class for MapValue. Only materializes declarations for global
  // variables.
  class GlobalDeclMaterializer : public ValueMaterializer {
  public:
    typedef std::set<const Function*> StubSet;

    GlobalDeclMaterializer(Module &Dst, const StubSet *StubsToClone = nullptr)
        : Dst(Dst), StubsToClone(StubsToClone) {}

    Value* materializeValueFor(Value *V) final {
      if (auto *GV = dyn_cast<GlobalVariable>(V))
        return cloneGlobalVariableDecl(Dst, *GV);
      else if (auto *F = dyn_cast<Function>(V)) {
        auto *ClonedF = cloneFunctionDecl(Dst, *F);
        if (StubsToClone && StubsToClone->count(F)) {
          GlobalVariable *FnBodyPtr =
            createImplPointer(*ClonedF->getType(), *ClonedF->getParent(),
                              ClonedF->getName() + "$orc_addr", nullptr);
          makeStub(*ClonedF, *FnBodyPtr);
          ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage);
          ClonedF->addFnAttr(Attribute::AlwaysInline);
        }
        return ClonedF;
      }
      // Else.
      return nullptr;
    }
  private:
    Module &Dst;
    const StubSet *StubsToClone;
  };

  typedef typename BaseLayerT::ModuleSetHandleT BaseLayerModuleSetHandleT;

  struct LogicalModuleResources {
    std::shared_ptr<Module> SourceModule;
    std::set<const Function*> StubsToClone;
  };

  struct LogicalDylibResources {
    typedef std::function<RuntimeDyld::SymbolInfo(const std::string&)>
      SymbolResolverFtor;
    SymbolResolverFtor ExternalSymbolResolver;
    PartitioningFtor Partitioner;
  };

  typedef LogicalDylib<BaseLayerT, LogicalModuleResources,
                       LogicalDylibResources> CODLogicalDylib;

  typedef typename CODLogicalDylib::LogicalModuleHandle LogicalModuleHandle;
  typedef std::list<CODLogicalDylib> LogicalDylibList;

public:
  /// @brief Handle to a set of loaded modules.
  typedef typename LogicalDylibList::iterator ModuleSetHandleT;

  /// @brief Construct a compile-on-demand layer instance.
  CompileOnDemandLayer(BaseLayerT &BaseLayer, CompileCallbackMgrT &CallbackMgr,
                       bool CloneStubsIntoPartitions)
      : BaseLayer(BaseLayer), CompileCallbackMgr(CallbackMgr),
        CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}

  /// @brief Add a module to the compile-on-demand layer.
  template <typename ModuleSetT, typename MemoryManagerPtrT,
            typename SymbolResolverPtrT>
  ModuleSetHandleT addModuleSet(ModuleSetT Ms,
                                MemoryManagerPtrT MemMgr,
                                SymbolResolverPtrT Resolver) {

    assert(MemMgr == nullptr &&
           "User supplied memory managers not supported with COD yet.");

    LogicalDylibs.push_back(CODLogicalDylib(BaseLayer));
    auto &LDResources = LogicalDylibs.back().getDylibResources();

    LDResources.ExternalSymbolResolver =
      [Resolver](const std::string &Name) {
        return Resolver->findSymbol(Name);
      };

    LDResources.Partitioner =
      [](Function &F) {
        std::set<Function*> Partition;
        Partition.insert(&F);
        return Partition;
      };

    // Process each of the modules in this module set.
    for (auto &M : Ms)
      addLogicalModule(LogicalDylibs.back(),
                       std::shared_ptr<Module>(std::move(M)));

    return std::prev(LogicalDylibs.end());
  }

  /// @brief Remove the module represented by the given handle.
  ///
  ///   This will remove all modules in the layers below that were derived from
  /// the module represented by H.
  void removeModuleSet(ModuleSetHandleT H) {
    LogicalDylibs.erase(H);
  }

  /// @brief Search for the given named symbol.
  /// @param Name The name of the symbol to search for.
  /// @param ExportedSymbolsOnly If true, search only for exported symbols.
  /// @return A handle for the given named symbol, if it exists.
  JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
    return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
  }

  /// @brief Get the address of a symbol provided by this layer, or some layer
  ///        below this one.
  JITSymbol findSymbolIn(ModuleSetHandleT H, const std::string &Name,
                         bool ExportedSymbolsOnly) {
    return H->findSymbol(Name, ExportedSymbolsOnly);
  }

private:

  void addLogicalModule(CODLogicalDylib &LD, std::shared_ptr<Module> SrcM) {

    // Bump the linkage and rename any anonymous/privote members in SrcM to
    // ensure that everything will resolve properly after we partition SrcM.
    makeAllSymbolsExternallyAccessible(*SrcM);

    // Create a logical module handle for SrcM within the logical dylib.
    auto LMH = LD.createLogicalModule();
    auto &LMResources =  LD.getLogicalModuleResources(LMH);
    LMResources.SourceModule = SrcM;

    // Create the GVs-and-stubs module.
    auto GVsAndStubsM = llvm::make_unique<Module>(
                          (SrcM->getName() + ".globals_and_stubs").str(),
                          SrcM->getContext());
    GVsAndStubsM->setDataLayout(SrcM->getDataLayout());
    ValueToValueMapTy VMap;

    // Process module and create stubs.
    // We create the stubs before copying the global variables as we know the
    // stubs won't refer to any globals (they only refer to their implementation
    // pointer) so there's no ordering/value-mapping issues.
    for (auto &F : *SrcM) {

      // Skip declarations.
      if (F.isDeclaration())
        continue;

      // Record all functions defined by this module.
      if (CloneStubsIntoPartitions)
        LMResources.StubsToClone.insert(&F);

      // For each definition: create a callback, a stub, and a function body
      // pointer. Initialize the function body pointer to point at the callback,
      // and set the callback to compile the function body.
      auto CCInfo = CompileCallbackMgr.getCompileCallback(SrcM->getContext());
      Function *StubF = cloneFunctionDecl(*GVsAndStubsM, F, &VMap);
      GlobalVariable *FnBodyPtr =
        createImplPointer(*StubF->getType(), *StubF->getParent(),
                          StubF->getName() + "$orc_addr",
                          createIRTypedAddress(*StubF->getFunctionType(),
                                               CCInfo.getAddress()));
      makeStub(*StubF, *FnBodyPtr);
      CCInfo.setCompileAction(
        [this, &LD, LMH, &F]() {
          return this->extractAndCompile(LD, LMH, F);
        });
    }

    // Now clone the global variable declarations.
    GlobalDeclMaterializer GDMat(*GVsAndStubsM);
    for (auto &GV : SrcM->globals())
      if (!GV.isDeclaration())
        cloneGlobalVariableDecl(*GVsAndStubsM, GV, &VMap);

    // Then clone the initializers.
    for (auto &GV : SrcM->globals())
      if (!GV.isDeclaration())
        moveGlobalVariableInitializer(GV, VMap, &GDMat);

    // Build a resolver for the stubs module and add it to the base layer.
    auto GVsAndStubsResolver = createLambdaResolver(
        [&LD](const std::string &Name) {
          return LD.getDylibResources().ExternalSymbolResolver(Name);
        },
        [](const std::string &Name) {
          return RuntimeDyld::SymbolInfo(nullptr);
        });

    std::vector<std::unique_ptr<Module>> GVsAndStubsMSet;
    GVsAndStubsMSet.push_back(std::move(GVsAndStubsM));
    auto GVsAndStubsH =
      BaseLayer.addModuleSet(std::move(GVsAndStubsMSet),
                             llvm::make_unique<SectionMemoryManager>(),
                             std::move(GVsAndStubsResolver));
    LD.addToLogicalModule(LMH, GVsAndStubsH);
  }

  static std::string Mangle(StringRef Name, const DataLayout &DL) {
    std::string MangledName;
    {
      raw_string_ostream MangledNameStream(MangledName);
      Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
    }
    return MangledName;
  }

  TargetAddress extractAndCompile(CODLogicalDylib &LD,
                                  LogicalModuleHandle LMH,
                                  Function &F) {
    Module &SrcM = *LD.getLogicalModuleResources(LMH).SourceModule;

    // If F is a declaration we must already have compiled it.
    if (F.isDeclaration())
      return 0;

    // Grab the name of the function being called here.
    std::string CalledFnName = Mangle(F.getName(), SrcM.getDataLayout());

    auto Partition = LD.getDylibResources().Partitioner(F);
    auto PartitionH = emitPartition(LD, LMH, Partition);

    TargetAddress CalledAddr = 0;
    for (auto *SubF : Partition) {
      std::string FName = SubF->getName();
      auto FnBodySym =
        BaseLayer.findSymbolIn(PartitionH, Mangle(FName, SrcM.getDataLayout()),
                               false);
      auto FnPtrSym =
        BaseLayer.findSymbolIn(*LD.moduleHandlesBegin(LMH),
                               Mangle(FName + "$orc_addr",
                                      SrcM.getDataLayout()),
                               false);
      assert(FnBodySym && "Couldn't find function body.");
      assert(FnPtrSym && "Couldn't find function body pointer.");

      TargetAddress FnBodyAddr = FnBodySym.getAddress();
      void *FnPtrAddr = reinterpret_cast<void*>(
          static_cast<uintptr_t>(FnPtrSym.getAddress()));

      // If this is the function we're calling record the address so we can
      // return it from this function.
      if (SubF == &F)
        CalledAddr = FnBodyAddr;

      memcpy(FnPtrAddr, &FnBodyAddr, sizeof(uintptr_t));
    }

    return CalledAddr;
  }

  template <typename PartitionT>
  BaseLayerModuleSetHandleT emitPartition(CODLogicalDylib &LD,
                                          LogicalModuleHandle LMH,
                                          const PartitionT &Partition) {
    auto &LMResources = LD.getLogicalModuleResources(LMH);
    Module &SrcM = *LMResources.SourceModule;

    // Create the module.
    std::string NewName = SrcM.getName();
    for (auto *F : Partition) {
      NewName += ".";
      NewName += F->getName();
    }

    auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
    M->setDataLayout(SrcM.getDataLayout());
    ValueToValueMapTy VMap;
    GlobalDeclMaterializer GDM(*M, &LMResources.StubsToClone);

    // Create decls in the new module.
    for (auto *F : Partition)
      cloneFunctionDecl(*M, *F, &VMap);

    // Move the function bodies.
    for (auto *F : Partition)
      moveFunctionBody(*F, VMap, &GDM);

    // Create memory manager and symbol resolver.
    auto MemMgr = llvm::make_unique<SectionMemoryManager>();
    auto Resolver = createLambdaResolver(
        [this, &LD, LMH](const std::string &Name) {
          if (auto Symbol = LD.findSymbolInternally(LMH, Name))
            return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
                                           Symbol.getFlags());
          return LD.getDylibResources().ExternalSymbolResolver(Name);
        },
        [this, &LD, LMH](const std::string &Name) {
          if (auto Symbol = LD.findSymbolInternally(LMH, Name))
            return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
                                           Symbol.getFlags());
          return RuntimeDyld::SymbolInfo(nullptr);
        });
    std::vector<std::unique_ptr<Module>> PartMSet;
    PartMSet.push_back(std::move(M));
    return BaseLayer.addModuleSet(std::move(PartMSet), std::move(MemMgr),
                                  std::move(Resolver));
  }

  BaseLayerT &BaseLayer;
  CompileCallbackMgrT &CompileCallbackMgr;
  LogicalDylibList LogicalDylibs;
  bool CloneStubsIntoPartitions;
};

} // End namespace orc.
} // End namespace llvm.

#endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H


text:
using namespace OpenZWave;

//-----------------------------------------------------------------------------
//	<TimeStamp::TimeStamp>
//	Constructor
//-----------------------------------------------------------------------------
TimeStamp::TimeStamp
(
):
	m_pImpl( new TimeStampImpl() )
{
}

//-----------------------------------------------------------------------------
//	<TimeStamp::~TimeStamp>
//	Destructor
//-----------------------------------------------------------------------------
TimeStamp::~TimeStamp
(
)
{
	delete m_pImpl;
}

//-----------------------------------------------------------------------------
//	<TimeStamp::SetTime>
//	Sets the timestamp to now, plus an offset in milliseconds
//-----------------------------------------------------------------------------
void TimeStamp::SetTime
(
	int32 _milliseconds	// = 0
)
{
	m_pImpl->SetTime( _milliseconds );
}

//-----------------------------------------------------------------------------
//	<TimeStamp::TimeRemaining>
//	Gets the difference between now and the timestamp time in milliseconds
//-----------------------------------------------------------------------------
int32 TimeStamp::TimeRemaining
(
)
{
	return m_pImpl->TimeRemaining();
}

//-----------------------------------------------------------------------------
//	<TimeStamp::GetAsString>
//	Return object as a string
//-----------------------------------------------------------------------------
string TimeStamp::GetAsString
(
)
{
	return m_pImpl->GetAsString();
}
//-----------------------------------------------------------------------------
//	<TimeStamp::operator->
//	Overload the subtract operator to get the difference between two
//	timestamps in milliseconds
//-----------------------------------------------------------------------------
int32 TimeStamp::operator-
(
	TimeStamp const& _other
)
{
	return (int32)(m_pImpl - _other.m_pImpl);
}


text:
class Foo extends Bar {
  override private foo1: string
  readonly private foo2: string;
  readonly private override foo3: string;
  private readonly override foo4: string;
}


text:
title: Ember Data v1.0.0-beta.19 Released
author: Stanley Stuart
tags: Ember Data, 2015, Version 1.x
responsive: true
---

Ember Data 1.0.0-beta.19 contains a lot of bugfixes from the comunity!
Thank you for helping us push toward a stable release of Ember Data!

## New Features

### Snapshots have changedAttributes

`changedAttributes`, which represents the changes that have happened
since the model was last synced with the server, are now available on
the snapshot in your adapters and serializers, instead of just on
`DS.Model` instances.

## Breaking Changes

### Passing Classes to Store Methods

Previously, you were allowed to pass a classes directly to store methods
like `store.push`:

```javascript
var record = store.push(App.Post, {id: 1});
```

While this isn't a very popular way and generally not recommended in the
documentation, it did remain the preferred way to do things in Ember
Data's tests for a long time. As we move toward to using Ember's
Dependency Injection framework for consistency, passing these classes
directly to store methods has been removed. Instead, you should pass a
dasherized string:

```javascript
var record = store.push('post', {id: 1});
```

To help you upgrade through this change easily, we've written an [Ember
Watson command](https://github.com/abuiles/ember-watson#ember-watsonconvert-ember-data-model-lookups).
You can use this command-line tool in both Ember-CLI projects and
"globals mode" style projects.

### Services depending on the store

In order to fix deprecations warning induced by Ember 1.12, the store service is now injected as an
[instanceInitializer](http://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_instance-initializers).
As a consequence, if you had initializers depending on the store, you should move
them to an instance initializer as well, and mark it as `after: 'ember-data'`.

## Important Deprecations

### Fixture Adapter Removed

Support for the Fixture Adapter has been deprecated. After some thought,
the Ember Data team decided it was not the right approach for
integration-style tests. We recommend using an AJAX/data transport
stubbing strategy like [Pretender](https://github.com/trek/pretender) or
[sinon](http://sinonjs.org/).

We'll be including docs on integration test strategies using Pretender in the
final release.

The Fixture Adapter now lives as an [addon](https://github.com/emberjs/ember-data-fixture-adapter).

## Internet Explorer 8

<s>This will be the last release to support Internet
Explorer 8. Future versions of Ember Data will not support Internet
Explorer 8</s>

Update:
[Ember Data 1.13](/blog/2015/06/18/ember-data-1-13-released.html) has
been released with support for IE8. Ember Data 1.13 is the last
version of Ember Data that supports IE8. Ember Data 2.0 supports IE9+.


text:
<?php

use Talal\LabelPrinter\Command;

class CutTest extends \PHPUnit_Framework_TestCase
{
    public function testFullCut()
    {
        $command = new Command\Cut(Command\Cut::FULL);

        $this->assertEquals('1b694301', bin2hex($command->read()));
    }

    public function testHalfCut()
    {
        $command = new Command\Cut(Command\Cut::HALF);

        $this->assertEquals('1b694302', bin2hex($command->read()));
    }

    public function testChainCut()
    {
        $command = new Command\Cut(Command\Cut::CHAIN);

        $this->assertEquals('1b694304', bin2hex($command->read()));
    }

    public function testSpecialCut()
    {
        $command = new Command\Cut(Command\Cut::SPECIAL);

        $this->assertEquals('1b694308', bin2hex($command->read()));
    }
}


text:
class Solution(object):
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if not inorder: return
        root = TreeNode(postorder[-1])
        i = 0
        while inorder[i] != postorder[-1]:
            i += 1
        root.left = self.buildTree(inorder[:i], postorder[:i])
        root.right = self.buildTree(inorder[i+1:], postorder[i:-1])
        return root


text:
ElixirPaymill
=============

** TODO: Add description **


text:
'use strict';

import * as assert from 'assert';
import { Selection } from 'vs/editor/common/core/selection';
import { Range } from 'vs/editor/common/core/range';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { SnippetSession } from 'vs/editor/contrib/snippet/browser/snippetSession';
import { ICommonCodeEditor } from 'vs/editor/common/editorCommon';
import { mockCodeEditor } from 'vs/editor/test/common/mocks/mockCodeEditor';
import { Model } from 'vs/editor/common/model/model';

suite('SnippetSession', function () {

	let editor: ICommonCodeEditor;
	let model: Model;

	function assertSelections(editor: ICommonCodeEditor, ...s: Selection[]) {
		for (const selection of editor.getSelections()) {
			const actual = s.shift();
			assert.ok(selection.equalsSelection(actual), `actual=${selection.toString()} <> expected=${actual.toString()}`);
		}
		assert.equal(s.length, 0);
	}

	setup(function () {
		model = Model.createFromString('function foo() {\n    console.log(a);\n}');
		editor = mockCodeEditor([], { model });
		editor.setSelections([new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5)]);
		assert.equal(model.getEOL(), '\n');
	});

	teardown(function () {
		model.dispose();
		editor.dispose();
	});

	test('normalize whitespace', function () {

		function assertNormalized(position: IPosition, input: string, expected: string): void {
			const actual = SnippetSession.adjustWhitespace(model, position, input);
			assert.equal(actual, expected);
		}

		assertNormalized(new Position(1, 1), 'foo', 'foo');
		assertNormalized(new Position(1, 1), 'foo\rbar', 'foo\nbar');
		assertNormalized(new Position(1, 1), 'foo\rbar', 'foo\nbar');
		assertNormalized(new Position(2, 5), 'foo\r\tbar', 'foo\n        bar');
		assertNormalized(new Position(2, 3), 'foo\r\tbar', 'foo\n      bar');
		assertNormalized(new Position(2, 5), 'foo\r\tbar\nfoo', 'foo\n        bar\n    foo');
	});

	test('adjust selection (overwrite[Before|After])', function () {

		let range = SnippetSession.adjustSelection(model, new Selection(1, 2, 1, 2), 1, 0);
		assert.ok(range.equalsRange(new Range(1, 1, 1, 2)));
		range = SnippetSession.adjustSelection(model, new Selection(1, 2, 1, 2), 1111, 0);
		assert.ok(range.equalsRange(new Range(1, 1, 1, 2)));
		range = SnippetSession.adjustSelection(model, new Selection(1, 2, 1, 2), 0, 10);
		assert.ok(range.equalsRange(new Range(1, 2, 1, 12)));
		range = SnippetSession.adjustSelection(model, new Selection(1, 2, 1, 2), 0, 10111);
		assert.ok(range.equalsRange(new Range(1, 2, 1, 17)));

	});

	test('text edits & selection', function () {
		const session = new SnippetSession(editor, 'foo${1:bar}foo$0');
		session.insert();
		assert.equal(editor.getModel().getValue(), 'foobarfoofunction foo() {\n    foobarfooconsole.log(a);\n}');

		assertSelections(editor, new Selection(1, 4, 1, 7), new Selection(2, 8, 2, 11));
		session.next();
		assertSelections(editor, new Selection(1, 10, 1, 10), new Selection(2, 14, 2, 14));
	});

	test('text edit with reversed selection', function () {

		const session = new SnippetSession(editor, '${1:bar}$0');
		editor.setSelections([new Selection(2, 5, 2, 5), new Selection(1, 1, 1, 1)]);

		session.insert();
		assert.equal(model.getValue(), 'barfunction foo() {\n    barconsole.log(a);\n}');
		assertSelections(editor, new Selection(2, 5, 2, 8), new Selection(1, 1, 1, 4));
	});

	test('snippets, repeated tabstops', function () {
		const session = new SnippetSession(editor, '${1:abc}foo${1:abc}$0');
		session.insert();
		assertSelections(editor,
			new Selection(1, 1, 1, 4), new Selection(1, 7, 1, 10),
			new Selection(2, 5, 2, 8), new Selection(2, 11, 2, 14),
		);
		session.next();
		assertSelections(editor,
			new Selection(1, 10, 1, 10),
			new Selection(2, 14, 2, 14),
		);
	});

	test('snippets, just text', function () {
		const session = new SnippetSession(editor, 'foobar');
		session.insert();
		assert.equal(model.getValue(), 'foobarfunction foo() {\n    foobarconsole.log(a);\n}');
		assertSelections(editor, new Selection(1, 7, 1, 7), new Selection(2, 11, 2, 11));
	});

	test('snippets, selections and new text with newlines', () => {

		const session = new SnippetSession(editor, 'foo\n\t${1:bar}\n$0');
		session.insert();

		assert.equal(editor.getModel().getValue(), 'foo\n    bar\nfunction foo() {\n    foo\n        bar\n    console.log(a);\n}');

		assertSelections(editor, new Selection(2, 5, 2, 8), new Selection(5, 9, 5, 12));

		session.next();
		assertSelections(editor, new Selection(3, 1, 3, 1), new Selection(6, 5, 6, 5));
	});

	test('snippets, selections -> next/prev', () => {

		const session = new SnippetSession(editor, 'f$1oo${2:bar}foo$0');
		session.insert();

		// @ $2
		assertSelections(editor, new Selection(1, 2, 1, 2), new Selection(2, 6, 2, 6));
		// @ $1
		session.next();
		assertSelections(editor, new Selection(1, 4, 1, 7), new Selection(2, 8, 2, 11));
		// @ $2
		session.prev();
		assertSelections(editor, new Selection(1, 2, 1, 2), new Selection(2, 6, 2, 6));
		// @ $1
		session.next();
		assertSelections(editor, new Selection(1, 4, 1, 7), new Selection(2, 8, 2, 11));
		// @ $0
		session.next();
		assertSelections(editor, new Selection(1, 10, 1, 10), new Selection(2, 14, 2, 14));
	});

	test('snippets, selections & typing', function () {
		const session = new SnippetSession(editor, 'f${1:oo}_$2_$0');
		session.insert();

		editor.trigger('test', 'type', { text: 'X' });
		session.next();
		editor.trigger('test', 'type', { text: 'bar' });

		// go back to ${2:oo} which is now just 'X'
		session.prev();
		assertSelections(editor, new Selection(1, 2, 1, 3), new Selection(2, 6, 2, 7));

		// go forward to $1 which is now 'bar'
		session.next();
		assertSelections(editor, new Selection(1, 4, 1, 7), new Selection(2, 8, 2, 11));

		// go to final tabstop
		session.next();
		assert.equal(model.getValue(), 'fX_bar_function foo() {\n    fX_bar_console.log(a);\n}');
		assertSelections(editor, new Selection(1, 8, 1, 8), new Selection(2, 12, 2, 12));
	});

	test('snippets, insert shorter snippet into non-empty selection', function () {
		model.setValue('foo_bar_foo');
		editor.setSelections([new Selection(1, 1, 1, 4), new Selection(1, 9, 1, 12)]);

		new SnippetSession(editor, 'x$0').insert();
		assert.equal(model.getValue(), 'x_bar_x');
		assertSelections(editor, new Selection(1, 2, 1, 2), new Selection(1, 8, 1, 8));
	});

	test('snippets, insert longer snippet into non-empty selection', function () {
		model.setValue('foo_bar_foo');
		editor.setSelections([new Selection(1, 1, 1, 4), new Selection(1, 9, 1, 12)]);

		new SnippetSession(editor, 'LONGER$0').insert();
		assert.equal(model.getValue(), 'LONGER_bar_LONGER');
		assertSelections(editor, new Selection(1, 7, 1, 7), new Selection(1, 18, 1, 18));
	});

	test('snippets, don\'t grow final tabstop', function () {
		model.setValue('foo_zzz_foo');
		editor.setSelection(new Selection(1, 5, 1, 8));
		const session = new SnippetSession(editor, '$1bar$0');
		session.insert();

		assertSelections(editor, new Selection(1, 5, 1, 5));
		editor.trigger('test', 'type', { text: 'foo-' });

		session.next();
		assert.equal(model.getValue(), 'foo_foo-bar_foo');
		assertSelections(editor, new Selection(1, 12, 1, 12));

		editor.trigger('test', 'type', { text: 'XXX' });
		assert.equal(model.getValue(), 'foo_foo-barXXX_foo');
		session.prev();
		assertSelections(editor, new Selection(1, 5, 1, 9));
		session.next();
		assertSelections(editor, new Selection(1, 15, 1, 15));
	});

	test('snippets, don\'t merge touching tabstops 1/2', function () {

		const session = new SnippetSession(editor, '$1$2$3$0');
		session.insert();
		assertSelections(editor, new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5));

		session.next();
		assertSelections(editor, new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5));

		session.next();
		assertSelections(editor, new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5));

		session.next();
		assertSelections(editor, new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5));

		session.prev();
		session.prev();
		session.prev();
		assertSelections(editor, new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5));
		editor.trigger('test', 'type', { text: '111' });

		session.next();
		editor.trigger('test', 'type', { text: '222' });

		session.next();
		editor.trigger('test', 'type', { text: '333' });

		session.next();
		assert.equal(model.getValue(), '111222333function foo() {\n    111222333console.log(a);\n}');
		assertSelections(editor, new Selection(1, 10, 1, 10), new Selection(2, 14, 2, 14));

		session.prev();
		assertSelections(editor, new Selection(1, 7, 1, 7), new Selection(2, 11, 2, 11));
		session.prev();
		assertSelections(editor, new Selection(1, 4, 1, 4), new Selection(2, 8, 2, 8));
		session.prev();
		assertSelections(editor, new Selection(1, 1, 1, 4), new Selection(2, 5, 2, 8));
	});
	test('snippets, don\'t merge touching tabstops 2/2', function () {

		const session = new SnippetSession(editor, '$1$2$3$0');
		session.insert();
		assertSelections(editor, new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5));

		editor.trigger('test', 'type', { text: '111' });

		session.next();
		assertSelections(editor, new Selection(1, 4, 1, 4), new Selection(2, 8, 2, 8));
		editor.trigger('test', 'type', { text: '222' });

		session.next();
		assertSelections(editor, new Selection(1, 7, 1, 7), new Selection(2, 11, 2, 11));
		editor.trigger('test', 'type', { text: '333' });

		session.next();
		assert.equal(session.isAtLastPlaceholder, true);
	});

	test('snippets, gracefully move over final tabstop', function () {
		const session = new SnippetSession(editor, '${1}bar$0');
		session.insert();

		assert.equal(session.isAtLastPlaceholder, false);
		assertSelections(editor, new Selection(1, 1, 1, 1), new Selection(2, 5, 2, 5));

		session.next();
		assert.equal(session.isAtLastPlaceholder, true);
		assertSelections(editor, new Selection(1, 4, 1, 4), new Selection(2, 8, 2, 8));

		session.next();
		assert.equal(session.isAtLastPlaceholder, true);
		assertSelections(editor, new Selection(1, 4, 1, 4), new Selection(2, 8, 2, 8));
	});

	test('snippets, overwriting nested placeholder', function () {
		const session = new SnippetSession(editor, 'log(${1:"$2"});$0');
		session.insert();
		assertSelections(editor, new Selection(1, 5, 1, 7), new Selection(2, 9, 2, 11));

		editor.trigger('test', 'type', { text: 'XXX' });
		assert.equal(model.getValue(), 'log(XXX);function foo() {\n    log(XXX);console.log(a);\n}');

		session.next();
		assert.equal(session.isAtLastPlaceholder, false);
		// assertSelections(editor, new Selection(1, 7, 1, 7), new Selection(2, 11, 2, 11));

		session.next();
		assert.equal(session.isAtLastPlaceholder, true);
		assertSelections(editor, new Selection(1, 10, 1, 10), new Selection(2, 14, 2, 14));
	});

	test('snippets, selections and snippet ranges', function () {
		const session = new SnippetSession(editor, '${1:foo}farboo${2:bar}$0');
		session.insert();
		assert.equal(model.getValue(), 'foofarboobarfunction foo() {\n    foofarboobarconsole.log(a);\n}');
		assertSelections(editor, new Selection(1, 1, 1, 4), new Selection(2, 5, 2, 8));

		assert.equal(session.isSelectionWithinPlaceholders(), true);

		editor.setSelections([new Selection(1, 1, 1, 1)]);
		assert.equal(session.isSelectionWithinPlaceholders(), false);

		editor.setSelections([new Selection(1, 6, 1, 6), new Selection(2, 10, 2, 10)]);
		assert.equal(session.isSelectionWithinPlaceholders(), false); // in snippet, outside placeholder

		editor.setSelections([new Selection(1, 6, 1, 6), new Selection(2, 10, 2, 10), new Selection(1, 1, 1, 1)]);
		assert.equal(session.isSelectionWithinPlaceholders(), false); // in snippet, outside placeholder

		editor.setSelections([new Selection(1, 6, 1, 6), new Selection(2, 10, 2, 10), new Selection(2, 20, 2, 21)]);
		assert.equal(session.isSelectionWithinPlaceholders(), false);

		// reset selection to placeholder
		session.next();
		assert.equal(session.isSelectionWithinPlaceholders(), true);
		assertSelections(editor, new Selection(1, 10, 1, 13), new Selection(2, 14, 2, 17));

		// reset selection to placeholder
		session.next();
		assert.equal(session.isSelectionWithinPlaceholders(), true);
		assert.equal(session.isAtLastPlaceholder, true);
		assertSelections(editor, new Selection(1, 13, 1, 13), new Selection(2, 17, 2, 17));
	});

	test('snippets, nested sessions', function () {

		model.setValue('');
		editor.setSelection(new Selection(1, 1, 1, 1));

		const first = new SnippetSession(editor, 'foo${2:bar}foo$0');
		first.insert();
		assert.equal(model.getValue(), 'foobarfoo');
		assertSelections(editor, new Selection(1, 4, 1, 7));

		const second = new SnippetSession(editor, 'ba${1:zzzz}$0');
		second.insert();
		assert.equal(model.getValue(), 'foobazzzzfoo');
		assertSelections(editor, new Selection(1, 6, 1, 10));

		second.next();
		assert.equal(second.isAtLastPlaceholder, true);
		assertSelections(editor, new Selection(1, 10, 1, 10));

		first.next();
		assert.equal(first.isAtLastPlaceholder, true);
		assertSelections(editor, new Selection(1, 13, 1, 13));
	});

	test('snippets, typing at final tabstop', function () {

		const session = new SnippetSession(editor, 'farboo$0');
		session.insert();
		assert.equal(session.isAtLastPlaceholder, true);
		assert.equal(session.isSelectionWithinPlaceholders(), false);

		editor.trigger('test', 'type', { text: 'XXX' });
		assert.equal(session.isSelectionWithinPlaceholders(), false);
	});

	test('snippets, typing at beginning', function () {

		editor.setSelection(new Selection(1, 2, 1, 2));
		const session = new SnippetSession(editor, 'farboo$0');
		session.insert();

		editor.setSelection(new Selection(1, 2, 1, 2));
		assert.equal(session.isSelectionWithinPlaceholders(), false);
		assert.equal(session.isAtLastPlaceholder, true);

		editor.trigger('test', 'type', { text: 'XXX' });
		assert.equal(model.getLineContent(1), 'fXXXfarboounction foo() {');
		assert.equal(session.isSelectionWithinPlaceholders(), false);

		session.next();
		assertSelections(editor, new Selection(1, 11, 1, 11));
	});

	test('snippets, typing with nested placeholder', function () {

		editor.setSelection(new Selection(1, 1, 1, 1));
		const session = new SnippetSession(editor, 'This ${1:is ${2:nested}}.$0');
		session.insert();
		assertSelections(editor, new Selection(1, 6, 1, 15));

		session.next();
		assertSelections(editor, new Selection(1, 9, 1, 15));

		editor.trigger('test', 'cut', {});
		assertSelections(editor, new Selection(1, 9, 1, 9));

		editor.trigger('test', 'type', { text: 'XXX' });
		session.prev();
		assertSelections(editor, new Selection(1, 6, 1, 12));
	});

	test('snippets, snippet with variables', function () {
		const session = new SnippetSession(editor, '@line=$TM_LINE_NUMBER$0');
		session.insert();

		assert.equal(model.getValue(), '@line=1function foo() {\n    @line=2console.log(a);\n}');
		assertSelections(editor, new Selection(1, 8, 1, 8), new Selection(2, 12, 2, 12));
	});

	test('snippets, merge', function () {
		editor.setSelection(new Selection(1, 1, 1, 1));
		const session = new SnippetSession(editor, 'This ${1:is ${2:nested}}.$0');
		session.insert();
		session.next();
		assertSelections(editor, new Selection(1, 9, 1, 15));

		session.merge('really ${1:nested}$0');
		assertSelections(editor, new Selection(1, 16, 1, 22));

		session.next();
		assertSelections(editor, new Selection(1, 22, 1, 22));
		assert.equal(session.isAtLastPlaceholder, false);

		session.next();
		assert.equal(session.isAtLastPlaceholder, true);
		assertSelections(editor, new Selection(1, 23, 1, 23));

		session.prev();
		editor.trigger('test', 'type', { text: 'AAA' });

		// back to `really ${1:nested}`
		session.prev();
		assertSelections(editor, new Selection(1, 16, 1, 22));

		// back to `${1:is ...}` which now grew
		session.prev();
		assertSelections(editor, new Selection(1, 6, 1, 25));
	});

	test('Snippet placeholder index incorrect after using 2+ snippets in a row that each end with a placeholder, #30769', function () {
		editor.getModel().setValue('');
		editor.setSelection(new Selection(1, 1, 1, 1));
		const session = new SnippetSession(editor, 'test ${1:replaceme}');
		session.insert();

		editor.trigger('test', 'type', { text: '1' });
		editor.trigger('test', 'type', { text: '\n' });
		assert.equal(editor.getModel().getValue(), 'test 1\n');

		session.merge('test ${1:replaceme}');
		editor.trigger('test', 'type', { text: '2' });
		editor.trigger('test', 'type', { text: '\n' });

		assert.equal(editor.getModel().getValue(), 'test 1\ntest 2\n');

		session.merge('test ${1:replaceme}');
		editor.trigger('test', 'type', { text: '3' });
		editor.trigger('test', 'type', { text: '\n' });

		assert.equal(editor.getModel().getValue(), 'test 1\ntest 2\ntest 3\n');

		session.merge('test ${1:replaceme}');
		editor.trigger('test', 'type', { text: '4' });
		editor.trigger('test', 'type', { text: '\n' });

		assert.equal(editor.getModel().getValue(), 'test 1\ntest 2\ntest 3\ntest 4\n');
	});

	test('Snippet variable text isn\'t whitespace normalised, #31124', function () {
		editor.getModel().setValue([
			'start',
			'\t\t-one',
			'\t\t-two',
			'end'
		].join('\n'));

		editor.getModel().updateOptions({ insertSpaces: false });
		editor.setSelection(new Selection(2, 2, 3, 7));

		new SnippetSession(editor, '
\n\t$TM_SELECTED_TEXT\n
$0').insert();

		let expected = [
			'start',
			'\t
',
			'\t\t\t-one',
			'\t\t\t-two',
			'\t
',
			'end'
		].join('\n');

		assert.equal(editor.getModel().getValue(), expected);

		editor.getModel().setValue([
			'start',
			'\t\t-one',
			'\t-two',
			'end'
		].join('\n'));

		editor.getModel().updateOptions({ insertSpaces: false });
		editor.setSelection(new Selection(2, 2, 3, 7));

		new SnippetSession(editor, '
\n\t$TM_SELECTED_TEXT\n
$0').insert();

		expected = [
			'start',
			'\t
',
			'\t\t\t-one',
			'\t\t-two',
			'\t
',
			'end'
		].join('\n');

		assert.equal(editor.getModel().getValue(), expected);
	});

	test('Selecting text from left to right, and choosing item messes up code, #31199', function () {
		const model = editor.getModel();
		model.setValue('console.log');

		let actual = SnippetSession.adjustSelection(model, new Selection(1, 12, 1, 9), 3, 0);
		assert.ok(actual.equalsSelection(new Selection(1, 9, 1, 6)));

		actual = SnippetSession.adjustSelection(model, new Selection(1, 9, 1, 12), 3, 0);
		assert.ok(actual.equalsSelection(new Selection(1, 9, 1, 12)));

		editor.setSelections([new Selection(1, 9, 1, 12)]);
		new SnippetSession(editor, 'far', 3, 0).insert();
		assert.equal(model.getValue(), 'console.far');
	});
});


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Org.BouncyCastle.Crypto;

namespace Org.BouncyCastle.Bcpg.OpenPgp
{
    public interface IPgpPublicKey
    {
        /// The version of this key.
        int Version { get; }

        /// The creation time of this key.
        DateTime CreationTime { get; }

        /// The number of valid days from creation time - zero means no expiry.
        int ValidDays { get; }

        /// The keyId associated with the public key.
        long KeyId { get; }

        ///
        /// Check if this key has an algorithm type that makes it suitable to use for encryption.
        ///
        /// <remarks>
        /// Note: with version 4 keys KeyFlags subpackets should also be considered when present for
        /// determining the preferred use of the key.
        /// </remarks>
        /// <returns>
        /// <c>true</c> if this key algorithm is suitable for encryption.
        /// </returns>
        bool IsEncryptionKey { get; }

        /// True, if this is a master key.
        bool IsMasterKey { get; }

        /// The algorithm code associated with the public key.
        PublicKeyAlgorithmTag Algorithm { get; }

        ///
        /// Gets the user identities.
        ///
        /// <value>
        /// The user identities.
        /// </value>
        string[] UserIdentities { get; }

        ///
        /// The public key packet
        ///
        /// <value>
        /// The public key packet.
        /// </value>
        IPublicKeyPacket PublicKeyPacket { get; }

        ITrustPacket TrustPaket { get; }

        IList<IPgpSignature> KeySigs { get; }

        IList Ids { get; }

        IList<ITrustPacket> IdTrusts { get; }

        IList<IList<IPgpSignature>> IdSigs { get; }

        IList<IPgpSignature> SubSigs { get; }

        /// The strength of the key in bits.
        int BitStrength { get; }

        /// Return the trust data associated with the public key, if present.
        /// <returns>A byte array with trust data, null otherwise.</returns>
        byte[] GetTrustData();

        /// The number of valid seconds from creation time - zero means no expiry.
        long GetValidSeconds();

        /// The fingerprint of the key
        byte[] GetFingerprint();

        /// The public key contained in the object.
        /// <returns>A lightweight public key.</returns>
        /// <exception cref="PgpException">If the key algorithm is not recognised.</exception>
        IAsymmetricKeyParameter GetKey();

        /// Allows enumeration of any user IDs associated with the key.
        /// <returns>An <c>IEnumerable</c> of <c>string</c> objects.</returns>
        IEnumerable GetUserIds();

        /// Allows enumeration of any user attribute vectors associated with the key.
        /// <returns>An <c>IEnumerable</c> of <c>PgpUserAttributeSubpacketVector</c> objects.</returns>
        IEnumerable<IPgpUserAttributeSubpacketVector> GetUserAttributes();

        /// Allows enumeration of any signatures associated with the passed in id.
        /// <param name="id">The ID to be matched.</param>
        /// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns>
        IEnumerable<IPgpSignature> GetSignaturesForId(string id);

        /// Allows enumeration of signatures associated with the passed in user attributes.
        /// <param name="userAttributes">The vector of user attributes to be matched.</param>
        /// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns>
        IEnumerable<IPgpSignature> GetSignaturesForUserAttribute(IPgpUserAttributeSubpacketVector userAttributes);

        /// Allows enumeration of signatures of the passed in type that are on this key.
        /// <param name="signatureType">The type of the signature to be returned.</param>
        /// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns>
        IEnumerable<IPgpSignature> GetSignaturesOfType(int signatureType);

        /// Allows enumeration of all signatures/certifications associated with this key.
        /// <returns>An <c>IEnumerable</c> with all signatures/certifications.</returns>
        IEnumerable<IPgpSignature> GetSignatures();

        byte[] GetEncoded();

        void Encode(Stream outStr);

        /// Check whether this (sub)key has a revocation signature on it.
        /// <returns>True, if this (sub)key has been revoked.</returns>
        bool IsRevoked();
    }
}


text:
using System.Collections.Generic;
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.EntityStateManagement;

using BEPUphysics.CollisionShapes.ConvexShapes;
using BEPUutilities;

namespace BEPUphysics.Entities.Prefabs
{
    /// <summary>
    /// Shape representing the sweeping of one entity through another.  Can collide and move.  After making an entity, add it to a Space so that the engine can manage it.
    /// </summary>
    public class MinkowskiSum : Entity<ConvexCollidable<MinkowskiSumShape>>
    {
        /// <summary>
        /// First entity in the sum.
        /// </summary>
        public Entity EntityA;

        /// <summary>
        /// Second entity in the sum.
        /// </summary>
        public Entity EntityB;

        private MinkowskiSum(OrientedConvexShapeEntry a, OrientedConvexShapeEntry b, float m)
            :base(new ConvexCollidable<MinkowskiSumShape>(new MinkowskiSumShape(a, b)), m)
        {
            Position = -CollisionInformation.Shape.LocalOffset;
        }

        private MinkowskiSum(OrientedConvexShapeEntry a, OrientedConvexShapeEntry b)
            : base(new ConvexCollidable<MinkowskiSumShape>(new MinkowskiSumShape(a, b)))
        {
            Position = -CollisionInformation.Shape.LocalOffset;
        }

        /// <summary>
        /// Constructs a dynamic minkowski sum.
        /// </summary>
        /// <param name="position">Position of the resulting shape.</param>
        /// <param name="a">First entity in the sum.</param>
        /// <param name="b">Second entity in the sum.</param>
        /// <param name="mass">Mass of the object.</param>
        public MinkowskiSum(Vector3 position, OrientedConvexShapeEntry a, OrientedConvexShapeEntry b, float mass)
            : this(a, b, mass)
        {
            Position = position;
        }

        /// <summary>
        /// Constructs a nondynamic minkowski sum of two entities.
        /// </summary>
        /// <param name="position">Position of the resulting shape.</param>
        /// <param name="a">First entity in the sum.</param>
        /// <param name="b">Second entity in the sum.</param>
        public MinkowskiSum(Vector3 position, OrientedConvexShapeEntry a, OrientedConvexShapeEntry b)
            : this(a, b)
        {
            Position = position;
        }

        /// <summary>
        /// Constructs a dynamic minkowski sum of two entities.
        /// </summary>
        /// <param name="motionState">Motion state specifying the entity's initial state.</param>
        /// <param name="a">First entity in the sum.</param>
        /// <param name="b">Second entity in the sum.</param>
        /// <param name="mass">Mass of the object.</param>
        public MinkowskiSum(MotionState motionState, OrientedConvexShapeEntry a, OrientedConvexShapeEntry b, float mass)
            : this(a, b, mass)
        {
            MotionState = motionState;
        }

        /// <summary>
        /// Constructs a nondynamic minkowski sum of two entities.
        /// </summary>
        /// <param name="motionState">Motion state specifying the entity's initial state.</param>
        /// <param name="a">First entity in the sum.</param>
        /// <param name="b">Second entity in the sum.</param>
        public MinkowskiSum(MotionState motionState, OrientedConvexShapeEntry a, OrientedConvexShapeEntry b)
            : this(a, b)
        {
            MotionState = motionState;
        }

        /// <summary>
        /// Constructs a dynamic minkowski sum entity.
        /// </summary>
        /// <param name="motionState">Motion state specifying the entity's initial state.</param>
        /// <param name="shapes">List of shapes to make the sum frmo.</param>
        /// <param name="mass">Mass of the object.</param>
        public MinkowskiSum(MotionState motionState, IList<OrientedConvexShapeEntry> shapes, float mass)
            : base(new ConvexCollidable<MinkowskiSumShape>(new MinkowskiSumShape(shapes)), mass)
        {
            MotionState = motionState;
        }

        /// <summary>
        /// Constructs a nondynamic minkowski sum.
        /// </summary>
        /// <param name="motionState">Motion state specifying the entity's initial state.</param>
        /// <param name="shapes">List of shapes to make the sum frmo.</param>
        public MinkowskiSum(MotionState motionState, IList<OrientedConvexShapeEntry> shapes)
            : base(new ConvexCollidable<MinkowskiSumShape>(new MinkowskiSumShape(shapes)))
        {
            MotionState = motionState;
        }

    }
}