text:
package vn.brine.haileader.exploratorysearch;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import vn.brine.haileader.exploratorysearch.fragments.FavoriteFragment;
import vn.brine.haileader.exploratorysearch.fragments.FragmentDrawer;
import vn.brine.haileader.exploratorysearch.fragments.HomeFragment;
import vn.brine.haileader.exploratorysearch.fragments.SettingFragment;

public class MainActivity extends AppCompatActivity
        implements FragmentDrawer.FragmentDrawerListener {
    public static final String TAG = MainActivity.class.getSimpleName();

    private static final int HOME_FRAGMENT = 0;
    private static final int FAVORITE_FRAGMENT = 1;
    private static final int SETTING_FRAGMENT = 2;

    private Toolbar mToolbar;
    private FragmentDrawer drawerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        drawerFragment = (FragmentDrawer)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);

        displayView(HOME_FRAGMENT);
    }

    @Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId){
            case R.id.action_settings:
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void displayView(int position){
        Fragment fragment = null;
        String title = getString(R.string.app_name);
        switch (position) {
            case HOME_FRAGMENT:
                fragment = new HomeFragment();
                title = getString(R.string.title_home);
                break;
            case FAVORITE_FRAGMENT:
                fragment = new FavoriteFragment();
                title = getString(R.string.title_favorites);
                break;
            case SETTING_FRAGMENT:
                fragment = new SettingFragment();
                title = getString(R.string.title_settings);
                break;
            default:
                break;
        }
        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.commit();
            getSupportActionBar().setTitle(title);
        }
    }
}


text:
if [[ $EUID -ne 0 ]]; then
	echo "You must be a root user"
	exit 1
fi

usage() {
	cat <<EOF
	usage: aws-ephemeral-format.sh [ OPTION ]

	Format and or mount ephemeral storage on boot.

	Add to /etc/rc.local before exit 0 (/etc/rc.local must exit 0)

	Note: Remember to chown the -m directory if your planing on writing
		to it via a user other than root.

	Options
	-t 		Partition type Linux Swap/Linux [ 82 | 83 ]
	-s 		Partition size in cylinders (required partition size in bytes divided by 8225697)
	-f 		File system format type [ swap | ext2 | ext3 | ext4 ]
	-m 		Mount location

EOF
}

while getopts "t:s:f:m:" opt; do
	case $opt in
		t)
			partitionTypeArg="$OPTARG" >&2
			;;
		s)
			partitionSizeArg="$OPTARG" >&2
			;;
		f)
			fileSystemFormatArg="$OPTARG" >&2
			;;
		m)
			mountLocationArg="$OPTARG" >&2
			;;
		\?)
			echo "Invalid option: -$OPTARG" >&2
			usage
			exit 1
			;;
		:)
			echo "backup.sh Requires an argument" >&2
			usage
			exit 1
			;;
	esac
done

#   ----------------------------------------------------------------
# 	Set function default function exist status
#			*** Do not modify ***
#   ----------------------------------------------------------------
createPartition_result=0
formatPartition_result=0
checkEphemeralStorage_result=0

PROGNAME=$(basename $0)

IFS="
"

function error_exit {
#	----------------------------------------------------------------
#	Function for exit due to fatal program error
#		Accepts 1 argument:
#			string containing descriptive error message
#	----------------------------------------------------------------

	echo "${PROGNAME}: ${1:-"Unknown Error"}" | tee >> $log
	cat $log
	exit 1
}

#   ----------------------------------------------------------------
#	Default log location
#   ----------------------------------------------------------------
log=/tmp/aws_ephemeral_format.log

#   ----------------------------------------------------------------
#	Cleanup log
#   ----------------------------------------------------------------
echo $date > $log

#   ----------------------------------------------------------------
#	Partition type is 82 (Linux Swap)
#	Change to 83 for Linux ext3/ext4
#   ----------------------------------------------------------------
if [ -z $partitionTypeArg ]; then
	error_exit "Partition type -t requires an argument!"
fi
partitionType="$partitionTypeArg"

#   ----------------------------------------------------------------
#	Partition size (disk cylinders) 1024 cylinders = 8032MB
#   ----------------------------------------------------------------
if [ -z $partitionSizeArg ]; then
	error_exit "Partition type -s requires an argument!"
fi
partitionSize="$partitionSizeArg"

#   ----------------------------------------------------------------
#	File system type. Supports: swap, ext2, ext3 & ext4
#   ----------------------------------------------------------------
if [ -z $fileSystemFormatArg ]; then
	error_exit "Partition type -f requires an argument!"
fi
fileSystemFormat="$fileSystemFormatArg"

#   ----------------------------------------------------------------
#	File system type. Supports: swap, ext2, ext3 & ext4
#   ----------------------------------------------------------------

if ! [[ $fileSystemFormat == swap ]]; then
	if [ -z $mountLocationArg ]; then
		error_exit "Partition type -m requires an argument!"
	fi
fi
mountLocation="$mountLocationArg"

function checkEphemeralStorage {
#	----------------------------------------------------------------
#	Function for checking Ephemeral storage which should be
#		on /dev/xvdb (Unless not avaiable for instance type)
#	----------------------------------------------------------------
	sfdisk -l /dev/xvdb > /dev/null 2>&1 || error_exit "Ephemeral storage not available"

	for line in `sfdisk -l /dev/xvdb 2>&1 | grep -A 1 \/dev\/xvdb:\ unrecognized\ partition\ table\ type`
	do
		if [[ $? -ne 0 ]]; then
			error_exit "Ephemeral storage not available"
		fi
		hddA+=( $line )
	done
	echo ${hddA[0]} | grep -q \/dev\/xvdb:\ unrecognized\ partition\ table\ type
	if [[ $? = 0 ]]; then
		echo "Ephemeral storage available on /dev/xvdb" >> $log
		checkEphemeralStorage_result=1
	else
		echo "Ephemeral storage already has a partition structure or is unavailable!" >> $log
		checkEphemeralStorage_result=0
	fi
}

function createPartition {
#   ----------------------------------------------------------------
#   Function to create partitions on Ephemeral storage
#   on /dev/xvdb (Unless not avaiable for instance type)
#	*** Caution will overwrite any data on /dev/xvdb ****
#   ----------------------------------------------------------------

	if [ -z $1 ]; then
		error_exit "partition type not selected! at line: $LINENO"
	elif ! [[ $1 =~ (82|83) ]]; then
		error_exit "partition type incorrect at line: $LINENO"
	fi

	if [ -z $2 ]; then
		error_exit "partition size not selected! at line: $LINENO"
	elif ! [[ $2 =~ [0-9]+ ]]; then
		error_exit "partition size \"$2\" invalid at line: $LINENO"
	fi

	local _partitionType=$1
	local _partitionSize=$2

	umount /dev/xvdb >> $log 2>&1
sfdisk /dev/xvdb  >> $log 2>&1 << EOF
,${_partitionSize},${_partitionType}
,
;
;
EOF
	if [ $? = 0 ]; then createPartition_result=1; fi
}

function mountPartition {
#       ----------------------------------------------------------------
#       Function create partition on Ephemeral storage
#       /dev/xvdb (Unless not avaiable for instance type)
# 							*** WARNING ***
#		*** This function will remove all data on the selected partition ***
#							*** WARNING ***
#       ----------------------------------------------------------------

	cat /proc/mounts | grep -q \/dev\/xvdb1 >> $log 2>&1
	local _isAlreadyMounted=$?
	if [ $_isAlreadyMounted = 0 ]; then
		echo "/dev/xvdb1 device already mounted!" >> $log
		exit 0
	fi
	local _mountType=$1
	local _mountLocation=$2
	if [ -z $1 ]; then
		error_exit "files system format not selected! at line: $LINENO"
	elif ! [[ $1 =~ (swap|ext2|ext3|ext4) ]]; then
		error_exit "File system format incorrect or unsupported! at line: $LINENO"
	fi

	if ! [[ $_mountType == swap ]]; then
		if ! [ -d $_mountLocation ]; then
			error_exit "Mount location: $_mountLocation does not exist!"
		fi
	fi

    local _partitionType=`sfdisk --print-id /dev/xvdb 1`
    local _partitionTypeStatus=$?

    if [[ $_partitionTypeStatus = 0 ]] && [[ $_partitionType == 82 ]] && [[ $_mountType == swap ]]; then
		echo "Mounting swap partition" >> $log
		/sbin/swapon /dev/xvdb1 >> $log 2>&1
		if [ $? = 1 ]; then error_exit "Unable to mount swap at $LINENO"; fi
	elif [[ $_partitionTypeStatus = 0 ]] && [[ $_partitionType == 83 ]] && [[ $_mountType =~ (ext2|ext3|ext4) ]]; then
		echo "Mounting $_mountType partition" >> $log
		/bin/mount /dev/xvdb1 $mountLocation >> $log 2>&1
		if [ $? = 1 ]; then error_exit "Unable to mount $_mountType at $LINENO"; fi
	else
		error_exit "Unable to determine disk format or mount location at line: $LINENO"
	fi
}

function formatPartition {
#       ----------------------------------------------------------------
#       Function to format partition on Ephemeral storage
#       /dev/xvdb (Unless not avaiable for instance type)
# 							*** WARNING ***
#		*** This function will remove all data on the selected partition ***
#							*** WARNING ***
#       ----------------------------------------------------------------
	if [ -z $1 ]; then
		error_exit "files system format not selected! at line: $LINENO"
	elif ! [[ $1 =~ (swap|ext2|ext3|ext4) ]]; then
		error_exit "File system format incorrect or unsupported! at line: $LINENO"
	fi

	local _fileSystemFormat=$1
    local _partitionTypeCheck=`sfdisk --print-id /dev/xvdb 1`
    local _partitionTypeCheckStatus=$?

    if [[ $_partitionTypeCheckStatus == 0 ]] && [[ $_partitionTypeCheck == 82 ]] && [[ $_fileSystemFormat == swap ]]; then
	   	echo "Fomatting swap partition" >> $log
       	/sbin/mkswap /dev/xvdb1 >> $log 2>&1
       	if [ $? = 0 ]; then formatPartition_result=1; fi
	elif [[ $_partitionTypeCheckStatus == 0 ]] && [[ $_partitionTypeCheck == 83 ]] && [[ $_fileSystemFormat == ext2 ]]; then
		echo "Formatting Linux ext2 partition" >> $log
		/sbin/mkfs.ext2 /dev/xvdb1 >> $log 2>&1
		if [ $? = 0 ]; then formatPartition_result=1; fi
	elif [[ $_partitionTypeCheckStatus == 0 ]] && [[ $_partitionTypeCheck == 83 ]] && [[ $_fileSystemFormat == ext3 ]]; then
		echo "Formatting Linux ext3 partition" >> $log
		/sbin/mkfs.ext3 /dev/xvdb1 >> $log 2>&1
	elif [[ $_partitionTypeCheckStatus == 0 ]] && [[ $_partitionTypeCheck == 83 ]] && [[ $_fileSystemFormat == ext4 ]]; then
		echo "Formatting Linux ext4 partition" >> $log
		/sbin/mkfs.ext3 /dev/xvdb1 >> $log 2>&1
		if [ $? = 0 ]; then formatPartition_result=1; fi
	else
		error_exit "Error formating, Unable to determine disk format or file system format at line: $LINENO"
	fi
}

#   ----------------------------------------------------------------
#	Check if Ephemeral storage is avaiable and proceed.
#   ----------------------------------------------------------------
checkEphemeralStorage

if [[ $checkEphemeralStorage_result = 1 ]]; then
	createPartition $partitionType $partitionSize
	if [ $createPartition_result = 1 ]; then
		formatPartition $fileSystemFormat
	fi
	if [ $formatPartition_result = 1 ]; then
		mountPartition $fileSystemFormat $mountLocation
	fi
elif [[ $checkEphemeralStorage_result = 0 ]]; then
	mountPartition $fileSystemFormat $mountLocation
else
	error_exit
fi

redpajama_set_name: RedPajamaGithub


text:
module Admin
  class BaseController < ApplicationController

    def index
      raise "Dummy - Admin::BaseController"
    end

  end
end


text:
using System;
using System.Linq;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace RMS.Models
{
    public enum ProjectClass { 院级, 校级, 市级, 国家级 };
    public class BannerImage
    {
        public int ID { get; set; }
        public string href { get; set; }
        public virtual File src { get; set; }
    }

    public class Notification
    {
        public int ID { get; set; }
        public enum n_type { 通知公告 , 焦点新闻 , 政策文件 , 项目指南 , 文件表格 }
        public n_type type { get; set; }
        public virtual Notice notice { get; set; }
        public virtual News news { get; set; }
        public virtual Policy policy { get; set; }
        public virtual Table table { get; set; }
        public virtual Gallery gallery { get; set; }
        //public virtual Guide guide { get; set; } //todo
    }

    public class Notice
    {
        public int ID { get; set; }
        public DateTime date { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public virtual List<Attachment> attachment { get; set; }
    }

    public class News
    {
        public int ID { get; set; }
        public DateTime date { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public virtual List<Attachment> attachment { get; set; }
    }

    public class Policy
    {
        public int ID { get; set; }
        public DateTime date { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public virtual List<Attachment> attachment { get; set; }
    }

    public class Guide
    {
        public int ID { get; set; }
        public DateTime date { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public virtual List<Attachment> attachment { get; set; }
    }

    public class Gallery
    {
        public int ID { get; set; }
        public virtual Project project { get; set; }
        public virtual IEnumerable<Result> result { get; set; }
        public class Result
        {
            public int ID { get; set; }
            public string title { get; set; }
            public string content { get; set; }
            public File pic { get; set; }
        }
    }

    public class Table
    {
        public int ID { get; set; }
        public string title { get; set; }
        public virtual File file { get; set; }
    }

    public class Academy
    {
        public int ID { get; set; }
        public string academy { get; set; }
    }

    public class Person
    {
        public string name { get; set; }
        public bool sex { get; set; }
        public virtual Academy academy { get; set; }
        public string identity { get; set; }
        public string email { get; set; }
        public long phone { get; set; }
    }
    public class Club :Person
    {
        public int cno { get; set; }
        public string pwd { get; set; }
        public int grade { get; set; }
        public string subject { get; set; }
        //照片
    }
    public class Admin : Person
    {
        [Key]
        public int ano { get; set; }
        public string pwd { get; set; }
    }
    public class Teacher :Person
    {
        [Key]
        public int tno { get; set; }
        public string pwd { get; set; }
        public int tage { get; set; }
        public string finaldegree { get; set; }
        public string subject { get; set; }
        public string direction { get; set; }
        public string title { get; set; }
        public string duty { get; set; }
        public string tel { get; set; }
    }
    public class Member : Person
    {
        [Key]
        public int sno { get; set; }
        public string subject { get; set; }
        public string assignment { get; set; }
        public int assignmentratio { get; set; }
        public bool afterinto { get; set; }
    }
    public class Leader : Person
    {
        [Key]
        public int sno { get; set; }
        public string subject { get; set; }
        public string assignment { get; set; }
        public int assignmentratio { get; set; }
        public bool afterinto { get; set; }
    }
    public class Stu :Person
    {
        [Key]
        public int sno { get; set; }
        public string pwd { get; set; }
        public int grade { get; set; }
        public string subject { get; set; }
    }

    public class Fund
    {
        public enum m_type { 图书资料费, 实验材料费, 调研费, 印刷费, 成果转化费, 文献资料收集查询费, 交通费, 其他 }
        public int ID { get; set; }
        public m_type fundType { get; set; }
        public float money { get; set; }
        public string reason { get; set; }
    }

    public class Project
    {
        public enum p_type { 指南类, 自选类, 创业类, 定向资助, 延续资助 }
        public int ID { get; set; }
        public string projectName { get; set; }
        public p_type projectType { get; set; }
        public string projectNo { get; set; }
        public string projectSubject { get; set; }
        public virtual Leader leader { get; set; }
        public virtual IEnumerable<Member> members { get; set; }
        //todo 教师类
        //public virtual Teacher teacher { get; set; }
        public string baseon { get; set; }
        public string purpose { get; set; }
        public string schedule { get; set; }
        public string format { get; set; }
        public string special { get; set; }
        public string experience { get; set; }
        public virtual IEnumerable<Fund> fund { get; set; }
        public virtual IEnumerable<FundUse> funduse { get; set; }
        public virtual StartReport startreport { get; set; }
        public virtual MidReport midreport { get; set; }
        public virtual EndReport endreport { get; set; }

        #region 以下部分未定
        public string passProject { get; set; }
        public ProjectClass passProjectClass { get; set; }
        public string passLeaderName { get; set; }
        public long passLeaderPhone { get; set; }
        public long passLeaderSno { get; set; }
        public string passTeacherName { get; set; }
        public long passTeacherPhone { get; set; }
        public string passTeacherTitle { get; set; }
        #endregion
    }

    public class StartReport
    {
        public int ID { get; set; }
    }

    public class MidReport
    {
        public int ID { get; set; }
        public enum Status { 提前完成, 按时完成, 可能无法完成 }
        public double money { get; set; }
        public Status status { get; set; }
        public string proceed { get; set; }
    }

    public class EndReport
    {
        public int ID { get; set; }
        public string summary { get; set; }
        public string mainresult { get; set; }
        public string resultformat { get; set; }
        public IEnumerable<Fund> expectfund { get; set; }
        public IEnumerable<Fund> actualfund { get; set; }
    }

    public class FundUse
    {
        public int ID { get; set; }
        public DateTime time { get; set; }
        public string title { get; set; }
        public float money { get; set; }
    }

    public class Project_Progress
    {

        public int ID { get; set; }
        public int sequence { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public virtual Project project { get; set; }
    }

    public class DBHelper : DbContext
    {
        public static readonly DBHelper instence = new DBHelper();
        private DBHelper() : base("name=DefaultConnection") { }
        public DbSet<File> Files { get; set; }
        public DbSet<BannerImage> Banners { get; set; }
        public DbSet<Notice> Notices { get; set; }
        public DbSet<News> News { get; set; }
        public DbSet<Policy> Policy { get; set; }
        public DbSet<Guide> Guide { get; set; }
        public DbSet<Table> Table { get; set; }
        public DbSet<Project_Progress> Project_progress { get; set; }
        public DbSet<Project> Project { get; set; }
        public DbSet<Notification> Notification { get; set; }

        public DbSet<Academy> Academy { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}


text:
module.exports = function(embark) {
  embark.registerServiceCheck('PluginService', function(cb) {
    cb({name: "ServiceName", status: "on"});
  });
};


text:
"""
Plugin Handling Functions

All plugins should be stored in the "plugins" directory.

They should be seperated with folders. Then they are to be organized by usage.
Finally, each plugin module should have its own folder. The

Example Directory Structure

plugins/

        hub/                    - plugin directory for "hub
            greeting/           - the "greeting" plugin folder
                main.py         - Important entry point for the plugin.
                helperfile.py   - some extra file for helping.

        irc/                    - plugin directory for "irc"
            trivia/             - the "trivia" plugin folder
                main.py         - this holds initialization code
                db.py           - extra file for helping.

"""

import sys, imp
import os.path, os

from PluginUtils import comparePlugin

import import2

# Maybe use weakref.WeakValueDictionary()?
module_cache = {}

def loadFolder(path, reload=False):
    """
    Search the given path for plugin directories.
    Return intialized plugin objects.

    If reload is true, then changes made to the plugin files will be reloaded.
    """

    dir = os.listdir( os.path.normpath(path) )

    # find directories with main.py in them
    possible_modules = []
    for item in dir:
        item = os.path.join(path, item)
        # check if it contains main.py
        if os.path.isfile( os.path.join(item, 'main.py') ):
            possible_modules.append(item)

    # load the modules and make plugins
    plugins = []
    for modulepath in possible_modules:
        mod = loadModule(modulepath, reload)
        plugins.append(loadPlugin(mod))

    # sort the plugins
    plugins.sort(comparePlugin)

    return plugins

def loadModule(path, reload=False):
    """
    Load a single module from it's folder.
    Used by loadFolder
    """

    absolute_path = os.path.abspath(path)

    # try getting the module from the cache
    if reload == False:
        try:
            return module_cache[absolute_path]
        except KeyError:
            pass

    # load the module
    mod          = imp.new_module(os.path.basename(path))
    mod.__file__ = os.path.join(absolute_path, 'main.py')

    # Create a reference to itself for import2.py
    mod.__dict__['_self'] = mod

    # add the directory to the module searchpath temporarily.
    # so plugins can import files in their own directory
    sys.path.insert(0, absolute_path)

    # Behavior: the working directory of all plugins default to where the program was run.
    # This can be overriden by os.chdir(). But, maybe the seperation between plugins, and working data is fine.

    # create the module
    execfile(mod.__file__, mod.__dict__)

    # remove the directory to clean it up now that we are done.
    sys.path.pop(0)

    # save to cache
    module_cache[mod.__file__] = mod

    return mod

def loadPlugin(mod):
    """
    Spawn a plugin class given a module object.
    Used by loadModule
    """
    plugin = mod.Main()
    plugin.name = plugin.__module__
    plugin.__file__ = mod.__file__

    return plugin


text:
namespace onnxruntime {

// A helper struct holding attributes for Pool-family ops
struct PoolAttributes {
  static bool IsGlobalPooling(const std::string& op_name) {
    return op_name == "GlobalAveragePool" || op_name == "GlobalMaxPool" || op_name == "GlobalLpPool";
  }

#ifdef SHARED_PROVIDER
  // Shared providers don't know about OpNodeProtoHelper
  PoolAttributes(const OpKernelInfo& info,
#else
  PoolAttributes(const OpNodeProtoHelper<ProtoHelperNodeContext>& info,
#endif
                 const std::string& op_name, int start_version)
      : global_pooling(IsGlobalPooling(op_name)) {
    if (global_pooling) {
      return;
    }

    ORT_ENFORCE(info.GetAttrs("kernel_shape", kernel_shape).IsOK(),
                "No kernel shape is set.");

    std::string auto_padding;
    ORT_ENFORCE(info.GetAttr<std::string>("auto_pad", &auto_padding).IsOK());
    auto_pad = StringToAutoPadType(auto_padding);

    if (!info.GetAttrs("pads", pads).IsOK() || pads.empty()) {
      pads.resize(kernel_shape.size() * 2, 0);
    }

    if (!info.GetAttrs("strides", strides).IsOK() || strides.empty()) {
      strides.resize(kernel_shape.size(), 1);
    }

    if (!info.GetAttr<int64_t>("ceil_mode", &ceil_mode).IsOK()) {
      ceil_mode = 0;
    }

    default_dilations = false;
    if (!info.GetAttrs("dilations", dilations).IsOK() || dilations.empty()) {
      dilations.resize(kernel_shape.size(), 1);
      default_dilations = true;
    } else {
      default_dilations = std::all_of(dilations.begin(), dilations.end(), [](int64_t i) { return i == 1; });
    }

    if (op_name == "AveragePool") {
      int64_t temp;
      ORT_ENFORCE(info.GetAttr<int64_t>("count_include_pad", &temp).IsOK());
      count_include_pad = (temp != 0);
    }

    if (op_name == "MaxPool") {
      if (start_version >= 8) {
        ORT_ENFORCE(info.GetAttr("storage_order", &storage_order).IsOK());
      }
    }

    for (size_t dim = 0; dim < kernel_shape.size(); ++dim) {
      ORT_ENFORCE(kernel_shape[dim] > 0);
      ORT_ENFORCE(pads[dim] < kernel_shape[dim] && pads[dim + kernel_shape.size()] < kernel_shape[dim],
                  "Pad should be smaller than kernel.");
    }

    ORT_ENFORCE(strides.size() == kernel_shape.size());
    ORT_ENFORCE(dilations.size() == kernel_shape.size(),
                "Dilations dimensions should match kernel shape");
  }

  const bool global_pooling;

  bool count_include_pad{};
  int64_t storage_order{0};  // MaxPool_8 only. 0 is row major, and 1 is column major. Default is 0.
  int64_t ceil_mode{0};      // Introduced in MaxPool_10
  TensorShapeVector kernel_shape;
  TensorShapeVector pads;
  TensorShapeVector strides;
  TensorShapeVector dilations;  // Introduced in MaxPool_10
  // default_dilations is true if dilations is not set or all dilations are 1
  bool default_dilations;
  AutoPadType auto_pad;

  TensorShapeVector SetOutputSize(const TensorShape& input_shape,
                                     int64_t output_channel,
                                     TensorShapeVector* actual_pads) const {
    ORT_ENFORCE(input_shape.Size() > 0 || input_shape[0] == 0,
                "Invalid input shape. Only N can be zero. Got:", input_shape);
    TensorShapeVector output_dims;
    int64_t N = input_shape[0];
    InferOutputSize(input_shape.GetDims(), &output_dims, actual_pads);

    output_dims.insert(output_dims.begin(), {N, output_channel});

    return output_dims;
  }

  void InferOutputSize(gsl::span<const int64_t> input_dims,
                       TensorShapeVector* output_dims,
                       TensorShapeVector* actual_pads) const {
    ORT_ENFORCE(input_dims.size() >= 2);
    if (global_pooling) {
      output_dims->assign(input_dims.size() - 2, 1);
    } else {
      for (size_t dim = 0; dim < input_dims.size() - 2; ++dim) {
        int64_t dim_size = 0;
        ComputeSizePadDilations(static_cast<int>(input_dims[dim + 2]),
                                strides[dim],
                                kernel_shape[dim],
                                &actual_pads->at(dim),
                                &actual_pads->at(input_dims.size() + dim - 2),
                                dilations[dim],
                                &dim_size);
        output_dims->push_back(dim_size);
      }
    }
  }

  void ComputeSizePadDilations(const int64_t in_size,
                               const int64_t stride,
                               const int64_t kernel,
                               int64_t* pad_head,
                               int64_t* pad_tail,
                               int64_t dilation,
                               int64_t* out_size) const {
    if (auto_pad != AutoPadType::NOTSET) {
      switch (auto_pad) {
        case AutoPadType::VALID:
          *pad_head = 0;
          *pad_tail = 0;
          *out_size = ComputeOutputSize(in_size, stride, kernel, 0, dilation);
          break;
        case AutoPadType::SAME_LOWER: {
          int64_t legacy_target_size = (in_size + stride - 1) / stride;
          int64_t pad_needed = (legacy_target_size - 1) * stride + kernel - in_size;
          *pad_head = (pad_needed + 1) / 2;
          *pad_tail = pad_needed - *pad_head;
          *out_size = ComputeOutputSize(in_size, stride, kernel, pad_needed, dilation);
          break;
        }
        case AutoPadType::SAME_UPPER: {
          int64_t legacy_target_size = (in_size + stride - 1) / stride;
          int64_t pad_needed = (legacy_target_size - 1) * stride + kernel - in_size;
          *pad_head = pad_needed / 2;
          *pad_tail = pad_needed - *pad_head;
          *out_size = ComputeOutputSize(in_size, stride, kernel, pad_needed, dilation);
          break;
        }
        default: {
          ORT_THROW("Unsupported AutoPad Type.");
        }
      }
    } else {
      *out_size = ComputeOutputSize(in_size, stride, kernel, *pad_head + *pad_tail, dilation);
    }
  }
#if defined(_MSC_VER) && !defined(__clang__)
#pragma warning(push)
// Chance of arithmetic overflow could be reduced
#pragma warning(disable : 26451)
#endif
  int64_t ComputeOutputSize(int64_t in_size,
                            int64_t stride,
                            int64_t kernel,
                            int64_t pad_needed,
                            int64_t dilation) const {
    if (ceil_mode == 0) {
      return static_cast<int64_t>(static_cast<float>(in_size + pad_needed - dilation * (kernel - 1) - 1) / stride + 1);
    }
    return static_cast<int64_t>(
        std::ceil(static_cast<float>(in_size + pad_needed - dilation * (kernel - 1) - 1) / stride + 1));
  }
#if defined(_MSC_VER) && !defined(__clang__)
#pragma warning(pop)
#endif
};

}  // namespace onnxruntime


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.

namespace UnitsNet
{
    public partial struct ForcePerLength
    {
        /// Get <see cref="Force"/> from <see cref="ForcePerLength"/> multiplied by <see cref="Length"/>.
        public static Force operator *(ForcePerLength forcePerLength, Length length)
        {
            return Force.FromNewtons(forcePerLength.NewtonsPerMeter * length.Meters);
        }

        /// Get <see cref="Length"/> from <see cref="Force"/> divided by <see cref="ForcePerLength"/>.
        public static Length operator /(Force force, ForcePerLength forcePerLength)
        {
            return Length.FromMeters(force.Newtons / forcePerLength.NewtonsPerMeter);
        }

        /// Get <see cref="Pressure"/> from <see cref="ForcePerLength"/> divided by <see cref="Length"/>.
        public static Pressure operator /(ForcePerLength forcePerLength, Length length)
        {
            return Pressure.FromNewtonsPerSquareMeter(forcePerLength.NewtonsPerMeter / length.Meters);
        }

        /// Get <see cref="Torque"/> from <see cref="ForcePerLength"/> multiplied by <see cref="Area"/>.
        public static Torque operator *(ForcePerLength forcePerLength, Area area)
        {
            return Torque.FromNewtonMeters(forcePerLength.NewtonsPerMeter * area.SquareMeters);
        }
    }
}


text:
package fatjar.implementations.xml;

import fatjar.Log;
import fatjar.XML;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Optional;

public class JaxbXML implements XML {

    @SuppressWarnings("unchecked")
    public <T> Optional<T> fromXML(byte[] xmlData, Class<T> tClass) {
        try {
            return Optional.ofNullable((T) JAXBContext.newInstance(tClass).createUnmarshaller().unmarshal(new ByteArrayInputStream(xmlData)));
        } catch (Exception e) {
            Log.error("got exception while creating object from xml, exception: " + e, e);
            return Optional.empty();
        }
    }

    public <T> Optional<String> toXML(T object) {
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            Marshaller marshaller = JAXBContext.newInstance(object.getClass()).createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(object, outStream);
            return Optional.of(new String(outStream.toByteArray()));
        } catch (Exception e) {
            Log.error("got exception while creating object from xml, exception: " + e, e);
            return Optional.empty();
        }
    }

}


text:
   0"
     ng-click="gmfLayertreeCtrl.removeAllNodes()">
     {{'Clear all' | translate}}

 1">

    {{layertreeCtrl.node.name | translate}}

        <ngeo-date-picker
          ng-if="::layertreeCtrl.node.time.widget === 'datepicker'"
          time="layertreeCtrl.node.time"
          on-date-selected="gmfLayertreeCtrl.updateWMSTimeLayerState(layertreeCtrl, time)">
        </ngeo-date-picker>

        <gmf-time-slider
          ng-if="::layertreeCtrl.node.time.widget === 'slider'"
          gmf-time-slider-time="layertreeCtrl.node.time"
          gmf-time-slider-on-date-selected="gmfLayertreeCtrl.updateWMSTimeLayerState(layertreeCtrl, time)">
        </gmf-time-slider>

     1 && layertreeCtrl.parent.node.mixed && !layertreeCtrl.node.children) || (gmfLayertreeCtrl.getLegendsObject(layertreeCtrl) && layertreeCtrl.node.metadata.legend) || layertreeCtrl.getDataSource().filtrable" ngeo-popover-dismiss=".content">

 1 && layertreeCtrl.parent.node.mixed)">

            {{'Opacity'|translate}}
            <input
              class="input-action"
              name="layer-opactity"
              type="range"
              min="0"
              max="1"
              step="0.01"
              ng-model="layertreeCtrl.layer.opacity" />

              {{'Show/hide legend'|translate}}

              {{'Filter'|translate}}

    {{'Opacity'|translate}}
    <input
        class="input-action"
        name="layer-opactity"
        type="range"
        min="0"
        max="1"
        step="0.01"
        ng-model="layertreeCtrl.layer.opacity" />

    {{'Show/hide legend'|translate}}

    {{'Hide legend'|translate}}

 1">{{title|translate}}

  <gmf-datasourcegrouptree
    class="gmf-layertree-node gmf-layertree-depth-1"
    ng-repeat="wmtsGroup in gmfLayertreeCtrl.gmfExternalDataSourcesManager.wmtsGroups"
    group="wmtsGroup"
  >
  </gmf-datasourcegrouptree>
  <gmf-datasourcegrouptree
    class="gmf-layertree-node gmf-layertree-depth-1"
    ng-repeat="wmsGroup in gmfLayertreeCtrl.gmfExternalDataSourcesManager.wmsGroups"
    group="wmsGroup"
  >
  </gmf-datasourcegrouptree>
  <gmf-datasourcegrouptree
    class="gmf-layertree-node gmf-layertree-depth-1"
    ng-if="gmfLayertreeCtrl.gmfExternalDataSourcesManager.fileGroup.dataSources.length"
    group="gmfLayertreeCtrl.gmfExternalDataSourcesManager.fileGroup"
  >
  </gmf-datasourcegrouptree>

<ul
  id="gmf-layertree-layer-group-{{::layertreeCtrl.uid}}"
  ng-if="::layertreeCtrl.node.children"
  ng-class="{collapse: !layertreeCtrl.isRoot, in : layertreeCtrl.node.metadata.isExpanded}"
  ngeo-sortable="::layertreeCtrl.isRoot && layertreeCtrl.node.children"
  ngeo-sortable-options="{handleClassName: 'ngeo-sortable-handle', draggerClassName: 'gmf-layertree-dragger', placeholderClassName : 'gmf-layertree-curr-drag-item'}"
  ngeo-sortable-callback="::gmfLayertreeCtrl.afterReorder"
  ngeo-sortable-callback-ctx="::gmfLayertreeCtrl">


text:
> Check whether an atom package name is available.

## Install

```
$ npm install --save atom-name
```

## Usage

```js
var atomName = require('atom-name');

atomName('open-terminal', function(err, available) {
	console.log(available);
	//=> false
});
```

## CLI

```
$ npm install --global atom-name
```

```
$ atom-name --help

	Usage
	  atom-name <name>

	Exits with exit code 0 when available or 2 when taken.
```

## License

MIT © [Daniel Chatfield](https://github.com/danielchatfield)


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

namespace Oro\DBAL\Types;

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class PercentType extends Type
{
    public const TYPE = 'percent';

    /**
     * @return string
     * @noinspection PhpMissingReturnTypeInspection
     * @noinspection ReturnTypeCanBeDeclaredInspection
     */
    public function getName()
    {
        return self::TYPE;
    }

    /**
     * @noinspection PhpMissingReturnTypeInspection
     * @noinspection ReturnTypeCanBeDeclaredInspection
     */
    public function getSQLDeclaration(array $column, AbstractPlatform $platform)
    {
        return $platform->getFloatDeclarationSQL($column);
    }

    /**
     * @noinspection PhpMissingParentCallCommonInspection
     * @noinspection PhpMissingReturnTypeInspection
     * @noinspection ReturnTypeCanBeDeclaredInspection
     * @noinspection PhpDocSignatureInspection
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return (null === $value) ? null : (double) $value;
    }

    /**
     * @noinspection PhpMissingParentCallCommonInspection
     * @noinspection PhpMissingReturnTypeInspection
     * @noinspection ReturnTypeCanBeDeclaredInspection
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Adelaide Bot. Gard. 6:74. 1982

#### Original name
Casuarina acuaria F. Muell.

### Remarks
null


text:
package eleflow.uberdata.core

import eleflow.uberdata.core.data.{DataTransformer, Dataset}
import eleflow.uberdata.core.enums.DataSetType
import org.apache.spark.rpc.netty.{BeforeAndAfterWithContext, TestSparkConf}
import org.apache.spark.SparkException
import org.scalatest._

/**
  * Created by dirceu on 14/10/14.
  *
  */
class FuncTestSparkNotebookContext extends FlatSpec with BeforeAndAfterWithContext { this: Suite =>

  val uberContext = context

  "Functional SparkNotebookContext" should
    "correctly load rdd" in {

    import Dataset._

    val dataset = Dataset(uberContext, s"${defaultFilePath}FuncTestSparkNotebookContextFile1.csv")

    val testDataSet =
      Dataset(uberContext, s"${defaultFilePath}FuncTestSparkNotebookContextFile2.csv")

    val (train, test, _) =
      DataTransformer.createLabeledPointFromRDD(dataset, testDataSet, "int", "id")
    val all = train.take(3)
    val (_, first) = all.head
    val (_, second) = all.tail.head
    assert(first.label == 5.0)
    assert(first.features.toArray.deep == Array[Double](0.0, 1.0, 10.5).deep)
    assert(second.label == 1.0)
    assert(second.features.toArray.deep == Array[Double](1.0, 0.0, 0.1).deep)

    val allTest = test.take(3)
    val (_, firstTest) = allTest.head
    val (_, secondTest) = allTest.tail.head
    assert(firstTest.label == 1.0)
    assert(firstTest.features.toArray.deep == Array[Double](0.0, 1.0, 10.5).deep)
    assert(secondTest.label == 2.0)
    assert(secondTest.features.toArray.deep == Array[Double](1.0, 0.0, 0.1).deep)
  }

  it should "Throw an exception when process an empty numeric column" in {

    @transient lazy val context = uberContext

    context.sparkContext
    try {
      import Dataset._
      val dataset = Dataset(context, s"${defaultFilePath}FuncTestSparkNotebookContextFile1.csv")
      dataset.take(3)
    } catch {
      case e: SparkException =>
        assert(e.getMessage.contains("UnexpectedFileFormatException"))
    }
  }

  it should "Correct handle empty string values" in {
    @transient lazy val context = uberContext
    context.sparkContext
    val schemaRdd =
      Dataset(context, s"${defaultFilePath}FuncTestSparkNotebookContextEmpty.csv").toDataFrame
    val result = DataTransformer
      .createLabeledPointFromRDD(schemaRdd, Seq("int"), Seq("id"), DataSetType.Train)
    assert(result.count() == 3)
  }

  it should "Throw an exception when input have different number of columns" in {
    uberContext.sparkContext
    try {

      context
        .load(s"${defaultFilePath}FuncTestSparkNotebookContextFile1.csv", TestSparkConf.separator)
    } catch {
      case e: SparkException =>
        assert(e.getMessage.contains("UnexpectedFileFormatException"))
    }
  }

}


text:
KeyGrabber::KeyGrabber (Display * display, unsigned int numlockMask, unsigned int scrolllockMask)
  : _display(display), _numlockMask(numlockMask), _scrolllockMask(scrolllockMask)
{
}
KeyGrabber::~KeyGrabber ()
{
}
//--------------------------------------------------------
// grab
//--------------------------------------------------------
bool KeyGrabber::grab (const KeyCode & keyCode,
                       const unsigned int & modifierMask,  Window window)
{
  int ret =
  XGrabKey(_display, keyCode, modifierMask,
           window, True, GrabModeAsync, GrabModeAsync);
  XGrabKey(_display, keyCode,
           modifierMask|LockMask,
           window, True, GrabModeAsync, GrabModeAsync);
  XGrabKey(_display, keyCode,
           modifierMask|_scrolllockMask,
           window, True, GrabModeAsync, GrabModeAsync);
  XGrabKey(_display, keyCode,
           modifierMask|_numlockMask,
           window, True, GrabModeAsync, GrabModeAsync);

  XGrabKey(_display, keyCode,
           modifierMask|LockMask|_scrolllockMask,
           window, True, GrabModeAsync, GrabModeAsync);
  XGrabKey(_display, keyCode,
           modifierMask|_scrolllockMask|_numlockMask,
           window, True, GrabModeAsync, GrabModeAsync);
  XGrabKey(_display, keyCode,
           modifierMask|_numlockMask|LockMask,
           window, True, GrabModeAsync, GrabModeAsync);

  XGrabKey(_display, keyCode,
           modifierMask|_numlockMask|LockMask|_scrolllockMask,
           window, True, GrabModeAsync, GrabModeAsync);

  // Um.  Isn't there SOME way we can tell if a grab worked???
  // return (ret == Success);
  return true;
}
//--------------------------------------------------------
// ungrab
//--------------------------------------------------------
bool KeyGrabber::ungrab (const KeyCode & keyCode,
                         const unsigned int & modifierMask,  Window window)
{
  XUngrabKey(_display, keyCode, modifierMask, window);
  XUngrabKey(_display, keyCode, modifierMask|LockMask, window);
  XUngrabKey(_display, keyCode, modifierMask|_scrolllockMask, window);
  XUngrabKey(_display, keyCode, modifierMask|_numlockMask, window);

  XUngrabKey(_display, keyCode, modifierMask|LockMask|_scrolllockMask, window);
  XUngrabKey(_display, keyCode, modifierMask|_scrolllockMask|_numlockMask, window);
  XUngrabKey(_display, keyCode, modifierMask|_numlockMask|LockMask, window);
  XUngrabKey(_display, keyCode, modifierMask|_numlockMask|LockMask|
             _scrolllockMask, window);

  return true;
}
//--------------------------------------------------------
// ungrabAll
//--------------------------------------------------------
bool KeyGrabber::ungrabAll (Window  window)
{

  XUngrabKey(_display, AnyKey, AnyModifier, window);

  return true;
}


text:
function checkUsername() {											// Declare function
	var elMsg = document.getElementById('feedback');				// Get feedback element
	if (this.value.length < 5) {									// If username too short
		elMsg.textContent = 'Username must be 5 characters or more';	// Set error message
	} else {														// Otherwise
		elMsg.textContent = '';										// Clear message
	}
}

var elUsername = document.getElementById('username');				// Get username input
// When it loses focus call checkUsername()
elUsername.addEventListener('blur', checkUsername, false);


text:
<?php

class Presenter_Record extends Presenter
{
    private $manifests_table_rows = [];

    public function before() {
        parent::before();

        $this->requested_flight_record = Model_Flight_Record::find($this->id, [
            'related' => [
                'manifests' => [
                    'related' => ['aircraft', 'aerodromes']
                ]
            ]
        ]);

        $this->requested_flight_record === null ? $this->requested_flight_record = Model_Flight_Record::forge() : null;

    // Pull out manifest details
        foreach($this->requested_flight_record->manifests as $manifest)
        {
            $left_text = ''; // AA-CH #10009 for example
            $cells = [
                View::forge('widgets/tablewithactions/row/cell', [
                    'cell_content' => $left_text
                ], false)
            ];

            $this->manifests_table_rows[] = View::forge('widgets/tablewithactions/row', [
                'cells' => $cells,
                'id' => $manifest->id,
                'duplicate_action' => false
            ]);
        }
    }

    public function view()
    {
        // Group's inputs.
        $aircraft_group_inputs = [
            View::forge('form/group/input', [
                'label_coltype' => 'col-xs-2',
                'input_coltype' => 'col-xs-4',
                'input' => '',
                'label' => 'A/C Name'
            ], false),
        ];

        $aircraft_group = View::forge('form/group', ['inputs' => $aircraft_group_inputs], false);

        $details_section_data = [
            'heading' => 'Aircraft',
            'unique_id' => Str::random('uuid'),
            'groups' => [
                $aircraft_group,
            ]
        ];
        $manifests_section_data = [
            'heading' => 'Manifests',
            'unique_id' => Str::random('uuid'),
            'groups' => [
                $aircraft_group,
            ]
        ];

        $heading = View::forge('form/heading', [
            'text' => 'Flight Record' . $this->requested_flight_record->id
        ], false);
        $details_section = View::forge('form/section', $details_section_data, false);
        $manifests_section = View::forge('form/section', $manifests_section_data, false);

        $this->aircraft_form = $heading . $details_section . $manifests_section;
    }
}


text:
@interface IBContentHuggingLayoutConstraintAbstraction (IBContentSizeLayoutConstraintAbstraction)
- (unsigned long long)_matchingVerticalContentChangeType;
- (unsigned long long)_matchingHorizontalContentChangeType;
- (id)ibTypeNameForDefaultLabel;
- (id)ibBadgeLabelForDrawableAtIndex:(unsigned long long)arg1 stateMask:(unsigned long long)arg2;
@end


text:
Ciphers
=======

All the cipher code I write goes here

August 22, 2013 - Added the vigenere cipher to the list
  python scripts can read .txt files or directly input (ARGV) open the scripts for more information


text:
'use strict';

var utils = require('../../../utils/utils');
var BaseXform = require('../base-xform');

var IntegerXform = module.exports = function(options) {
  this.tag = options.tag;
  this.attr = options.attr;
  this.attrs = options.attrs;
};

utils.inherits(IntegerXform, BaseXform, {

  render: function(xmlStream, model) {
    // int is different to float in that zero is not rendered
    if (model) {
      xmlStream.openNode(this.tag);
      if (this.attrs) {
        xmlStream.addAttributes(this.attrs);
      }
      if (this.attr) {
        xmlStream.addAttribute(this.attr, model);
      } else {
        xmlStream.writeText(model);
      }
      xmlStream.closeNode();
    }
  },

  parseOpen: function(node) {
    if (node.name === this.tag) {
      if (this.attr) {
        this.model = parseInt(node.attributes[this.attr]);
      } else {
        this.text = [];
      }
      return true;
    } else {
      return false;
    }
  },
  parseText: function(text) {
    if (!this.attr) {
      this.text.push(text);
    }
  },
  parseClose: function() {
    if (!this.attr) {
      this.model = parseInt(this.text.join('') || 0);
    }
    return false;
  }
});


text:
import Button   from 'components/Button/Button.react';
import ParseApp from 'lib/ParseApp';
import Parse    from 'parse';
import React    from 'react';

export default class RunNowButton extends React.Component {
  constructor() {
    super();

    this.state = {
      progress: null,
      result: null
    };

    this.timeout = null;
  }

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }

  handleClick() {
    this.setState({ progress: true });
    this.context.currentApp.runJob(this.props.job).then(() => {
      this.setState({ progress: false, result: 'success' });
      this.timeout = setTimeout(() => this.setState({ result: null }), 3000);
    }, () => {
      this.setState({ progress: false, result: 'error' });
      this.timeout = setTimeout(() => this.setState({ result: null }), 3000);
    });
  }

  render() {
    let { job, ...other } = this.props;
    let value = 'Run now';
    if (this.state.result === 'error') {
      value = 'Failed.';
    } else if (this.state.result === 'success') {
      value = 'Success!';
    }
    return (
      <Button
        progress={this.state.progress}
        onClick={this.handleClick.bind(this)}
        color={this.state.result === 'error' ? 'red' : 'blue'}
        value={value}
        {...other} />
    );
  }
}

RunNowButton.contextTypes = {
  currentApp: React.PropTypes.instanceOf(ParseApp),
};


text:
<?php

    namespace UniApi\Common\Exception;

    class SingletonPatternViolationException extends \Exception {}


text:
<?php

namespace frontend\controllers;

use Yii;
use common\models\App;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AppController implements the CRUD actions for App model.
 */
class AppController extends Controller
{
    /**
     * Lists all App models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => App::find()->with('build')->orderBy('last_update DESC'),
			'sort' => false,
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single App model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Finds the App model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return App the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = App::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package lebah.mail;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "localhost");
		//props.put("mail.smtp.socketFactory.port", "465");
		//props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		//props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "25");

//		Session session = Session.getDefaultInstance(props,
//			new javax.mail.Authenticator() {
//				protected PasswordAuthentication getPasswordAuthentication() {
//					return new PasswordAuthentication("username","password");
//				}
//			});

		//Session session = Session.getInstance(props, null);
		Session session = Session.getDefaultInstance(props);

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("sbahrin3@yahoo.com"));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sbahrin3@gmail.com"));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler," +
					"\n\n No spam to my email, please!");

			Transport.send(message);

			System.out.println("Done");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
<blog>

	<!-- Configure where the engine should look to
	find entries for this blog/article collection -->
	<post_directory>/var/www/engine/lib/webadmin/pages</post_directory>

	<page_directory>/var/www/engine/lib/webadmin/pages</page_directory>

	<!-- Configure the id of the blog (this is where the
	 blog is on the web, i.e example.com/yourblog) -->
	<id>webadmin</id>

	<!-- Configure the title of the blog -->
	<title>Web Administration Panel</title>

	<short_title>Webadmin</short_title>

	<!-- Configure the blog's (brief) description/catchline -->
	<catchline></catchline>

	<!-- Insert any comment code (such as disqus) here -->
	<comment_code></comment_code>

</blog>


text:
<?php
namespace Ilios\CoreBundle\Entity\Repository;

use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Ilios\CoreBundle\Entity\DTO\ProgramYearDTO;

/**
 * Class ProgramYearRepository
 * @package Ilios\CoreBundle\Entity\Repository
 */
class ProgramYearRepository extends EntityRepository
{
    /**
     * Custom findBy so we can filter by related entities
     *
     * @param array $criteria
     * @param array|null $orderBy
     * @param null $limit
     * @param null $offset
     *
     * @return array
     */
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select('DISTINCT p')->from('IliosCoreBundle:ProgramYear', 'p');

        $this->attachCriteriaToQueryBuilder($qb, $criteria, $orderBy, $limit, $offset);

        return $qb->getQuery()->getResult();
    }

    /**
     * Find and hydrate as DTOs
     *
     * @param array $criteria
     * @param array|null $orderBy
     * @param null $limit
     * @param null $offset
     *
     * @return array
     */
    public function findDTOsBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $qb = $this->_em->createQueryBuilder()->select('p')->distinct()->from('IliosCoreBundle:ProgramYear', 'p');
        $this->attachCriteriaToQueryBuilder($qb, $criteria, $orderBy, $limit, $offset);

        $programYearDTOs = [];
        foreach ($qb->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY) as $arr) {
            $programYearDTOs[$arr['id']] = new ProgramYearDTO(
                $arr['id'],
                $arr['startYear'],
                $arr['locked'],
                $arr['archived'],
                $arr['publishedAsTbd'],
                $arr['published']
            );
        }
        $programYearIds = array_keys($programYearDTOs);

        $qb = $this->_em->createQueryBuilder()
            ->select('p.id as programYearId, pr.id as programId, c.id as cohortId')
            ->from('IliosCoreBundle:ProgramYear', 'p')
            ->join('p.program', 'pr')
            ->join('p.cohort', 'c')
            ->where($qb->expr()->in('p.id', ':ids'))
            ->setParameter('ids', $programYearIds);

        foreach ($qb->getQuery()->getResult() as $arr) {
            $programYearDTOs[$arr['programYearId']]->program = (int) $arr['programId'];
            $programYearDTOs[$arr['programYearId']]->cohort = (int) $arr['cohortId'];
        }

        $related = [
            'directors',
            'competencies',
            'terms',
            'objectives',
            'stewards',
        ];

        foreach ($related as $rel) {
            $qb = $this->_em->createQueryBuilder()
                ->select('r.id AS relId, p.id AS programYearId')->from('IliosCoreBundle:ProgramYear', 'p')
                ->join("p.{$rel}", 'r')
                ->where($qb->expr()->in('p.id', ':programYearIds'))
                ->orderBy('relId')
                ->setParameter('programYearIds', $programYearIds);

            foreach ($qb->getQuery()->getResult() as $arr) {
                $programYearDTOs[$arr['programYearId']]->{$rel}[] = $arr['relId'];
            }
        }

        return array_values($programYearDTOs);
    }

    /**
     * @param QueryBuilder $qb
     * @param array $criteria
     * @param array $orderBy
     * @param int $limit
     * @param int $offset
     *
     * @return QueryBuilder
     */
    protected function attachCriteriaToQueryBuilder(QueryBuilder $qb, $criteria, $orderBy, $limit, $offset)
    {
        if (array_key_exists('courses', $criteria)) {
            $ids = is_array($criteria['courses']) ? $criteria['courses'] : [$criteria['courses']];
            $qb->join('p.cohort', 'c_cohort');
            $qb->join('c_cohort.courses', 'c_course');
            $qb->andWhere($qb->expr()->in('c_course.id', ':courses'));
            $qb->setParameter(':courses', $ids);
        }

        if (array_key_exists('sessions', $criteria)) {
            $ids = is_array($criteria['sessions']) ? $criteria['sessions'] : [$criteria['sessions']];
            $qb->join('p.cohort', 'se_cohort');
            $qb->join('se_cohort.courses', 'se_course');
            $qb->join('se_course.sessions', 'se_session');
            $qb->andWhere($qb->expr()->in('se_session.id', ':sessions'));
            $qb->setParameter(':sessions', $ids);
        }

        if (array_key_exists('terms', $criteria)) {
            $ids = is_array($criteria['terms']) ? $criteria['terms'] : [$criteria['terms']];
            $qb->join('p.terms', 't_term');
            $qb->andWhere($qb->expr()->in('t_term.id', ':terms'));
            $qb->setParameter(':terms', $ids);
        }

        if (array_key_exists('schools', $criteria)) {
            $ids = is_array($criteria['schools']) ? $criteria['schools'] : [$criteria['schools']];
            $qb->join('p.program', 'py_program');
            $qb->join('py_program.school', 'py_school');
            $qb->andWhere($qb->expr()->in('py_school.id', ':schools'));
            $qb->setParameter(':schools', $ids);
        }

        if (array_key_exists('startYears', $criteria)) {
            $startYears = is_array($criteria['startYears']) ? $criteria['startYears'] : [$criteria['startYears']];
            $qb->andWhere($qb->expr()->in('p.startYear', ':startYears'));
            $qb->setParameter(':startYears', $startYears);
        }

        unset($criteria['schools']);
        unset($criteria['courses']);
        unset($criteria['sessions']);
        unset($criteria['terms']);
        unset($criteria['startYears']);

        if (count($criteria)) {
            foreach ($criteria as $key => $value) {
                $values = is_array($value) ? $value : [$value];
                $qb->andWhere($qb->expr()->in("p.{$key}", ":{$key}"));
                $qb->setParameter(":{$key}", $values);
            }
        }

        if (empty($orderBy)) {
            $orderBy = ['id' => 'ASC'];
        }

        if (is_array($orderBy)) {
            foreach ($orderBy as $sort => $order) {
                $qb->addOrderBy('p.'.$sort, $order);
            }
        }

        if ($offset) {
            $qb->setFirstResult($offset);
        }

        if ($limit) {
            $qb->setMaxResults($limit);
        }

        return $qb;
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler.InlineCompletions;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.LanguageClient
{
    /// <summary>
    /// Defines the LSP server for Razor C#.  This is separate so that we can
    /// activate this outside of a liveshare session and publish diagnostics
    /// only for razor cs files.
    /// TODO - This can be removed once C# is using LSP for diagnostics.
    /// https://github.com/dotnet/roslyn/issues/42630
    /// </summary>
    /// <remarks>
    /// This specifies RunOnHost because in LiveShare we don't want this to activate on the guest instance
    /// because LiveShare drops the ClientName when it mirrors guest clients, so this client ends up being
    /// activated solely by its content type, which means it receives requests for normal .cs and .vb files
    /// even for non-razor projects, which then of course fails because it gets text sync info for documents
    /// it doesn't know about.
    /// </remarks>
    [ContentType(ContentTypeNames.CSharpContentType)]
    [ClientName(ClientName)]
    [RunOnContext(RunningContext.RunOnHost)]
    [Export(typeof(ILanguageClient))]
    internal class RazorInProcLanguageClient : AbstractInProcLanguageClient
    {
        public const string ClientName = ProtocolConstants.RazorCSharp;

        private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider;

        protected override ImmutableArray<string> SupportedLanguages => ProtocolConstants.RoslynLspLanguages;

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public RazorInProcLanguageClient(
            RequestDispatcherFactory csharpVBRequestDispatcherFactory,
            IGlobalOptionService globalOptions,
            IAsynchronousOperationListenerProvider listenerProvider,
            LspWorkspaceRegistrationService lspWorkspaceRegistrationService,
            DefaultCapabilitiesProvider defaultCapabilitiesProvider,
            IThreadingContext threadingContext,
            ILspLoggerFactory lspLoggerFactory)
            : base(csharpVBRequestDispatcherFactory, globalOptions, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, ClientName)
        {
            _defaultCapabilitiesProvider = defaultCapabilitiesProvider;
        }

        protected override void Activate_OffUIThread()
        {
            // Ensure we let the default capabilities provider initialize off the UI thread to avoid
            // unnecessary MEF part loading during the GetCapabilities call, which is done on the UI thread
            _defaultCapabilitiesProvider.Initialize();
        }

        public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities)
        {
            var capabilities = _defaultCapabilitiesProvider.GetCapabilities(clientCapabilities);

            // Razor doesn't use workspace symbols, so disable to prevent duplicate results (with LiveshareLanguageClient) in liveshare.
            capabilities.WorkspaceSymbolProvider = false;

            if (capabilities is VSInternalServerCapabilities vsServerCapabilities)
            {
                vsServerCapabilities.SupportsDiagnosticRequests = true;

                var regexExpression = string.Join("|", InlineCompletionsHandler.BuiltInSnippets);
                var regex = new Regex(regexExpression, RegexOptions.Compiled | RegexOptions.Singleline, TimeSpan.FromSeconds(1));
                vsServerCapabilities.InlineCompletionOptions = new VSInternalInlineCompletionOptions
                {
                    Pattern = regex
                };

                return vsServerCapabilities;
            }

            return capabilities;
        }

        /// <summary>
        /// If the razor server is activated then any failures are catastrophic as no razor c# features will work.
        /// </summary>
        public override bool ShowNotificationOnInitializeFailed => true;

        public override WellKnownLspServerKinds ServerKind => WellKnownLspServerKinds.RazorLspServer;
    }
}


text:
from __future__ import with_statement

import unittest

import IECore

import Gaffer
import GafferTest

class PlugTest( unittest.TestCase ) :

	def testParenting( self ) :

		n = Gaffer.Node()
		p = Gaffer.Plug()
		self.assert_( p.parent() is None )
		self.assert_( p.node() is None )
		self.assert_( p.acceptsParent( n ) )
		n.addChild( p )
		self.assert_( p.parent().isSame( n ) )
		self.assert_( p.node().isSame( n ) )

	def testConnectionAcceptance( self ) :

		p1 = Gaffer.Plug( direction=Gaffer.Plug.Direction.In )
		p2 = Gaffer.Plug( direction=Gaffer.Plug.Direction.Out )
		self.assert_( p1.acceptsInput( p2 ) )

		p1 = Gaffer.Plug( direction=Gaffer.Plug.Direction.In )
		p2 = Gaffer.Plug( direction=Gaffer.Plug.Direction.In )
		self.assert_( p1.acceptsInput( p2 ) )

	def testConnection( self ) :

		n1 = Gaffer.Node()
		p1 = Gaffer.Plug()
		n1.addChild( p1 )
		self.assert_( p1.getInput() is None )
		self.assertEqual( p1.outputs(), () )

		n2 = Gaffer.Node()
		p2 = Gaffer.Plug()
		n2.addChild( p2 )
		self.assert_( p2.getInput() is None )
		self.assertEqual( p2.outputs(), () )

		p2.setInput( p1 )
		self.assert_( p2.getInput().isSame( p1 ) )
		self.assert_( len( p1.outputs() ), 1 )
		self.assert_( p1.outputs()[0].isSame( p2 ) )

		p2.setInput( None )
		self.assert_( p2.getInput() is None )
		self.assertEqual( p1.outputs(), () )

	def testConnectionSignals( self ) :

		def f( p ) :

			PlugTest.__connection = ( p, p.getInput() )

		n1 = Gaffer.Node()
		p1 = Gaffer.Plug( direction=Gaffer.Plug.Direction.Out )
		n1.addChild( p1 )

		n2 = Gaffer.Node()
		p2 = Gaffer.Plug( direction=Gaffer.Plug.Direction.In )
		n2.addChild( p2 )

		c = n2.plugInputChangedSignal().connect( f )
		p2.setInput( p1 )
		self.assert_( PlugTest.__connection[0].isSame( p2 ) )
		self.assert_( PlugTest.__connection[1].isSame( p1 ) )
		PlugTest.__connection = None
		p2.setInput( None )
		self.assert_( PlugTest.__connection[0].isSame( p2 ) )
		self.assert_( PlugTest.__connection[1] is None )

	def testDirectionality( self ) :

		p = Gaffer.Plug( direction=Gaffer.Plug.Direction.In )
		self.assertEqual( p.direction(), Gaffer.Plug.Direction.In )
		p = Gaffer.Plug( direction=Gaffer.Plug.Direction.Out )
		self.assertEqual( p.direction(), Gaffer.Plug.Direction.Out )

	def testFlags( self ) :

		p = Gaffer.Plug()
		self.assertEqual( p.getFlags(), Gaffer.Plug.Flags.Default )

		p = Gaffer.Plug( flags=Gaffer.Plug.Flags.Dynamic )
		self.assertEqual( p.getFlags(), Gaffer.Plug.Flags.Dynamic )
		self.assertEqual( p.getFlags( Gaffer.Plug.Flags.Dynamic ), True )

		p.setFlags( Gaffer.Plug.Flags.Dynamic, False )
		self.assertEqual( p.getFlags( Gaffer.Plug.Flags.Dynamic ), False )

	def testDerivingInPython( self ) :

		class TestPlug( Gaffer.Plug ) :

			def __init__( self, name = "TestPlug", direction = Gaffer.Plug.Direction.In, flags = Gaffer.Plug.Flags.Default ) :

				Gaffer.Plug.__init__( self, name, direction, flags )

				self.inputHasBeenSet = False

			def acceptsInput( self, plug ) :

				if not Gaffer.Plug.acceptsInput( self, plug ) :
					return False

				return isinstance( plug, ( TestPlug, type( None ) ) )

			def setInput( self, plug ) :

				Gaffer.Plug.setInput( self, plug )

				self.inputHasBeenSet = True

			def acceptsParent( self, potentialParent ) :

				if not Gaffer.Plug.acceptsParent( self, potentialParent ) :
					return False

				if isinstance( potentialParent, Gaffer.CompoundPlug ) :
					return False

				return True

			def createCounterpart( self, name, direction ) :

				return TestPlug( name, direction, self.getFlags() )

		IECore.registerRunTimeTyped( TestPlug )

		# check the constructor

		p1 = TestPlug( "testIn" )
		self.assertEqual( p1.getName(), "testIn" )
		self.assertEqual( p1.direction(), Gaffer.Plug.Direction.In )
		self.assertEqual( p1.getFlags(), Gaffer.Plug.Flags.Default )

		n1 = Gaffer.Node()
		n1.addChild( p1 )
		self.assertEqual( n1["testIn"], p1 )

		n2 = Gaffer.Node()
		n2.addChild( TestPlug( name = "testOut", direction = Gaffer.Plug.Direction.Out ) )
		n2.addChild( Gaffer.IntPlug( name = "intOut", direction = Gaffer.Plug.Direction.Out ) )

		# check that accepts input and setInput can be overridden

		self.failUnless( n1["testIn"].acceptsInput( n2["testOut"] ) )
		self.failIf( n1["testIn"].acceptsInput( n2["intOut"] ) )

		self.assertRaises( RuntimeError, n1["testIn"].setInput, n2["intOut"] )
		self.assertEqual( n1["testIn"].inputHasBeenSet, False )

		n1["testIn"].setInput( n2["testOut"] )
		self.assertEqual( n1["testIn"].inputHasBeenSet, True )
		self.assertEqual( n1["testIn"].getInput(), n2["testOut"] )

		# check that acceptsParent can be overridden

		p2 = TestPlug()
		self.assertRaises( RuntimeError, Gaffer.CompoundPlug().addChild, p2 )

		# try making a counterpart

		p3 = p2.createCounterpart( "ll", Gaffer.Plug.Direction.Out )
		self.assertEqual( p3.getName(), "ll" )
		self.assertEqual( p3.direction(), Gaffer.Plug.Direction.Out )

	def testRemovePlugRemovesInputs( self ) :

		s = Gaffer.ScriptNode()

		s["n1"] = Gaffer.Node()
		s["n2"] = Gaffer.Node()

		s["n1"]["o"] = Gaffer.IntPlug( direction = Gaffer.Plug.Direction.Out )

		s["n2"]["i"] = Gaffer.IntPlug()
		s["n2"]["c"] = Gaffer.CompoundPlug()
		s["n2"]["c"]["i"] = Gaffer.IntPlug()

		s["n2"]["i"].setInput( s["n1"]["o"] )
		s["n2"]["c"]["i"].setInput( s["n1"]["o"] )

		self.failUnless( s["n2"]["i"].getInput().isSame( s["n1"]["o"] ) )
		self.failUnless( s["n2"]["c"]["i"].getInput().isSame(  s["n1"]["o"] ) )
		self.assertEqual( len( s["n1"]["o"].outputs() ), 2 )

		with Gaffer.UndoContext( s ) :

			del s["n2"]["i"]
			del s["n2"]["c"]["i"]

		self.assertEqual( len( s["n1"]["o"].outputs() ), 0 )

		s.undo()

		self.failUnless( s["n2"]["i"].getInput().isSame( s["n1"]["o"] ) )
		self.failUnless( s["n2"]["c"]["i"].getInput().isSame(  s["n1"]["o"] ) )
		self.assertEqual( len( s["n1"]["o"].outputs() ), 2 )

	def testRemovePlugRemovesOutputs( self ) :

		s = Gaffer.ScriptNode()

		s["n1"] = Gaffer.Node()
		s["n2"] = Gaffer.Node()

		s["n1"]["o"] = Gaffer.IntPlug( direction = Gaffer.Plug.Direction.Out )

		s["n2"]["i"] = Gaffer.IntPlug()

		s["n2"]["i"].setInput( s["n1"]["o"] )

		self.failUnless( s["n2"]["i"].getInput().isSame( s["n1"]["o"] ) )
		self.assertEqual( len( s["n1"]["o"].outputs() ), 1 )

		with Gaffer.UndoContext( s ) :

			removedPlug = s["n1"]["o"]
			del s["n1"]["o"]

		self.assertEqual( len( removedPlug.outputs() ), 0 )

		s.undo()

		self.failUnless( s["n2"]["i"].getInput().isSame( s["n1"]["o"] ) )
		self.assertEqual( len( s["n1"]["o"].outputs() ), 1 )
		self.failUnless( s["n1"]["o"].isSame( removedPlug ) )

	def testDefaultFlags( self ) :

		p = Gaffer.Plug()
		self.failUnless( p.getFlags( Gaffer.Plug.Flags.Serialisable ) )

	def testSerialisableFlag( self ) :

		s = Gaffer.ScriptNode()

		s["n"] = GafferTest.AddNode()

		self.failUnless( s["n"]["op1"].getFlags( Gaffer.Plug.Flags.Serialisable ) )

		s["n"]["op1"].setValue( 20 )
		ss = s.serialise()

		s = Gaffer.ScriptNode()
		s.execute( ss )

		self.assertEqual( s["n"]["op1"].getValue(), 20 )

		s["n"]["op1"].setFlags( Gaffer.Plug.Flags.Serialisable, False )
		ss = s.serialise()

		self.failIf( "op1" in ss )

		s = Gaffer.ScriptNode()
		s.execute( ss )

		self.assertEqual( s["n"]["op1"].getValue(), 0 )

	def testFlagSerialisation( self ) :

		s = Gaffer.ScriptNode()
		s["n"] = Gaffer.Node()
		s["n"]["p"] = Gaffer.Plug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )

		ss = s.serialise()

		s = Gaffer.ScriptNode()
		s.execute( ss )

		self.assertEqual( s["n"]["p"].getFlags(), Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )

	def testFlagsNeverSerialisedAsAll( self ) :

		# it's a terrible idea to serialise a set of flags that happen to be All
		# as All, rather than as the or-ing of the specific flags, because when new
		# flags are introduced in the future (and default to off) they will suddenly
		# pop on when loading old files.

		s = Gaffer.ScriptNode()
		s["n"] = Gaffer.Node()
		s["n"]["p"] = Gaffer.Plug( flags = Gaffer.Plug.Flags.All )

		ss = s.serialise()

		self.failIf( "All" in ss )

		s = Gaffer.ScriptNode()
		s.execute( ss )

		self.assertEqual( s["n"]["p"].getFlags(), Gaffer.Plug.Flags.All )

	def testAcceptsInputsFlag( self ) :

		pOut = Gaffer.Plug( direction = Gaffer.Plug.Direction.Out )

		pIn1 = Gaffer.Plug( flags = Gaffer.Plug.Flags.Default & ~Gaffer.Plug.Flags.AcceptsInputs )
		self.assertEqual( pIn1.getFlags( Gaffer.Plug.Flags.AcceptsInputs ), False )
		self.assertEqual( pIn1.acceptsInput( pOut ), False )

		pIn2 = Gaffer.Plug()
		self.assertEqual( pIn2.getFlags( Gaffer.Plug.Flags.AcceptsInputs ), True )
		self.assertEqual( pIn2.acceptsInput( pOut ), True )

	def testReadOnlyDefaultsToOff( self ) :

		p = Gaffer.Plug()
		self.failIf( p.getFlags( Gaffer.Plug.Flags.ReadOnly ) )

	def testReadOnlyDisallowsInputs( self ) :

		self.failUnless( Gaffer.Plug.Flags.All & Gaffer.Plug.Flags.ReadOnly )

		p1 = Gaffer.Plug()
		p2 = Gaffer.Plug()
		self.failUnless( p1.acceptsInput( p2 ) )
		# read-only plugs can still be used as connection sources
		p2.setFlags( Gaffer.Plug.Flags.ReadOnly, True )
		self.failUnless( p1.acceptsInput( p2 ) )
		# but cannot be used as destinations
		self.failIf( p2.acceptsInput( p1 ) )
		self.assertRaises( RuntimeError, p2.setInput, p1 )

	def testOutputPlugsDisallowReadOnly( self ) :

		p = Gaffer.Plug( direction = Gaffer.Plug.Direction.Out )
		self.assertRaises( RuntimeError, p.setFlags, Gaffer.Plug.Flags.ReadOnly, True )

		self.assertRaises(
			RuntimeError,
			Gaffer.Plug,
			direction = Gaffer.Plug.Direction.Out,
			flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.ReadOnly
		)

	def testRepr( self ) :

		p1 = Gaffer.Plug(
			"p",
			Gaffer.Plug.Direction.Out,
			Gaffer.Plug.Flags.Default & ~Gaffer.Plug.Flags.AcceptsInputs,
		)

		p2 = eval( repr( p1 ) )

		self.assertEqual( p1.getName(), p2.getName() )
		self.assertEqual( p1.direction(), p2.direction() )
		self.assertEqual( p1.getFlags(), p2.getFlags() )

	def testCreateCounterpart( self ) :

		p = Gaffer.Plug(
			"p",
			Gaffer.Plug.Direction.Out,
			Gaffer.Plug.Flags.Default & ~Gaffer.Plug.Flags.AcceptsInputs,
		)

		p2 = p.createCounterpart( "p2", Gaffer.Plug.Direction.In )

		self.assertEqual( p2.getName(), "p2" )
		self.assertEqual( p2.direction(), Gaffer.Plug.Direction.In )
		self.assertEqual( p2.getFlags(), p.getFlags() )

	def testSource( self ) :

		p1 = Gaffer.Plug( "p1" )
		p2 = Gaffer.Plug( "p2" )
		p3 = Gaffer.Plug( "p3" )

		self.assertTrue( p1.source().isSame( p1 ) )
		self.assertTrue( p2.source().isSame( p2 ) )
		self.assertTrue( p3.source().isSame( p3 ) )

		p2.setInput( p1 )
		self.assertTrue( p1.source().isSame( p1 ) )
		self.assertTrue( p2.source().isSame( p1 ) )
		self.assertTrue( p3.source().isSame( p3 ) )

		p3.setInput( p2 )
		self.assertTrue( p1.source().isSame( p1 ) )
		self.assertTrue( p2.source().isSame( p1 ) )
		self.assertTrue( p3.source().isSame( p1 ) )

	def testRejectsInputFromSelf( self ) :

		p = Gaffer.Plug()
		self.assertFalse( p.acceptsInput( p ) )

	def testReadOnlySerialisation( self ) :

		s = Gaffer.ScriptNode()
		s["n"] = Gaffer.Node()
		s["n"]["p"] = Gaffer.Plug( flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
		s["n"]["p2"] = Gaffer.Plug( direction=Gaffer.Plug.Direction.Out, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
		s["n"]["p"].setInput( s["n"]["p2"] )
		s["n"]["p"].setFlags( Gaffer.Plug.Flags.ReadOnly, True )
		ss = s.serialise()

		s2 = Gaffer.ScriptNode()
		s2.execute( ss )

		self.assertTrue( s2["n"]["p"].getInput().isSame( s2["n"]["p2"] ) )
		self.assertEqual( s2["n"]["p"].getFlags( Gaffer.Plug.Flags.ReadOnly ), True )

	def testReadOnlyRepr( self ) :

		p1 = Gaffer.Plug(
			"p",
			flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.ReadOnly,
		)

		p2 = eval( repr( p1 ) )

		self.assertEqual( p1.getName(), p2.getName() )
		self.assertEqual( p1.direction(), p2.direction() )
		self.assertEqual( p1.getFlags(), p2.getFlags() )

	def testNoFlagsRepr( self ) :

		p1 = Gaffer.Plug(
			"p",
			Gaffer.Plug.Direction.Out,
			Gaffer.Plug.Flags.None,
		)

		p2 = eval( repr( p1 ) )

		self.assertEqual( p1.getName(), p2.getName() )
		self.assertEqual( p1.direction(), p2.direction() )
		self.assertEqual( p1.getFlags(), p2.getFlags() )

	def testAllFlagPermutationsRepr( self ) :

		for i in range( 0, int( Gaffer.Plug.Flags.All ) + 1 ) :

			p1 = Gaffer.Plug(
				flags = Gaffer.Plug.Flags( i )
			)

			p2 = eval( repr( p1 ) )

			self.assertEqual( p1.getFlags(), p2.getFlags() )

	def testFlagReprAlwaysIncludesDefault( self ) :

		# we always need to serialise the flags by adding and removing things
		# from the default flags, so that if we add new default flags in the future,
		# they will default to on when loaded from file.

		for i in range( 0, int( Gaffer.Plug.Flags.All ) + 1 ) :

			if i == Gaffer.Plug.Flags.Default :
				continue

			p = Gaffer.Plug(
				flags = Gaffer.Plug.Flags( i )
			)
			self.assertTrue( "Gaffer.Plug.Flags.Default" in repr( p ) )

if __name__ == "__main__":
	unittest.main()


text:
<?php

namespace LF14\SysMgmtBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use LF14\SysMgmtBundle\Model\Contact;
use LF14\SysMgmtBundle\Form\Type\ContactType;
use LF14\SysMgmtBundle\Model\ContactPeer;
use LF14\SysMgmtBundle\Model\ContactQuery;

class ContactController extends Controller
{

	public function listAction() {

		$contacts = ContactQuery::create()->orderByName()->find();

		$tmpl_vars = Array();

		if (count($contacts) > 0) {
			$tmpl_vars['contacts'] = $contacts;
		}

		return $this->render('LF14SysMgmtBundle:Admin:contact.list.html.twig', $tmpl_vars);
	}

    public function formAction($id) {

    	if (!$id) {
    		$contact = new Contact();
    		$form = $this->createForm(new ContactType(), $contact);
    	} else {
    		$contact = ContactQuery::create()->findPk($id);
    	}

    	$form = $this->createForm(new ContactType(), $contact);

    	$request = $this->getRequest();

    	if ($request->getMethod() === 'POST') {

    		$form->handleRequest($request);

    		if ($form->isValid()) {
    			if (!$form->get('cancel')->isClicked()) {
	    			$contact->save();
    			}
    			return $this->redirect($this->generateUrl('lf14sm_admin_contacts'));
    		}
    	}

    	return $this->render('LF14SysMgmtBundle:Admin:contact.form.html.twig', array(
    		'form' => $form->createView(),
    	));

    }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * essentielb Pyxis
 *
 * DEVICE: pyxis_boulanger
 * MODEL: Essentielb-Pixis
 */
final class pyxis5fboulanger {
    public static final String DATA = "essentielb|Pyxis|";
}


text:
var utils = require('./utils');
var dom = require('./dom');

module.exports = function (element, options) {
    options = utils.defaults({
        drag:          true,
        borderWidth:   2,
        borderColor:   'white',
        borderPadding: 10
    }, options);

    element.classList.add('kikka-container', 'kikka-sweep');

    var img = element.getElementsByTagName('img')[1];

    var min = 0;
    var max = img.width - options.borderWidth;
    var x   = max / 2;

    var cropper = document.createElement('span');
    cropper.style.borderRightWidth = options.borderWidth + 'px';
    cropper.style.borderRightColor = options.borderColor;
    cropper.style.borderRightStyle = 'solid';
    cropper.appendChild(element.removeChild(img));
    element.appendChild(cropper);

    var rangeInput   = document.createElement('input');
    rangeInput.type  = 'range';
    rangeInput.min   = min;
    rangeInput.max   = max;
    rangeInput.step  = (max - min) / 50;
    rangeInput.value = x;
    rangeInput.addEventListener('input', function(evt) {
        setX(parseInt(rangeInput.value));
    }, false);
    element.appendChild(rangeInput);

    function setX(newX) {
        x = utils.clamp(newX, 0, img.width - options.borderWidth);
        cropper.style.width = x + 'px';
    }

    setX(img.width / 2);

    var dragging = false;

    function mousemove(evt) {
        var ex = evt.pageX - dom.getPos(element).x;
        if (ex > x - options.borderPadding && ex < x + options.borderWidth + options.borderPadding) {
            element.style.cursor = 'col-resize';
            dragging = true;
        } else {
            element.style.cursor = 'default';
            dragging = false;
        }

        evt.stopPropagation();
        evt.preventDefault();
    }

    function dragstart(evt) {
        if (dragging) {
            document.addEventListener('mousemove', dragmove, false);
            document.addEventListener('mouseup', dragend, false);
            element.removeEventListener('mousemove', mousemove, false);
            element.removeEventListener('mousedown', dragstart, false);

            dragging = false;
            dragmove(evt);
        }
    }

    function dragmove(evt) {
        var pos = evt.pageX - dom.getPos(element).x;
        setX(pos - options.borderWidth / 2);
        rangeInput.value = pos;

        evt.stopPropagation();
        evt.preventDefault();
    }

    function dragend(evt) {
        document.removeEventListener('mousemove', dragmove, false);
        document.removeEventListener('mouseup', dragend, false);
        element.addEventListener('mousemove', mousemove, false);
        element.addEventListener('mousedown', dragstart, false);

        mousemove(evt);
    }

    if (options.drag) {
        element.addEventListener('mousemove', mousemove, false);
        element.addEventListener('mousedown', dragstart, false);
    } else {
        element.addEventListener('mousemove', dragmove, false);
    }

    function touchstart(evt) {
        var ex = evt.touches[0].pageX - dom.getPos(element).x;
        if (ex > x - options.borderPadding && ex < x + options.borderWidth + options.borderPadding) {
            document.addEventListener('touchmove', touchmove, false);
            document.addEventListener('touchend', touchend, false);
            element.removeEventListener('touchstart', touchstart, false);

            touchmove(evt);
        }
    }

    function touchmove(evt) {
        var pos = evt.touches[0].pageX - dom.getPos(element).x;
        setX(pos - options.borderWidth / 2);
        rangeInput.value = pos;

        evt.stopPropagation();
        evt.preventDefault();
    }

    function touchend() {
        document.removeEventListener('touchmove', touchmove, false);
        document.removeEventListener('touchend', touchend, false);
        element.addEventListener('touchstart', touchstart, false);
    }

    element.addEventListener('touchstart', touchstart, false);

    return {
        element: element,
        remove: function() {
            element.classList.remove('kikka-container', 'kikka-sweep');

            element.appendChild(cropper.removeChild(img));
            element.removeChild(cropper);

            element.removeChild(rangeInput);

            document.removeEventListener('mousemove', dragmove, false);
            document.removeEventListener('mouseup', dragend, false);
            element.removeEventListener('mousemove', mousemove, false);
            element.removeEventListener('mousedown', dragstart, false);
            element.removeEventListener('mousemove', dragmove, false);

            document.removeEventListener('touchmove', touchmove, false);
            document.removeEventListener('touchend', touchend, false);
            element.removeEventListener('touchstart', touchstart, false);
        }
    };
};


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.trello.rxlifecycle4;

import org.junit.Before;
import org.junit.Test;

import io.reactivex.rxjava3.processors.PublishProcessor;
import io.reactivex.rxjava3.subjects.PublishSubject;
import io.reactivex.rxjava3.subscribers.TestSubscriber;

public class UntilLifecycleTransformerFlowableTest {

    PublishProcessor<String> stream;
    PublishSubject<String> lifecycle;

    @Before
    public void setup() {
        stream = PublishProcessor.create();
        lifecycle = PublishSubject.create();
    }

    @Test
    public void noEvent() {
        TestSubscriber<String> testSubscriber = stream
            .compose(RxLifecycle.<String, String>bind(lifecycle))
            .test();

        stream.onNext("1");
        stream.onNext("2");
        testSubscriber.assertValues("1", "2");
        testSubscriber.assertNotComplete();
    }

    @Test
    public void oneEvent() {
        TestSubscriber<String> testSubscriber = stream
            .compose(RxLifecycle.<String, String>bind(lifecycle))
            .test();

        stream.onNext("1");
        lifecycle.onNext("stop");
        stream.onNext("2");

        testSubscriber.assertValues("1");
        testSubscriber.assertComplete();
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

extern NSString *const UniDBErrorDomain;

@interface UniDB : NSObject

- (BOOL)open:(NSString *)file error:(NSError ** _Nullable)error;

- (BOOL)close;

- (BOOL)executeUpdate:(NSString *)sql arguments:(NSArray * _Nullable)arguments error:(NSError ** _Nullable)error;

- (BOOL)executeUpdate:(NSString *)sql stmtBlock:(void (^)(sqlite3_stmt *stmt, int idx))stmtBlock error:(NSError **)error;

- (BOOL)executeQuery:(NSString *)sql arguments:(NSArray * _Nullable)arguments resultBlock:(void (^)(sqlite3_stmt *stmt, bool *stop))resultBlock error:(NSError ** _Nullable)error;

- (BOOL)executeQuery:(NSString *)sql stmtBlock:(void (^)(sqlite3_stmt *stmt, int idx))stmtBlock resultBlock:(void (^)(sqlite3_stmt *stmt, bool *stop))resultBlock error:(NSError ** _Nullable)error;

- (NSArray *)executeQuery:(NSString *)sql stmtBlock:(void (^)(sqlite3_stmt *stmt, int idx))stmtBlock error:(NSError ** _Nullable)error;

- (NSArray *)executeQuery:(NSString *)sql arguments:(NSArray * _Nullable)arguments error:(NSError ** _Nullable)error;

- (BOOL)beginTransaction;

- (BOOL)commit;

@end

NS_ASSUME_NONNULL_END


text:
#include "El.hpp"

namespace El {

template<typename T>
void EntrywiseFill( Matrix<T>& A, function<T(void)> func )
{
    DEBUG_ONLY(CSE cse("EntrywiseFill"))
    const Int m = A.Height();
    const Int n = A.Width();
    for( Int j=0; j<n; ++j )
        for( Int i=0; i<m; ++i )
            A.Set( i, j, func() );
}

template<typename T>
void EntrywiseFill( AbstractDistMatrix<T>& A, function<T(void)> func )
{ EntrywiseFill( A.Matrix(), func ); }

template<typename T>
void EntrywiseFill( AbstractBlockDistMatrix<T>& A, function<T(void)> func )
{ EntrywiseFill( A.Matrix(), func ); }

template<typename T>
void EntrywiseFill( DistMultiVec<T>& A, function<T(void)> func )
{ EntrywiseFill( A.Matrix(), func ); }

#define PROTO(T) \
  template void EntrywiseFill \
  ( Matrix<T>& A, function<T(void)> func ); \
  template void EntrywiseFill \
  ( AbstractDistMatrix<T>& A, function<T(void)> func ); \
  template void EntrywiseFill \
  ( AbstractBlockDistMatrix<T>& A, function<T(void)> func ); \
  template void EntrywiseFill \
  ( DistMultiVec<T>& A, function<T(void)> func );

#define EL_ENABLE_QUAD
#include "El/macros/Instantiate.h"

} // namespace El


text:
from fruit.models import Image

from ..users import user_to_data
from ..utils import get_full_url

CAPTION_MAX_LENGTH = Image._meta.get_field("caption").max_length

CREATE_IMAGE_BAD_ARGS = [
    (
        {"caption": "c" * (CAPTION_MAX_LENGTH + 1)},
        {"caption": [f"Ensure this field has no more than {CAPTION_MAX_LENGTH} characters."]},
    ),
    ({"caption": None}, {"caption": ["This field may not be null."]}),
    ({"image": None}, {"image": ["This field may not be null."]}),
    (
        {"image": "rubbish"},
        {"image": ["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]},
    ),
]

def image_to_data(image, response):
    return {
        "id": image.id,
        "image": get_full_url(response, image.image.url),
        "caption": image.caption,
        "author": user_to_data(image.author, response),
    }