text:
<?php

namespace Biz\OpenCourse\Processor;

use Topxia\Service\Common\ServiceKernel;

class CourseProcessorFactory
{
    public static function create($type)
    {
        if (!in_array($type, array('normal', 'live', 'open', 'liveOpen', 'course', 'openCourse'))) {
            throw new \Exception('课程类型不存在');
        }

        if (in_array($type, array('normal', 'live', 'course'))) {
            return ServiceKernel::instance()->createService('Course:CourseService');
        } elseif (in_array($type, array('open', 'liveOpen', 'openCourse'))) {
            return ServiceKernel::instance()->createService('OpenCourse:OpenCourseService');
        }
    }
}


text:
TK_DLL_FILE="tk85.dll"

# Tk's version number.
TK_VERSION='8.5'
TK_MAJOR_VERSION='8'
TK_MINOR_VERSION='5'
TK_PATCH_LEVEL='.9'

# -D flags for use with the C compiler.
TK_DEFS='-DPACKAGE_NAME=\"\" -DPACKAGE_TARNAME=\"\" -DPACKAGE_VERSION=\"\" -DPACKAGE_STRING=\"\" -DPACKAGE_BUGREPORT=\"\" -Dinline=__inline -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_UXTHEME_H=1 -DTCL_CFG_OPTIMIZED=1 -DTCL_CFG_DEBUG=1 '

# Flag, 1: we built a shared lib, 0 we didn't
TK_SHARED_BUILD=1

# This indicates if Tk was build with debugging symbols
TK_DBGX=

# The name of the Tk library (may be either a .a file or a shared library):
TK_LIB_FILE='tk85.lib'

# Additional libraries to use when linking Tk.
TK_LIBS='user32.lib advapi32.lib ws2_32.lib gdi32.lib comdlg32.lib imm32.lib comctl32.lib shell32.lib uuid.lib'

# Top-level directory in which Tcl's platform-independent files are
# installed.
TK_PREFIX='F:/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tcltk'

# Top-level directory in which Tcl's platform-specific files (e.g.
# executables) are installed.
TK_EXEC_PREFIX='F:/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tcltk'

# -l flag to pass to the linker to pick up the Tcl library
TK_LIB_FLAG='-ltk85'

# String to pass to linker to pick up the Tk library from its
# build directory.
TK_BUILD_LIB_SPEC='-L/f/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tk/win -ltk85'

# String to pass to linker to pick up the Tk library from its
# installed directory.
TK_LIB_SPEC='-LF:/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tcltk/lib -ltk85'

# Location of the top-level source directory from which Tk was built.
# This is the directory that contains a README file as well as
# subdirectories such as generic, unix, etc.  If Tk was compiled in a
# different place than the directory containing the source files, this
# points to the location of the sources, not the location where Tk was
# compiled.
TK_SRC_DIR='/f/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tk'

# Needed if you want to make a 'fat' shared library library
# containing tk objects or link a different wish.
TK_CC_SEARCH_FLAGS=''
TK_LD_SEARCH_FLAGS=''

# The name of the Tk stub library (.a):
TK_STUB_LIB_FILE='tkstub85.lib'

# -l flag to pass to the linker to pick up the Tk stub library
TK_STUB_LIB_FLAG='-ltkstub85'

# String to pass to linker to pick up the Tk stub library from its
# build directory.
TK_BUILD_STUB_LIB_SPEC='-L/f/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tk/win -ltkstub85'

# String to pass to linker to pick up the Tk stub library from its
# installed directory.
TK_STUB_LIB_SPEC='-LF:/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tcltk/lib -ltkstub85'

# Path to the Tk stub library in the build directory.
TK_BUILD_STUB_LIB_PATH='/f/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tk/win/tkstub85.lib'

# Path to the Tk stub library in the install directory.
TK_STUB_LIB_PATH='F:/as/apy-trunk/build/py2_7_2-win32-x86-apy27-rrun/tcltk/lib/tkstub85.lib'

redpajama_set_name: RedPajamaGithub


text:
using System.IO;
using NUnit.Framework;
using CodeWiseLLC.RefactorableSettingsGenerator;

namespace RefactorableSettingsGenerator.Tests
{
    [TestFixture]
    public class CodeGenerationTests
    {
        [Test]
        public void GeneratedCodeMatchesTarget()
        {
            var targetText = File.ReadAllText("Settings.cs.txt");

            var code = SettingsCodeGenerator.GenerateCodeFrom("Settings.settings");

            code.ShouldEqualWithDiff(targetText);
        }
    }

    public enum DiffStyle
    {
        Full,
        Minimal
    }
}


text:
module Admin
  class ConstraintsController < Admin::ApplicationController
    # To customize the behavior of this controller,
    # simply overwrite any of the RESTful actions. For example:
    #
    # def index
    #   super
    #   @resources = Constraint.all.paginate(10, params[:page])
    # end

    # Define a custom finder by overriding the `find_resource` method:
    # def find_resource(param)
    #   Constraint.find_by!(slug: param)
    # end

    # See https://administrate-docs.herokuapp.com/customizing_controller_actions
    # for more information
  end
end


text:
from __future__ import print_function
import vdc_api_call as vdc
import getpass
import json
import os
import sys
import pprint
import argparse
import re
from subprocess import call

# STEP: Parse the command line arguments
parser = argparse.ArgumentParser()
##parser.add_argument("-c", "--config", default=os.path.join(os.path.expanduser('~'), '.vdcapi'),
##                help="path/name of the config file to be used for the API URL and API keys (default is ~/.vdcapi)")
parser.add_argument("-f", "--filename", help="name of input file with the cluster setup information in JSON format")
parser.add_argument("-k", "--sshkeyfile", help="path/name value for ansible_ssh_private_key_file")
parser.add_argument("-u", "--sshuser", default="root", help="value for ansible_user")
datafile = parser.parse_args().filename
sshkeyFile = parser.parse_args().sshkeyfile
sshUser = parser.parse_args().sshuser

# STEP: Load the cluster data from the JSON file
with open(datafile) as json_file:
   zonesDict = json.load(json_file)
ansiblehostsfile = datafile.split('.')[0] + "_ansible_hosts"

# STEP: Open ansiblehostsfile
with open(ansiblehostsfile, 'w') as outfile:
   outfile.write("[%s_HOSTS]\n" % datafile.split('.')[0])
   hostnum = 0
   # STEP: Write hosts information
   for z in zonesDict:
      if zonesDict[z]['internetipaddress'] != 'MISSING':
         hostnum = hostnum + 1
         print("HOST %d>> %s ansible_host=%s ansible_port=%d ansible_user=%s ansible_ssh_private_key_file=%s" % (hostnum, zonesDict[z]['virtualmachinename'], zonesDict[z]['publicipaddress'], zonesDict[z]['publicport'], sshUser, sshkeyFile))
         outfile.write("%s ansible_host=%s ansible_port=%d ansible_user=%s ansible_ssh_private_key_file=%s\n" % (zonesDict[z]['virtualmachinename'], zonesDict[z]['publicipaddress'], zonesDict[z]['publicport'], sshUser, sshkeyFile))

# Step: File write complete
print("File %s written. Program terminating." % ansiblehostsfile)


text:
package org.apache.maven.execution;

import java.util.List;
import java.util.Optional;

import static java.util.Collections.emptyList;

/**
 * This class holds the information required to enable resuming a Maven build with {@code --resume}.
 */
public class BuildResumptionData
{
    /**
     * The project where the next build could resume from.
     */
    private final String resumeFrom;

    /**
     * List of projects to skip.
     */
    private final List<String> projectsToSkip;

    public BuildResumptionData ( final String resumeFrom, final List<String> projectsToSkip )
    {
        this.resumeFrom = resumeFrom;
        this.projectsToSkip = projectsToSkip;
    }

    /**
     * Returns the project where the next build can resume from.
     * This is usually the first failed project in the order of the reactor.
     * @return An optional containing the group and artifact id of the project. It does not make sense to resume
     *   the build when the first project of the reactor has failed, so then it will return an empty optional.
     */
    public Optional<String> getResumeFrom()
    {
        return Optional.ofNullable( this.resumeFrom );
    }

    /**
     * A list of projects which can be skipped in the next build.
     * @return A list of group and artifact ids. Can be empty when no projects can be skipped.
     */
    public List<String> getProjectsToSkip()
    {
        return ( projectsToSkip != null ) ? projectsToSkip : emptyList();
    }
}


text:
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE QuasiQuotes                #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeFamilies               #-}

module UserService.Database
  (setupDb, allUsers)
where

import           Data.Text
import           Data.Time
-- import           Database.PostgreSQL.Simple
-- import           Database.PostgreSQL.Simple.FromRow
-- import           Database.PostgreSQL.Simple.ToField
-- import           Database.PostgreSQL.Simple.ToRow
import qualified Seeds             as Seeds (users)
import           UserService.Types

-- instance FromRow Address where
--   fromRow = Address <$>
--       field <*>
--       field <*>
--       field <*>
--       field <*>
--       field

-- instance ToRow Address where
--   toRow Address{..} =
--     [ toField street
--     , toField city
--     , toField state
--     , toField aptNumber
--     , toField zipCode
--     ]

-- instance FromRow User where
--   fromRow = User <$>
--       field <*>
--       field <*>
--       field <*>
--       field <*>
--       field <*>
--       field

-- instance ToRow User where
--   toRow User{..} =
--     [ toField firstName
--     , toField lastName
--     , toField email
--     , toField address
--     , toField phone
--     , toField dob
--     ]

allUsers = Seeds.users
setupDb = undefined

-- setupDb = do
--   conn <- connect defaultConnectInfo { connectDatabase = "user_clone"}
--   execute conn "INSERT INTO users \
--     \ (first_name, last_name, email, address, phone, dob) \
--     \ VALUES (?,?,?,?,?,?)" Seeds.users
  -- putStrLn "setup database"

-- $(makeAdaptorAndInstance "pUser" ''User)

-- usersTable :: Table ( Column PGText
--                     , Column PGText
--                     , Column PGText
--                     , Column PGText
--                     , Maybe Column PGText
--                     , Column PGText
--                     , Column PGDate)
-- usersTable = Table "usersTable" (p7 ( required "firstName"
--                                     , required "lastName"
--                                     , required "email"
--                                     , optional "address"
--                                     , required "phone"
--                                     , required "dob" ))


text:
@implementation VKApiPhotos
- (VKRequest *)getUploadServer:(NSInteger)albumId
{
    return [self prepareRequestWithMethodName:@"getUploadServer" parameters:@{ VK_API_ALBUM_ID : @(albumId) }];
}

- (VKRequest *)getUploadServer:(NSInteger)albumId andGroupId:(NSInteger)groupId
{
    return [self prepareRequestWithMethodName:@"getUploadServer" parameters:@{ VK_API_ALBUM_ID : @(albumId), VK_API_GROUP_ID : @(groupId) }];
}

- (VKRequest *)getWallUploadServer
{
    return [self prepareRequestWithMethodName:@"getWallUploadServer" parameters:nil];
}

- (VKRequest *)getWallUploadServer:(NSInteger)groupId
{
    return [self prepareRequestWithMethodName:@"getWallUploadServer" parameters:@{ VK_API_GROUP_ID : @(groupId) }];
}

- (VKRequest *)saveWallPhoto:(NSDictionary *)params
{
    return [self prepareRequestWithMethodName:@"saveWallPhoto" parameters:params modelClass:[VKPhotoArray class]];
}

- (VKRequest *)save:(NSDictionary *)params
{
    return [self prepareRequestWithMethodName:@"save" parameters:params modelClass:[VKPhotoArray class]];
}

@end


text:
cookbook_path ["cookbooks", "site-cookbooks"]
node_path     "nodes"
role_path     "roles"
data_bag_path "data_bags"
#encrypted_data_bag_secret "data_bag_key"

environment_path "environments"

knife[:berkshelf_path] = "cookbooks"


text:
<?php

// Required
$php_ok = (function_exists('version_compare') && version_compare(phpversion(), '5.2.0', '>='));
$simplexml_ok = extension_loaded('simplexml');
$json_ok = (extension_loaded('json') && function_exists('json_encode') && function_exists('json_decode'));
$spl_ok = extension_loaded('spl');
$pcre_ok = extension_loaded('pcre');
if (function_exists('curl_version'))
{
	$curl_version = curl_version();
	$curl_ok = (function_exists('curl_exec') && in_array('https', $curl_version['protocols'], true));
}
$file_ok = (function_exists('file_get_contents') && function_exists('file_put_contents'));

// Optional, but recommended
$openssl_ok = (extension_loaded('openssl') && function_exists('openssl_sign'));
$zlib_ok = extension_loaded('zlib');

// Optional
$apc_ok = extension_loaded('apc');
$xcache_ok = extension_loaded('xcache');
$memcached_ok = extension_loaded('memcached');
$memcache_ok = extension_loaded('memcache');
$mc_ok = ($memcache_ok || $memcached_ok);
$pdo_ok = extension_loaded('pdo');
$pdo_sqlite_ok = extension_loaded('pdo_sqlite');
$sqlite2_ok = extension_loaded('sqlite');
$sqlite3_ok = extension_loaded('sqlite3');
$sqlite_ok = ($pdo_ok && $pdo_sqlite_ok && ($sqlite2_ok || $sqlite3_ok));

// Other
$int64_ok = (PHP_INT_MAX === 9223372036854775807);
$ini_memory_limit = get_cfg_var('memory_limit');
$ini_open_basedir = get_cfg_ini('open_basedir');
$ini_safe_mode = get_cfg_ini('safe_mode');
$ini_zend_enable_gc = get_cfg_ini('zend.enable_gc');

function get_cfg_ini($config)
{
	$cfg_value = get_cfg_var($config);

	if ($cfg_value === false || $cfg_value === '' || $cfg_value === 0)
	{
		return false;
	}
	elseif ($cfg_value === true || $cfg_value === '1' || $cfg_value === 1)
	{
		return true;
	}
}

function is_windows()
{
	return strtolower(substr(PHP_OS, 0, 3)) === 'win';
}

// CLI display
function success($s = 'Yes')
{
	return is_windows() ? $s : "\033[1;37m\033[42m " . $s . " \033[0m";
}

function info($s = 'Info')
{
	return is_windows() ? $s : "\033[1;37m\033[44m " . $s . " \033[0m";
}

function failure($s = 'No ')
{
	return is_windows() ? $s : "\033[1;37m\033[41m " . $s . " \033[0m";
}

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

echo PHP_EOL;

echo info('AWS SDK for PHP') . PHP_EOL;
echo 'PHP Environment Compatibility Test (CLI)' . PHP_EOL;
echo '----------------------------------------' . PHP_EOL;
echo PHP_EOL;

echo 'PHP 5.2 or newer............ ' . ($php_ok ? (success() . ' ' . phpversion()) : failure()) . PHP_EOL;
echo '64-bit architecture......... ' . ($int64_ok ? success() : failure()) . (is_windows() ? ' (see note below)' : '') . PHP_EOL;
echo 'cURL with SSL............... ' . ($curl_ok ? (success() . ' ' . $curl_version['version'] . ' (' . $curl_version['ssl_version'] . ')') : failure($curl_version['version'] . (in_array('https', $curl_version['protocols'], true) ? ' (with ' . $curl_version['ssl_version'] . ')' : ' (without SSL)'))) . PHP_EOL;
echo 'Standard PHP Library........ ' . ($spl_ok ? success() : failure()) . PHP_EOL;
echo 'SimpleXML................... ' . ($simplexml_ok ? success() : failure()) . PHP_EOL;
echo 'JSON........................ ' . ($json_ok ? success() : failure()) . PHP_EOL;
echo 'PCRE........................ ' . ($pcre_ok ? success() : failure()) . PHP_EOL;
echo 'File system read/write...... ' . ($file_ok ? success() : failure()) . PHP_EOL;
echo 'OpenSSL extension........... ' . ($openssl_ok ? success() : failure()) . PHP_EOL;
echo 'Zlib........................ ' . ($zlib_ok ? success() : failure()) . PHP_EOL;
echo 'APC......................... ' . ($apc_ok ? success() : failure()) . PHP_EOL;
echo 'XCache...................... ' . ($xcache_ok ? success() : failure()) . PHP_EOL;
echo 'Memcache.................... ' . ($memcache_ok ? success() : failure()) . PHP_EOL;
echo 'Memcached................... ' . ($memcached_ok ? success() : failure()) . PHP_EOL;
echo 'PDO......................... ' . ($pdo_ok ? success() : failure()) . PHP_EOL;
echo 'SQLite 2.................... ' . ($sqlite2_ok ? success() : failure()) . PHP_EOL;
echo 'SQLite 3.................... ' . ($sqlite3_ok ? success() : failure()) . PHP_EOL;
echo 'PDO-SQLite driver........... ' . ($pdo_sqlite_ok ? success() : failure()) . PHP_EOL;
echo 'open_basedir disabled....... ' . (!$ini_open_basedir ? success() : failure()) . PHP_EOL;
echo 'safe_mode disabled.......... ' . (!$ini_safe_mode ? success() : failure()) . PHP_EOL;
echo 'Garbage Collector enabled... ' . ($ini_zend_enable_gc ? success() : failure()) . PHP_EOL;

// Test SSL cert
if (!is_windows())
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, 'https://email.us-east-1.amazonaws.com');
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_NOBODY, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
	curl_setopt($ch, CURLOPT_TIMEOUT, 5184000);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
	curl_setopt($ch, CURLOPT_NOSIGNAL, true);
	curl_setopt($ch, CURLOPT_USERAGENT, 'aws-sdk-php/compat-cli');
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
	curl_setopt($ch, CURLOPT_VERBOSE, false);
	curl_exec($ch);
	$ssl_result = !(curl_getinfo($ch, CURLINFO_SSL_VERIFYRESULT) === 0);
	curl_close($ch);

	echo 'Valid SSL certificate....... ' . ($ssl_result ? failure() : success()) . PHP_EOL;
}
else
{
	$ssl_result = false;
	echo 'Valid SSL certificate....... ' . failure() . ' (will use the bundled certificate instead)' . PHP_EOL;
}

echo PHP_EOL;

echo '----------------------------------------' . PHP_EOL;
echo PHP_EOL;

if ($php_ok && $curl_ok && $simplexml_ok && $spl_ok && $json_ok && $pcre_ok && $file_ok)
{
	echo success('Your environment meets the minimum requirements for using the AWS SDK for PHP!') . PHP_EOL . PHP_EOL;
	if (version_compare(PHP_VERSION, '5.3.0') < 0) { echo '* You\'re still running PHP ' . PHP_VERSION . '. The PHP 5.2 family is no longer supported' . PHP_EOL . '  by the PHP team, and future versions of the AWS SDK for PHP will *require*' . PHP_EOL . '  PHP 5.3 or newer.' . PHP_EOL . PHP_EOL; }
	if ($openssl_ok) { echo '* The OpenSSL extension is installed. This will allow you to use CloudFront' . PHP_EOL . '  Private URLs and decrypt Windows instance passwords.' . PHP_EOL . PHP_EOL; }
	if ($zlib_ok) {    echo '* The Zlib extension is installed. The SDK will automatically leverage the' . PHP_EOL . '  compression capabilities of Zlib.' . PHP_EOL . PHP_EOL; }
	if (!$int64_ok) {  echo '* You\'re running on a 32-bit system. This means that PHP does not correctly' . PHP_EOL . '  handle files larger than 2GB (this is a well-known PHP issue).' . PHP_EOL . PHP_EOL; }
	if (!$int64_ok && is_windows()) {  echo '* Note that PHP on Microsoft(R) Windows(R) does not support 64-bit integers' . PHP_EOL . '  at all, even if both the hardware and PHP are 64-bit. http://j.mp/php64win' . PHP_EOL . PHP_EOL; }

	if ($ini_open_basedir || $ini_safe_mode) { echo '* You have open_basedir or safe_mode enabled in your php.ini file. Sometimes' . PHP_EOL . '  PHP behaves strangely when these settings are enabled. Disable them if you can.' . PHP_EOL . PHP_EOL; }
	if (!$ini_zend_enable_gc) { echo '* The PHP garbage collector (available in PHP 5.3+) is not enabled in your' . PHP_EOL . '  php.ini file. Enabling zend.enable_gc will provide better memory management' . PHP_EOL . '  in the PHP core.' . PHP_EOL . PHP_EOL; }

	$storage_types = array();
	if ($file_ok) { $storage_types[] = 'The file system'; }
	if ($apc_ok) { $storage_types[] = 'APC'; }
	if ($xcache_ok) { $storage_types[] = 'XCache'; }
	if ($sqlite_ok && $sqlite3_ok) { $storage_types[] = 'SQLite 3'; }
	elseif ($sqlite_ok && $sqlite2_ok) { $storage_types[] = 'SQLite 2'; }
	if ($memcached_ok) { $storage_types[] = 'Memcached'; }
	elseif ($memcache_ok) { $storage_types[] = 'Memcache'; }
	echo '* Storage types available for response caching:' . PHP_EOL . '  ' . implode(', ', $storage_types) . PHP_EOL . PHP_EOL;

	if (!$openssl_ok) { echo '* You\'re missing the OpenSSL extension, which means that you won\'t be able' . PHP_EOL . '  to take advantage of CloudFront Private URLs or Windows password decryption.' . PHP_EOL . PHP_EOL; }
	if (!$zlib_ok) {    echo '* You\'re missing the Zlib extension, which means that responses from Amazon\'s' . PHP_EOL . '  services will take a little longer to download and you won\'t be able to take' . PHP_EOL . '  advantage of compression with the response caching feature.' . PHP_EOL; }
}
else
{
	if (!$php_ok) {       echo '* ' . failure('PHP:') . ' You are running an unsupported version of PHP.' . PHP_EOL; }
	if (!$curl_ok) {      echo '* ' . failure('cURL:') . ' The cURL extension is not available. Without cURL, the SDK cannot' . PHP_EOL . '  connect to -- or authenticate with -- Amazon\'s services.' . PHP_EOL; }
	if (!$simplexml_ok) { echo '* ' . failure('SimpleXML:') . ': The SimpleXML extension is not available. Without SimpleXML,' . PHP_EOL . '  the SDK cannot parse the XML responses from Amazon\'s services.' . PHP_EOL; }
	if (!$spl_ok) {       echo '* ' . failure('SPL:') . ' Standard PHP Library support is not available. Without SPL support,' . PHP_EOL . '  the SDK cannot autoload the required PHP classes.' . PHP_EOL; }
	if (!$json_ok) {      echo '* ' . failure('JSON:') . ' JSON support is not available. AWS leverages JSON heavily in many' . PHP_EOL . '  of its services.' . PHP_EOL; }
	if (!$pcre_ok) {      echo '* ' . failure('PCRE:') . ' Your PHP installation doesn\'t support Perl-Compatible Regular' . PHP_EOL . '  Expressions (PCRE). Without PCRE, the SDK cannot do any filtering via' . PHP_EOL . '  regular expressions.' . PHP_EOL; }
	if (!$file_ok) {      echo '* ' . failure('File System Read/Write:') . ' The file_get_contents() and/or file_put_contents()' . PHP_EOL . '  functions have been disabled. Without them, the SDK cannot read from,' . PHP_EOL . '  or write to, the file system.' . PHP_EOL; }
}

echo '----------------------------------------' . PHP_EOL;
echo PHP_EOL;

if ($php_ok && $int64_ok && $curl_ok && $simplexml_ok && $spl_ok && $json_ok && $pcre_ok && $file_ok && $openssl_ok && $zlib_ok && ($apc_ok || $xcache_ok || $mc_ok || $sqlite_ok))
{
	echo success('Bottom Line: Yes, you can!') . PHP_EOL;
	echo PHP_EOL;
	echo 'Your PHP environment is ready to go, and can take advantage of all possible features!' . PHP_EOL;

	echo PHP_EOL;
	echo info('Recommended settings for config.inc.php') . PHP_EOL;
	echo PHP_EOL;

	echo "CFCredentials::set(array(" . PHP_EOL;
	echo "    '@default' => array(" . PHP_EOL;
	echo "        'key' => 'aws-key'," . PHP_EOL;
	echo "        'secret' => 'aws-secret'," . PHP_EOL;
	echo "        'default_cache_config' => ";
	if ($apc_ok) echo success('\'apc\'');
	elseif ($xcache_ok) echo success('\'xcache\'');
	elseif ($file_ok) echo success('\'/path/to/cache/folder\'');
	echo "," . PHP_EOL;
	echo "        'certificate_authority' => " . success($ssl_result ? 'true' : 'false') . PHP_EOL;
	echo "    )" . PHP_EOL;
	echo "));" . PHP_EOL;
}
elseif ($php_ok && $curl_ok && $simplexml_ok && $spl_ok && $json_ok && $pcre_ok && ($apc_ok || $xcache_ok || $sqlite_ok))
{
	echo success('Bottom Line: Yes, you can!') . PHP_EOL;
	echo PHP_EOL;
	echo 'Your PHP environment is ready to go! There are a couple of minor features that' . PHP_EOL . 'you won\'t be able to take advantage of, but nothing that\'s a show-stopper.' . PHP_EOL;

	echo PHP_EOL;
	echo info('Recommended settings for config.inc.php') . PHP_EOL;
	echo PHP_EOL;

	echo "CFCredentials::set(array(" . PHP_EOL;
	echo "    '@default' => array(" . PHP_EOL;
	echo "        'key' => 'aws-key'," . PHP_EOL;
	echo "        'secret' => 'aws-secret'," . PHP_EOL;
	echo "        'default_cache_config' => ";
	if ($apc_ok) echo success('\'apc\'');
	elseif ($xcache_ok) echo success('\'xcache\'');
	elseif ($file_ok) echo success('\'/path/to/cache/folder\'');
	echo "," . PHP_EOL;
	echo "        'certificate_authority' => " . ($ssl_result ? 'false' : 'true') . PHP_EOL;
	echo "    )" . PHP_EOL;
	echo "));" . PHP_EOL;
}
else
{
	echo failure('Bottom Line: We\'re sorry...') . PHP_EOL;
	echo 'Your PHP environment does not support the minimum requirements for the ' . PHP_EOL . 'AWS SDK for PHP.' . PHP_EOL;
}

echo PHP_EOL;


text:
define(['jquery'], function () {
    //var baseUrl = 'http://192.168.6.103:7778';
    var baseUrl = 'http://127.0.0.1:7778';
    //var baseUrl = 'http://ices.xyz';
    var _base = {
        makeData: function (url, type, data) {
            var result;
            $.ajax({
                type: type,
                url: baseUrl + url,
                data: data,
                dataType: 'json',
                timeout: 300,
                async: false,
                success: function (data) {
                    result = data;
                },
                error: function (xhr, type) {
                    result = false;
                }
            });
            return result;
        },
        project: function () {
            return this.makeData('/project', 'GET');
        },
        projectDetail: function (url) {
            return this.makeData('/project/detail' + url, 'GET');
        },
        projectItem: function () {
            return this.makeData('/project/category', 'GET');
        },
        projectApplication: function (url) {
            return this.makeData('/project/application' + url, 'POST');
        },
        projectStatus: function (url) {
            return this.makeData('/project/status' + url, 'GET');
        },
        discuss: function (url) {
            return this.makeData('/project/discuss' + url, 'POST');
        },
        crowdfunding: function (url) {
            return this.makeData('/project/crowdfunding' + url, 'POST')
        },
        login: function (url) {
            return this.makeData('/login' + url, 'GET');
        },
        new: function () {
            return this.makeData('/news', 'GET');
        },
        newDetail: function (url) {
            return this.makeData('/news/detail' + url, 'GET');
        },
        newRead: function (url) {
            return this.makeData('/news/read' + url, 'POST');
        },
        competition: function () {
            return this.makeData('/competition', 'GET');
        },
        competitonDetail: function (url) {
            return this.makeData('/competition/detail' + url, 'GET');
        },
        competitionApplication: function (url) {
            return this.makeData('/competition/application' + url, 'POST');
        },
        user: function (url) {
            return this.makeData('/user' + url, 'GET', 'json');
        },
        projectAddStudent: function (url) {
            return this.makeData('/project/add-item-student' + url, 'POST');
        },
        projectAddSchool: function (data) {
            return this.makeData('/project/add-item-school', 'POST', data);
        },
        getMessage: function (data) {
            return this.makeData('/message', 'GET', data);
        },
        getPushMessage: function (data) {
            return this.makeData('/message/push', 'GET', data);
        },
        messageCheck: function (data) {
            return this.makeData('/message/check','post', data);
        }
    };
    return _base;
});


text:
namespace System.Net
{

using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Runtime.InteropServices;

#if !ECMA_COMPAT
[ComVisible(true)]
#endif
public class WebHeaderCollection : NameValueCollection
{
	private static int[] restrictedHeaders=
	{
		"accept".GetHashCode(),
		"connection".GetHashCode(),
		"content-length".GetHashCode(),
		"content-type".GetHashCode(),
		"date".GetHashCode(),
		"expect".GetHashCode(),
		"host".GetHashCode(),
		"range".GetHashCode(),
		"referrer".GetHashCode(),
		"transfer-encoding".GetHashCode(),
		"user-agent".GetHashCode()
	};
	private static char[] tspecials= new char []
						{'(', ')', '<', '>', '@',
					     ',', ';', ':', '\\', '"',
					     '/', '[', ']', '?', '=',
					     '{', '}', ' ', '\t'};

	private bool strict=true;
	public WebHeaderCollection()
	{
		/* nothing here ? */
	}
	internal void SetStrict(bool strict)
	{
		this.strict=strict;
	}

	public void Add(string header)
	{
		if(header==null || header==String.Empty)
		{
			throw new ArgumentNullException("header");
		}
		int col=header.IndexOf(":");
		if(col==-1)
		{
			throw new ArgumentException("missing ':' in header"); /*TODO:I18n*/
		}
		Add(header.Substring(0,col),header.Substring(col+1));
	}

	public override void Add(string name, string value)
	{
		if(name==null)
		{
			throw new ArgumentNullException("name");
		}
		if(strict && IsRestricted(name))
		{
			throw new ArgumentException(S._("Arg_RestrictedHeader"));
		}
		AddWithoutValidate(name,value);
	}

	protected void AddWithoutValidate(string headerName, string headerValue)
	{
		headerName=headerName.Trim();
		if(!IsValidHeaderName(headerName))
		{
			throw new ArgumentException(S._("Arg_InvalidHeader"));
		}
		if(headerValue==null)headerValue="";
		else headerValue=headerValue.Trim(); /* remove excess LWS */
		base.Add(headerName,headerValue); /* add to NameValueCollection */
	}

	public override String[] GetValues(string header)
	{
		if(header==null)
		{
			throw new ArgumentNullException("header");
		}
		return base.GetValues(header);
	}

	public static bool IsRestricted(string headerName)
	{
		int hash=headerName.ToLower().GetHashCode(); /* case insensitive ? */
		for(int i=0;i<restrictedHeaders.Length;i++)
		{
			if(restrictedHeaders[i]==hash)return true;
		}
		return false;
	}

	public override void Remove(string name)
	{
		if(name==null)
		{
			throw new ArgumentNullException("name");
		}
		if(!IsValidHeaderName(name))
		{
			throw new ArgumentException(S._("Arg_InvalidHeader"));
		}
		if(strict && IsRestricted(name))
		{
			throw new ArgumentException(S._("Arg_RestrictedHeader"));
		}
		RemoveInternal(name);
	}

	internal void RemoveInternal(String name)
	{
		base.Remove(name);
	}

	public override void Set(string name, string value)
	{
		if(name==null)
		{
			throw new ArgumentNullException("name");
		}
		if(!IsValidHeaderName(name))
		{
			throw new ArgumentException(S._("Arg_InvalidHeader"));
		}
		if(strict && IsRestricted(name))
		{
			throw new ArgumentException(S._("Arg_RestrictedHeader"));
		}
		SetInternal(name,value);
	}

	internal void SetInternal(String name,String value)
	{
		if(value==null)value="";
		else value=value.Trim(); // LWS
		base.Set(name,value);
	}

	public override String ToString()
	{
		StringBuilder builder=new StringBuilder(40*this.Count);
		/* an assumption :-) */
		foreach(String key in this)
		{
			builder.Append(key+": "+this[key]+"\r\n");
		}
		return builder.ToString();
	}

	// private methods
	private static bool IsValidHeaderName(String name)
	{

        /*  token          = 1*<any CHAR except CTLs or tspecials>

          tspecials      = "(" | ")" | "<" | ">" | "@"
                         | "," | ";" | ":" | "\" | <">
                         | "/" | "[" | "]" | "?" | "="
                         | "{" | "}" | SP | HT
		*/
		if(name == null || name.Length == 0) return false;
		char[] chars=name.ToCharArray();
		int len=chars.Length;
		for(int i=0;i< len; i++)
		{
			if(chars[i]< 0x20 || chars[i]>=0x7f) /* no Unicode here */
			{
				return false;
			}
		}
		return name.IndexOfAny(tspecials) == -1;
	}

}; //class WebHeaderCollection

}; //namespace System.Net


text:
package me.lyml.summer.common.security.realm;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import me.lyml.summer.account.entity.Permission;
import me.lyml.summer.account.entity.Role;
import me.lyml.summer.account.entity.User;
import me.lyml.summer.account.service.RoleService;
import me.lyml.summer.account.service.UserService;
import me.lyml.summer.base.entity.ShiroUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: AuthorizationRealm
 * @author: cnlyml
 * @date: 2016/9/1 9:46
 */
public class AuthorizationRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
        List<Role> roleList = userService.findRolesByUserID(shiroUser.getId());
        Set<String> permissions = Sets.newHashSet();
        Set<String> roles = Sets.newHashSet();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for(Role role : roleList) {
            List<Permission> permissionList = roleService.findPermissionsByRoleID(role.getId());
            permissions.addAll(permissionList.stream().map(Permission::getPermissionCode).collect(Collectors.toList()));
            roles.add(role.getId() + "");
        }

        info.addStringPermissions(permissions);
        info.addRoles(roles);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();

        User user = userService.findUserByUserName(userName);
        if(user == null) {
            throw new UnknownAccountException("用户名或密码不正确");
        }

        return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getUserName(), user.getRealName(),
                user.getEmail(), user.getMobileNo(), user.getAvatar()), user.getUserPass(), ByteSource.Util.bytes(user.generateCredentialsSalt()),getName());
    }

}


text:
from django.conf.urls.defaults import *
from . import views

urlpatterns = [
    url(r'^js/textareas/(?P<name>.+)/$', views.textareas_js, name='tinymce-js')
]


text:
/**
 *
 */
package com.juxtapose.example.ch11.multithread;

import java.util.List;

import org.springframework.batch.item.ItemWriter;

/**
 *
 * @author bruce.liu(mailto:jxta.liu@gmail.com)
 * 2013-11-16下午10:58:20
 */
public class ConsoleWriter implements ItemWriter<String> {

	public void write(List<? extends String> items) throws Exception {
		System.out.print("Write begin:");
		for(String item : items){
			System.out.print(item + ",");
		}
		System.out.print("Write end!!");
		System.out.println("Job Write Thread name: " + Thread.currentThread().getName());
	}

}


text:
var ctor = require('../../');
var rtc = ctor();
var Peer = require('simple-peer');
var crel = require('crel');
var browser = require('detect-browser');
var onStreamLoaded = require('../../util/onStreamLoaded');

window.ctor = ctor;
window.rtc = rtc;
bootstrap();

function bootstrap(){
  console.log('Platform:', rtc.platform);
  console.debug('Inspect:', rtc);

  if (rtc.platform === 'unsupported') {
    console.error('Platform not supported!');
    return;
  }

  rtc.getUserMedia(function(err, stream){
    if (err) {
      return console.error(err);
    }
    console.debug('User camera:', stream);
    createLoopback(stream);
  });
}

function createLoopback(stream){

  // make this funky wrapper due to edge issues
  function getStream(){
    if (rtc.platform === 'edge') {
      return stream.clone();
    }
    return stream;
  }

  onStreamLoaded(getStream(), function(err, res){
    if (err) console.error('StreamLoaded error:', err);
    if (res) console.log('StreamLoaded:', res);
  });

  var initiator = new Peer({
    initiator: true,
    trickle: (rtc.platform !== 'edge'),
    stream: getStream(),
    wrtc: rtc
  });

  var receiver = new Peer({
    stream: getStream(),
    trickle: (rtc.platform !== 'edge'),
    wrtc: rtc
  });

  //debug(initiator, 'initiator');
  //debug(receiver, 'receiver');

  initiator.on('error', console.error.bind(console));
  receiver.on('error', console.error.bind(console));

  initiator.on('signal', receiver.signal.bind(receiver));
  receiver.on('signal', initiator.signal.bind(initiator));

  initiator.once('connect', function(){
    console.debug('Connected!');
  });

  initiator.once('stream', function(stream){
    console.debug('Stream relayed receiver -> initiator');
    crel(document.body, makeVideo(stream));
  });

  receiver.once('stream', function(stream){
    console.debug('Stream relayed  initiator -> receiver');
    crel(document.body, makeVideo(stream));
  });
}

function debug(peer, id){
  peer.on('signal', function(m){
    console.debug(id, 'signal:', JSON.stringify(m));
  });
}

function makeVideo(stream) {
  var el = crel('video', {
    muted: true,
    autoplay: true,
    className: 'video-stream',
    style: 'max-height:100px; max-width:100px; border: 2px solid gray; display:inline-block; background-color:black;'
  });
  return rtc.attachStream(stream, el);
}


text:
<?php
namespace Madfox\WebCrawler\Exception;

class LogicException extends \LogicException implements ExceptionInterface
{

}


text:
import sys
import re
import os

special = ("Media:", "Special:", "Talk:", "User:", "User_talk:", "Project:", "Project_talk:", "File:", "File_talk:", "MediaWiki:", "MediaWiki_talk:", "Template:", "Template_talk:", "Help:", "Help_talk:", "Category:", "Category_talk:", "Portal:", "Wikipedia:", "Wikipedia_talk:")
extens = (".jpg," ".gif," ".png," ".JPG," ".GIF," ".PNG," ".txt," ".ico")

def readInput(file):
    for line in file:
        yield line.split()

def checkSpecial(word):
    splitted = word.split(":")
    return len(splitted)>1 and splitted[0]+":" not in special

reg = "-([0-9]+)-"

def main(separator='\t'):
    data = readInput(sys.stdin)
    filename = os.environ["mapreduce_map_input_file"]
    date = re.search(reg, filename).group(0)[1:-1]
    for words in data:
        if words[0] == "en" and checkSpecial(words[1]) and words[1][0].istitle() and words[1][len(words[1])-4:] not in extens:
            print '%s%s%s%s%s' % (words[1], separator, words[2], separator, date)

if __name__ == "__main__":
    main()


text:
package kaptcha;

import java.awt.image.BufferedImage;

/**
 * {@link kaptcha.NoiseProducer} is responsible for adding noise to an image.
 */
public interface NoiseProducer {
    /**
     * Adds noise to an image. It uses four factor values to determine the noise
     * curve.
     *
     * @param image the image to add the noise to
     * @param factorOne
     * @param factorTwo
     * @param factorThree
     * @param factorFour
     */
    public void makeNoise(BufferedImage image, float factorOne, float factorTwo, float factorThree,
            float factorFour);
}


text:
.u-text-transform--inherit {
	text-transform: inherit;
}

.u-text-transform--none {
	text-transform: none;
}

.u-text-transform--capitalize {
	text-transform: capitalize;
}

.u-text-transform--uppercase {
	text-transform: uppercase;
}

.u-text-transform--lowercase {
	text-transform: lowercase;
}


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.

/*============================================================
**
**
** Purpose: Provides some basic access to some environment
** functionality.
**
**
============================================================*/

using System.Text;
using System.Collections;

namespace System
{
    public static partial class Environment
    {
        public unsafe static String ExpandEnvironmentVariables(String name)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            // Environment variable accessors are not approved modern API.
            // Behave as if no variables are defined in this case.
            return name;
        }

        public unsafe static String GetEnvironmentVariable(String variable)
        {
            if (variable == null)
                throw new ArgumentNullException("variable");

            // Environment variable accessors are not approved modern API.
            // Behave as if the variable was not found in this case.
            return null;
        }

        public static string MachineName
        {
            get
            {
                // Store apps don't support MachineName
                throw new PlatformNotSupportedException();
            }
        }
    }
}


text:
<!--                                                                        -->
<!-- Copyright 2008 Google Inc.                                             -->
<!-- Licensed under the Apache License, Version 2.0 (the "License"); you    -->
<!-- may not use this file except in compliance with the License. You may   -->
<!-- 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. License for the specific language governing permissions and   -->
<!-- limitations under the License.                                         -->

<!-- Module used to include Animation class.                                -->
<!--                                                                        -->
<!-- This module is typically inherited via com.google.gwt.user.User        -->
<!--                                                                        -->
<module>
  <inherits name="jsinterop.base.Base"/>
  <inherits name="elemental2.dom.Dom"/>
  <inherits name="org.gwtproject.dom.DOM"/>
  <inherits name="org.gwtproject.event.Event"/>
  <inherits name="org.gwtproject.event.legacy.EventLegacy"/>

  <source path="client" />
</module>


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**query** | [**\Dcm\Model\BidModifierQuery**](BidModifierQuery.md) |  | [optional]
**update** | [**\Dcm\Model\UpdatableBidModifier**](UpdatableBidModifier.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
<?php

class Controller_Member extends Controller_Site
{
	protected $check_not_auth_action = array(
		'home',
		'list',
	);

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

	/**
	 * Mmeber index
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_index()
	{
	}

	/**
	 * Mmeber mypage
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_mypage()
	{
		$this->action_home($this->u->id);
	}

	/**
	 * Mmeber home
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_home($id = null)
	{
		if (Auth::check() && (!$id || $id == 'me')) $id = $this->u->id;
		$id = (int)$id;
		list($is_mypage, $member, $access_from) = $this->check_auth_and_is_mypage($id);

		// Update read flag
		if (\Auth::check() && $id != $this->u->id && \Notice\Site_Util::check_enabled_notice_type('follow'))
		{
			$this->change_notice_status2read($this->u->id, 'member', $id);
		}

		$member_profiles = Model_MemberProfile::get4member_id($member->id, true);
		$data = array(
			'member' => $member,
			'member_profiles' => $member_profiles,
			'is_mypage' => $is_mypage,
			'access_from' => $access_from,
			'display_type' => 'summary',
		);
    // Report link
		$data['report_data'] = $this->set_global_for_report_form() ? array(
			'member_id' => $member->id,
			'uri' => 'member/'.$member->id,
			'type' => 'member',
			'content' => '',
		) : array();

		if (is_enabled('timeline'))
		{
			$data['timeline'] = \Timeline\Site_Util::get_list4view(
				\Auth::check() ? $this->u->id : 0,
				$member->id, false, null,
				$this->common_get_list_params(array(
					'desc' => 1,
					'latest' => 1,
					'limit' => conf('articles.limit', 'timeline'),
				), conf('articles.limit_max', 'timeline'), true)
			);
			$data['timeline']['member'] = $member;
			$this->template->post_footer = \View::forge('timeline::_parts/load_timelines');
		}
		$this->set_title_and_breadcrumbs(
			$is_mypage ? t('page.mypage') : t('member.page_of', array('label' => $member->name)),
			$is_mypage ? array() : array('member/list' => term('member.list')),
			$is_mypage ? $member : null, null, array(), false, false, array(
				'title' => t('member.page_of', array('label' => $member->name)),
				'image' => Site_Util::get_image_uri4file_name($member->get_image(), 'P_L', 'profile'),
			)
		);
		$this->template->content = \View::forge('member/home', $data);
	}

	/**
	 * Mmeber list
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_list()
	{
		$this->set_title_and_breadcrumbs(t('member.list'));
		$this->template->subtitle = \View::forge('member/_parts/list_subtitle');

		$default_params = array(
			'latest' => 1,
			'desc' => 1,
			'limit' => conf('member.view_params.list.limit'),
		);
		list($limit, $is_latest, $is_desc, $since_id, $max_id)
			= $this->common_get_list_params($default_params, conf('member.view_params.list.limit_max'));
		list($wheres, $search_word_str) = Site_Model::get_search_word_conds(\Input::get('q'), 'name', false, false, true);
		list($list, $next_id) = Model_Member::get_list($wheres, $limit, $is_latest, $is_desc, $since_id, $max_id);

		$this->template->main_container_attrs = array('data-not_render_site_summary' => 1);
		$this->template->content = \View::forge('member/list', array(
			'list' => $list,
			'next_id' => $next_id,
			'since_id' => $since_id,
			'max_id' => $max_id,
			'search_word' => $search_word_str,
		));
		$this->template->post_footer = \View::forge('_parts/load_item');
	}

	/**
	 * Mmeber Search
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_search()
	{
		if (!conf('profile.useCacheTable.isEnabled', 'member')) throw new HttpNotFoundException;

		$this->set_title_and_breadcrumbs(term('member.view', 'form.search'), array(
			'member/list' => term('member.list'),
		));

		list($limit, $page) = $this->common_get_pager_list_params(
			conf('member.view_params.list.limit'),
			conf('member.view_params.list.limit_max')
		);
		$data = array(
			'limit' => $limit,
			'no_data_message' =>  __('message_error_detail_search', array('label' => t('member.plural'))),
			'loaded_position' => 'replace',
			//'is_desplay_load_before_link' => $page > 1,
		);
		$data = array_merge($data, Site_Member::get_detail_search_pager_list(get_uid(), $limit, $page));

		$this->template->main_container_attrs = array('data-not_render_site_summary' => 1);
		$this->template->content = \View::forge('member/search', $data);
		$this->template->post_footer = \View::forge('_parts/load_item');
	}
}


text:
# CSS Overview
##  Cascading Style Sheets

HTML, CSS & JavaScript

Telerik School Academy

    http://academy.telerik.com

# Table of Contents
- What is CSS?
- Styling with Cascading Style Sheets (CSS)
- CSS Selectors
  - Select by element name, id or class
  - Nested Selectors
- Importing CSS into HTML
- Selectors
  - Attribute selectors
  - Pseudo Selectors

# CSS: A New Philosophy
- Separate content from presentation!
    - Content (`HTML` document on the left)
    - Presentation (`CSS` document on the right)

# The Resulting Page

# CSS Introduction
- Cascading Style Sheets (CSS)
  - Used to `describe` the presentation of documents
  - Define `sizes`, `spacing`, `fonts`, `colors`, `layout`, etc.
  - Improve content `accessibility`
  - Improve `flexibility`
- Designed to separate presentation from content
- Due to CSS, all `HTML presentation` tags and `attributes` are `deprecated`, e.g. `font`, `center`, etc.

# CSS Introduction (2)
- CSS can be applied to any XML document
  - Not just to HTML / XHTML
- CSS can specify different styles for different `media`
  - On-screen
  - In print
  - Handheld, projection, etc.
  - … even by voice or Braille-based reader

# Why "Cascading"?
- Priority scheme determining which style rules apply to element
  - `Cascade priorities` or `specificity (weight)` are calculated and assigned to the rules
  - Child elements in the HTML DOM tree inherit styles from their parent
    - Can override them
    - Control via `!important` rule

# Why "Cascading"? (2)

# Style Inheritance
- Some CSS styles are inherited and some are not
  - `Text-related` and `list-related` properties are `inherited`: `color`, `font-size`, `font-family`, `line-height`, `text-align`, `list-style`, etc.
  - `Box-related` and `positioning` styles are `not inherited`: `width`, `height`, `border`, `margin`, `padding`, `position`, `float`, etc
  - `<a>` elements do not inherit color and text-decoration

# Style Sheets Syntax
- Stylesheets consist of `rules`, `selectors`, `declarations`, `properties` and `values`

- `Selectors` are separated by commas
- `Declarations` are separated by semicolons
- `Properties` and `values` are separated by colons

```css
h1,h2,h3 { color: green; font-weight: bold; }
```
- http://css.maxdesign.com.au

# Selectors
- Selectors determine which element the rules apply to:
  - All elements of specific type (`tag`)
  - Those that match a specific attribute (`id`, `class`)
  - Elements may be matched depending on how they are nested in the document tree (HTML)
- Examples:

```css
.header a { color: green }
```

```css
#menu>li { padding-top: 8px }
```

# Primary Selectors
- Three primary kinds of selectors:
  - By tag (type selector):

  ```css
  h1 { font-family: verdana,sans-serif; }
  ```

  - By element id:

  ```css
  #element_id { color: #ff0000; }
  ```

  - By element class name (only for HTML):

  ```css
  .myClass {border: 1px solid red}
  ```

- Selectors can be combined with commas:
```css
h1, .link, #top-link {font-weight: bold}
```

-     This will match `<h1>` `tags`, elements with `class` `link`, and the element with `id` `top-link`

# Nested Selectors
- Match relative to element placement:

```css
p a {text-decoration: underline}
```

- This will match all `<a>` tags that are inside of `<p>`

- `x` – universal selector (avoid or use with care!):

```css
p x {color: black}
```

- This will match all descendants of `<p>` element
- `+` selector – used to match "next sibling":

```css
img + .link {float:right}
```

-     This will match all siblings with class name `link` that appear immediately after `<img>` tag

# Nested Selectors (2)
- `>` selector – matches direct child nodes:

```css
p > .error {font-size: 8px}
```

-   This will match all elements with class `error`, direct children of `<p>` tag
- `.class1.class2 `(no space!)
  - Matches elements with both (all) classes applied at the same time

```css
p.post-text.special {font-weight: bold}
```

##  [Demo]()

# Importing CSS Into HTML
- `CSS` (presentation) can be imported in `HTML` (content) in three ways:
  - `Inline`: the CSS rules in the `style` attribute
    - No selectors are needed
  - `Embedded`: in the `<head>` in a `<style>` tag
  - `External`: CSS rules in separate file (best)
    - Usually a file with `.css` extension
    - Linked via `<link rel="stylesheet" href="…">` tag
    - Via` @import` directive in embedded CSS block

# Linking HTML and CSS (2)
- Using `external CSS files `is highly recommended
  - Simplifies the HTML document
  - Improves page load speed (CSS file is cached)
- HTML links to external CSS file

# Inline Styles: Example

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Inline Styles</title>
</head>
<body>
  <p>Here is some text</p>
<!--Separate multiple styles with a semicolon-->
  <p style="font-size: 20pt">Here is some
    more text</p>
  <p style="font-size: 20pt;color:
    #0000FF" >Even more text</p>
</body>
</html>
```

# Embedded Styles
- Embedded in the HTML in the `<style>` tag:

```html
<style type="text/css"/>
```

  - The `<style>` tag is placed in the `<head>` section of the document
  - `type` attribute specifies the MIME type
    - MIME describes the format of the content
    - Other MIME types include `text/html`, `image/gif`, `text/javascript` …
    - Not required in HTML5
- Used for document-specific styles

# Embedded Styles: Example

```html
<!DOCTYPE html>
<html>
<head>
  <title>Style Sheets</title>
  <style type="text/css">
    em {background-color:#8000FF; color:white}
    h1 {font-family:Arial, sans-serif}
    p  {font-size:18pt}
    .blue {color:blue}
  </style>
<head>
```

# Embedded Styles: Example (2)

```html
…
<body>
  <header>
      <h1 class="blue">A Heading</h1>  </header>  <article>
      <p>Here is some text. Here is some text.
      Here is some text. Here is some text. Here
      is some text.</p>
     <h1>Another Heading</h1>
     <p class="blue">Here is some more text.
     Here is some more text.</p>
     <p class="blue">Here is some <em>more</em>
     text. Here is some more text.</p>  </article>
</body>
</html>
```

# External CSS Styles
- External linking
  - Separate pages can all use a shared style sheet
  - Only modify a single file to change the styles across your entire Web site (see [www.csszengarden.com](http://www.csszengarden.com))

- `link` tag (with a `rel` attribute)
  - Specifies a relationship between current document and another document

  ```html
  <link rel="stylesheet" type="text/css"
    href="styles.css">
  ```

  - `link` elements should be in the `<head>`

# External CSS Styles (2)
- `@import`
  - Another way to link external CSS files
  - Example:

  ```html
  <style type="text/css">
    @import url("styles.css");  /x same as x/
    @import "styles.css";
  </style>
  ```

  - Ancient browsers do not recognize `@import`
  - Use `@import` in an external CSS file to workaround the IE CSS file limit of 31 files

# External Styles: Example

```css
/x CSS Document x/
a       { text-decoration: none }
a:hover { text-decoration: underline;
          color: red;
          background-color: #CCFFCC }
li em   { color: red;
          font-weight: bold }
ul      { margin-left: 2cm }
ul ul      { text-decoration: underline;
          margin-left: .5cm }
```

# External Styles: Example (2)

```html
<!DOCTYPE html>
<html>
<head>
  <title>Importing style sheets</title>
  <link type="text/css" rel="stylesheet"
    href="styles.css"  />
</head>
<body>
  <h1>Shopping list for <em>Monday</em>:</h1>
  <li>Milk</li>
  …
```

# External Styles: Example (3)

```html
  …
  <li>Bread
    <ul>
      <li>White bread</li>
      <li>Rye bread</li>
      <li>Whole wheat bread</li>
    </ul>
  </li>
  <li>Rice</li>
  <li>Potatoes</li>
  <li>Pizza <em>with mushrooms</em></li>
</ul>
<a href="http://food.com" title="grocery
  store">Go to the Grocery store</a>
</body>
</html>
```

# Attribute Selectors
## Picking Elements with Certain Attributes

# Attribute Selectors
- `[ ]`selects elements based on attributes
  - Element with a given attributeSelects `<a>` elements with `title`

  ```css
  a[title] {color:black}
  ```

  - Elements with a concrete attribute value
  - Selects `<input>` elements with `type=text`

  ```css
  input[type=text] { font-family:Consolas}
  ```

  - Elements whose attribute values contain a word
  - Selects `<a>` elements whose title attribute value contains `logo`

  ```css
  a[titlex=logo] {border: none}
  ```

# Attribute Selectors
## [Demo]()

# Pseudo Selectors
## Relative to Element Content or State

# Common Pseudo Selectors
- Pseudo-classes define state
  - `:hover`, `:visited`, `:active` , `:lang`

- Pseudo-elements define element "parts" or are used to generate content
  - `:first-line` , `:before`, `:after`

```css
a:hover { color: red; }
p:first-line { text-transform: uppercase; }
.title:before { content: "»"; }
.title:after { content: "«"; }
```

## [Demo]()

# Structural Pseudo-classes
- `:root`
  - The root of the document

- `E:nth-child(n)`
  - An `E` element, the n-th child of its parent

- `E:nth-last-child(n)`
  - An `E` element, the n-th child of its parent, counting from the last on

- `E:nth-of-type(n)`
  - An `E` element, the n-th sibling of its type

# Structural Pseudo-classes (2)
- `E:nth-last-of-type(n)`
  - An `E` element, the n-th sibling of its type, counting from the last one

- `E:last-child`
  - An `E` element, last child of its parent

- `E:first-of-type`
  - An `E` element, first sibling of its type

- `E:last-of-type`
  - An `E` element, last sibling of its type

# Structural Pseudo-classes (3)
- `E:only-child`
  - An `E` element, only child of its parent

- `E:only-of-type`
  - An `E` element, only sibling of its type

- `E:empty`
  - An `E` element that has no children (including text nodes)

- More detailed descriptions:

[http://www.w3.org/TR/css3-selectors/#structural-pseudos](http://www.w3.org/TR/css3-selectors/#structural-pseudos)

## [Demo]()

# The UI Element StatesPseudo-Classes
- `E:enabled`
  - A user interface element `E` which is enabled

- `E:disabled`
  - A user interface element `E` which is disabled

- `E:checked`
  - A user interface element `E` which is checked (for instance a radio-button or checkbox)
  - Currently supported only in Opera and IE10 !

## [Demo]()

# Other CSS 3 Selectors
- `E:target`
  - An `E` element being the target of the referring URI

- `E:not(s)`
  - An `E` element that does not match simple selector

- `E ~ F`
  - An `F` element preceded by an `E` element

## [Demo]()

# CSS Values
## Types, Ranges, Units

# CSS Values
- All values in CSS are strings
  - They can represent values that are not strings
  - I.e. `14px` means size 14 pixels

- Colors are set in a red-green-blue format (RGB)
  - Both in hex and decimal

```css
li.nav-item {
  color: #44f1e1}
```

```css
li.nav-item {
  color: rgb(68, 241, 255)}
```

# Size Values
- When setting a size (width, height, font-size...) the values are given as numbers
  - Multiple formats / metrics may be used
  - Pixels, ems, e.g. `12px` , `1.4em`
  - Points, inches, centimeters, millimeters
    - E.g. `10pt` , `1in`, `1cm`, `1mm`

  - Percentages, e.g. `50%`
    - Of the size of the container/font size

  - Zero can be used with no unit: `border: 0;`

## [Demo]()

# Color Values
- Colors in CSS can be represented in few ways
  - Using red-green-blue
    - Or red-green-blue-alpha

The opacity values are from 0.0 to 1.0

```css
color: #f1a2ff
color: rgb(241, 162, 255)
color: rgba(241, 162, 255, 0.1)
```

  - Using hue-saturation-light
    - Or hue-saturation-light-alpha

```css
color: hsl(291, 85%, 89%);
color: hsl(291, 85%, 89%, 0.1);
```

# RGB Colors
- RGB colors are defined with values for red, green and blue intensity
- Syntax:` `
  - `#44fa36` – values are in hex
  - `rgb(<red>, <green>, <blue>)`– decimal values

- The range for `red`, `green` and `blue` is between integers `0` and `255`

```css
color: #07f2b3
  <!– or -->
color: rgb (7, 242, 179)
```

# RGBA Colors
- Standard RGB colors with an opacity value for the color (alpha channel)

- Syntax:`rgba(<red>, <green>,`

`<blue>, <alpha>)`
- The range for `red`, `green` and `blue` is between integers `0` and `255`
- The range for the alpha channel is between `0.0` and `1.0`
- Example: `rgba(255, 0, 0, 0.5)`

# HSL Colors
- Hue is a degree on the color wheel
  - `0` (or `360`) is red, `120` is green, `240` is blue

- Saturation is a percentage value
  - `100%` is the full color

- Lightness is also a percentage
  - `0%` is dark (black)
  - `100%` is light (white)
  - `50%` is the average

# HSLA Colors
- HSLA allows a fourth value, which sets the Opacity (via the Alpha channel) of the element
- As RGBA is to RGB, HSLA is to HSL
- Supported in IE9+, Firefox 3+, Chrome, Safari, and in Opera 10+
- Example:
  - `hsla(0, 100%, 50%, 0.5)`
  - Result:` `

## [Demo]()

# Default Browser Styles
- Browsers have predefined CSS styles
  - Used when there is no CSS information or any other style information in the document

- `Caution`: default styles differ in browsers
  - E.g. `margins`, `paddings`and `font sizes` differ most often
  - Usually developers reset them

```css
x { margin: 0; padding: 0; }
```

```css
body, h1, p, ul, li { margin: 0; padding: 0; }
```

# CSS Cascade (Precedence)
- There are browser, user and author stylesheets with "`normal`" and "`important`" declarations
  - Browser styles (least priority)
  - Normal user styles
  - Normal author styles (external, in head, inline)
  - Important author styles
  - Important user styles (max priority)

```css
a { color: red !important ; }
```

[http://www.slideshare.net/maxdesign/css-cascade-1658158](http://www.slideshare.net/maxdesign/css-cascade-1658158)

# CSS Specificity
- CSS specificity is used to determine the precedence (priority) of the CSS style declarations with the same origin
  - Simple calculation: `#id = 100`, `.class = 10`, `:pseudo = 10`, `[attr] = 10`, `tag = 1`, `x = 0`
  - Same number of points? Order matters!
  - See also:
    - [http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/](http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/)
    - [http://css.maxdesign.com.au/selectutorial/advanced_conflict.htm](http://css.maxdesign.com.au/selectutorial/advanced_conflict.htm)

## [Demo]()

# CSS References
- The CSS documentation at WebPlatform.org:
  - [http://docs.webplatform.org/wiki/css](http://docs.webplatform.org/wiki/css)

- CSS documentation at Mozilla
  - [https://developer.mozilla.org/en-US/docs/CSS](https://developer.mozilla.org/en-US/docs/CSS)

- CSS3 tutorial
  - [http://www.w3schools.com/css3/](http://www.w3schools.com/css3/)

- A list of all CSS 2.1 properties is available at [http://www.w3.org/TR/CSS2/propidx.html](http://www.w3.org/TR/CSS2/propidx.html)


text:
declare module 'inflection' {
  declare function camelize(source: string, lower: boolean): string;
  declare function classify(source: string): string;
  declare function dasherize(source: string): string;
  declare function pluralize(source: string): string;
  declare function singularize(source: string): string;
  declare function underscore(source: string, upper: boolean): string;
}


text:
<manifest package="com.hkm.ui.processbutton">
    <!--empty-->
</manifest>


text:
using System.ComponentModel;
using System.Linq;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Tools;
using TehPers.FishingOverhaul.Integrations.GenericModConfigMenu;

namespace TehPers.FishingOverhaul.Config
{
    /// <summary>
    /// Configuration for the chances of catching treasure while fishing.
    /// </summary>
    /// <inheritdoc cref="FishingChances"/>
    public class TreasureChances : FishingChances
    {
        /// <summary>
        /// The effect that the magnet bait has.
        /// </summary>
        [DefaultValue(0.15)]
        public double MagnetFactor { get; set; } = 0.15;

        /// <summary>
        /// The effect that the treasure hunter tackle has.
        /// </summary>
        [DefaultValue(0.05)]
        public double TreasureHunterFactor { get; set; } = 0.05;

        /// <summary>
        /// The effect that the pirate profession has. This is multiplied by your base chance
        /// before being added.
        /// </summary>
        [DefaultValue(1d)]
        public double PirateFactor { get; set; } = 1d;

        internal override void Reset()
        {
            base.Reset();

            this.MagnetFactor = 0.15d;
            this.TreasureHunterFactor = 0.05d;
            this.PirateFactor = 1d;
        }

        internal override void RegisterOptions(
            IGenericModConfigMenuApi configApi,
            IManifest manifest,
            ITranslationHelper translations
        )
        {
            Translation Name(string key) => translations.Get($"text.config.chances.treasure.{key}.name");
            Translation Desc(string key) => translations.Get($"text.config.chances.treasure.{key}.desc");

            base.RegisterOptions(configApi, manifest, translations);

            configApi.AddNumberOption(
                manifest,
                () => (float)this.MagnetFactor,
                val => this.MagnetFactor = val,
                () => Name("magnetFactor"),
                () => Desc("magnetFactor"),
                0f,
                1f
            );
            configApi.AddNumberOption(
                manifest,
                () => (float)this.TreasureHunterFactor,
                val => this.TreasureHunterFactor = val,
                () => Name("treasureHunterFactor"),
                () => Desc("treasureHunterFactor"),
                0f,
                1f
            );
        }

        /// <inheritdoc />
        public override double GetUnclampedChance(Farmer farmer, int streak)
        {
            var chance = base.GetUnclampedChance(farmer, streak);

            // Check attachments
            if (farmer.CurrentItem is FishingRod rod)
            {
                // Magnet bait
                if (rod.attachments.Any(attachment => attachment?.ParentSheetIndex == 703))
                {
                    chance += this.MagnetFactor;
                }

                // Treasure hunter tackle
                if (rod.attachments.Any(attachment => attachment?.ParentSheetIndex == 693))
                {
                    chance += this.TreasureHunterFactor;
                }
            }

            // Pirate profession
            if (farmer.professions.Contains(9))
            {
                chance += this.BaseChance * this.PirateFactor;
            }

            return chance;
        }
    }
}


text:
package org.hotpoor.pyq.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    String[]single_list={"男","女"};
    String[]multi_list={"篮球","足球","排球","乒乓球"};
    String[]item_list={"项目经理","策划","测试","程序员","美工"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initEvent();
    }
    /*
     *初始化点击事件
     */
    private void initEvent(){
        findViewById(R.id.dialog_btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            showDialog1();
            }
        });

        findViewById(R.id.dialog_btn2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog2();
            }
        });

        findViewById(R.id.dialog_btn3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog3();
            }
        });

        findViewById(R.id.dialog_btn4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog4();
            }
        });

        findViewById(R.id.dialog_btn5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog5();
            }
        });

    }
    /*
     *显示确认对话框
     */
    private void showDialog1(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("确认对话框");//设置标题
        builder.setIcon(R.mipmap.ic_launcher);//设置图标
        builder.setMessage("确认对话框提示内容");//设置内容
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this , "点击了确定按钮" , Toast.LENGTH_LONG).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this , "点击了取消按钮" , Toast.LENGTH_LONG).show();
            }
        });
        AlertDialog dialog=builder.create();//获取dialog
        dialog.show();//显示对话框
    }
    /*
     *显示单选按钮对话框
     */
    private void showDialog2(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("选择性别");//设置标题
        builder.setIcon(R.mipmap.ic_launcher);//设置图标
        builder.setSingleChoiceItems(single_list, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String str=single_list[which];
                Toast.makeText(MainActivity.this ,"这个人是"+str , Toast.LENGTH_LONG).show();
            }
        });
        AlertDialog dialog=builder.create();//获取dialog
        dialog.show();//显示对话框
    }
    /*
     *显示多选按钮对话框
     */
    private void showDialog3(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("爱好");//设置标题
        builder.setIcon(R.mipmap.ic_launcher);//设置图标
        builder.setMultiChoiceItems(multi_list, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                if (isChecked)
                    Toast.makeText(MainActivity.this, "我喜欢" + multi_list[which], Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(MainActivity.this ,"我不喜欢"+multi_list[which] , Toast.LENGTH_LONG).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog=builder.create();//获取dialog
        dialog.show();//显示对话框
    }
    /*
     *显示列表对话框
     */
    private void showDialog4(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("部门列表");//设置标题
        builder.setIcon(R.mipmap.ic_launcher);//设置图标
        builder.setItems(item_list, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this ,"我是"+item_list[which] , Toast.LENGTH_LONG).show();
            }
        });
        AlertDialog dialog=builder.create();//获取dialog
        dialog.show();//显示对话框
    }
    /*
     *显示自定义对话框
     */
    private void showDialog5(){
        LayoutInflater inflater=LayoutInflater.from(this);
        View view=inflater.inflate(R.layout.dialog,null);
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("自定义对话框");//设置标题
        builder.setIcon(R.mipmap.ic_launcher);//设置图标
        builder.setView(view);
        //创建dialog
        final Dialog dialog=builder.create();
        Button bt = (Button) view.findViewById(R.id.bt);
        final EditText et = (EditText) view.findViewById(R.id.editText);
        bt.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String str=et.getText().toString();
                Toast.makeText(MainActivity.this,"提交的内容是"+str,Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });
        dialog.show();//显示对话框
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>NeuralNetwork.Layers</title>
<meta name="date" content="2017-05-25">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package NeuralNetwork.Layers

Regroups the different layer types used in the neural network.

See: Description

Class Summary

Class
Description

HiddenLayer

Describes the network's hidden layer.

InputLayer

Describes the network's input layer

Layer

Describes Layer in the Neural network

OutputLayer

Represents the networks output layer

Package NeuralNetwork.Layers Description

Regroups the different layer types used in the neural network.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
var debug = require('debug')('changelog:printSection');
var format = require('util').format;

function printCommit(commit, printCommitLinks) {
  var prefix = '';
  var result = '';

  if (printCommitLinks) {
    result += format('%s\n  (%s', commit.subject, this.linkToCommit(commit.hash));

    if (commit.closes.length) {
     result += ',\n   ' + commit.closes.map(this.linkToIssue, this).join(', ');
    }
    result += ')\n';
  } else {
    result += format('%s\n', commit.subject);
  }

  return result;
}

module.exports = printCommit;


text:
package com.gentics.mesh.core.rest.common;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;

/**
 * Paging meta info model.
 */
public class PagingMetaInfo {

	@JsonProperty(required = true)
	@JsonPropertyDescription("Number of the current page.")
	private long currentPage;

	@JsonProperty(required = true)
	@JsonPropertyDescription("Number of elements which can be included in a single page.")
	private Long perPage;

	@JsonProperty(required = true)
	@JsonPropertyDescription("Number of the pages which can be found for the given per page count.")
	private long pageCount;

	@JsonProperty(required = true)
	@JsonPropertyDescription("Number of all elements which could be found.")
	private long totalCount;

	public PagingMetaInfo() {
	}

	/**
	 * Return the current page number.
	 *
	 * @return Current page number
	 */
	public long getCurrentPage() {
		return currentPage;
	}

	/**
	 * Set the current page number.
	 *
	 * @param currentPage
	 *            Current page number
	 * @return Fluent API
	 */
	public PagingMetaInfo setCurrentPage(long currentPage) {
		this.currentPage = currentPage;
		return this;
	}

	/**
	 * Return the amount of items that should be included in one page.
	 *
	 * @return Per page count
	 */
	public Long getPerPage() {
		return perPage;
	}

	/**
	 * Set the per page count.
	 *
	 * @param perPage
	 *            Per page count
	 * @return Fluent API
	 */
	public PagingMetaInfo setPerPage(Long perPage) {
		this.perPage = perPage;
		return this;
	}

	/**
	 * Return the total page count.
	 *
	 * @return Total page count
	 */
	public long getPageCount() {
		return pageCount;
	}

	/**
	 * Set the total page count.
	 *
	 * @param pageCount
	 *            Total page count
	 * @return Fluent API
	 */
	public PagingMetaInfo setPageCount(long pageCount) {
		this.pageCount = pageCount;
		return this;
	}

	/**
	 * Return the total element count.
	 *
	 * @return Total element count
	 */
	public long getTotalCount() {
		return totalCount;
	}

	/**
	 * Set the total element count.
	 *
	 * @param totalCount
	 *            Total element count
	 * @return Fluent API
	 */
	public PagingMetaInfo setTotalCount(long totalCount) {
		this.totalCount = totalCount;
		return this;
	}

}


text:
"""
Simulation to examine the P(reject) as the number of test locations
increases.
"""
__author__ = 'wittawat'

import kgof
import kgof.data as data
import kgof.glo as glo
import kgof.density as density
import kgof.goftest as gof
import kgof.util as util
import kgof.kernel as kernel

# need independent_jobs package
# https://github.com/karlnapf/independent-jobs
# The independent_jobs and kgof have to be in the global search path (.bashrc)
import independent_jobs as inj
from independent_jobs.jobs.IndependentJob import IndependentJob
from independent_jobs.results.SingleResult import SingleResult
from independent_jobs.aggregators.SingleResultAggregator import SingleResultAggregator
from independent_jobs.engines.BatchClusterParameters import BatchClusterParameters
from independent_jobs.engines.SerialComputationEngine import SerialComputationEngine
from independent_jobs.engines.SlurmComputationEngine import SlurmComputationEngine
from independent_jobs.tools.Log import logger
import logging
import math
#import numpy as np
import autograd.numpy as np
import os
import sys
import time

"""
All the job functions return a dictionary with the following keys:
    - goftest: test object. (may or may not return)
    - test_result: the result from calling perform_test(te).
    - time_secs: run time in seconds
"""

def job_fssdq_med(p, data_source, tr, te, r, J, null_sim=None):
    """
    FSSD test with a Gaussian kernel, where the test locations are randomized,
    and the Gaussian width is set with the median heuristic. Use full sample.
    No training/testing splits.

    p: an UnnormalizedDensity
    data_source: a DataSource
    tr, te: Data
    r: trial number (positive integer)
    """
    if null_sim is None:
        null_sim = gof.FSSDH0SimCovObs(n_simulate=2000, seed=r)

    # full data
    data = tr + te
    X = data.data()
    with util.ContextTimer() as t:
        # median heuristic
        med = util.meddistance(X, subsample=1000)
        k = kernel.KGauss(med**2)
        V = util.fit_gaussian_draw(X, J, seed=r+1)

        fssd_med = gof.FSSD(p, k, V, null_sim=null_sim, alpha=alpha)
        fssd_med_result = fssd_med.perform_test(data)
    return { 'test_result': fssd_med_result, 'time_secs': t.secs}

def job_fssdq_opt(p, data_source, tr, te, r, J, null_sim=None):
    """
    FSSD with optimization on tr. Test on te. Use a Gaussian kernel.
    """
    if null_sim is None:
        null_sim = gof.FSSDH0SimCovObs(n_simulate=2000, seed=r)

    Xtr = tr.data()
    with util.ContextTimer() as t:
        # Use grid search to initialize the gwidth
        n_gwidth_cand = 5
        gwidth_factors = 2.0**np.linspace(-3, 3, n_gwidth_cand)
        med2 = util.meddistance(Xtr, 1000)**2

        k = kernel.KGauss(med2*2)
        # fit a Gaussian to the data and draw to initialize V0
        V0 = util.fit_gaussian_draw(Xtr, J, seed=r+1, reg=1e-6)
        list_gwidth = np.hstack( ( (med2)*gwidth_factors ) )
        besti, objs = gof.GaussFSSD.grid_search_gwidth(p, tr, V0, list_gwidth)
        gwidth = list_gwidth[besti]
        assert util.is_real_num(gwidth), 'gwidth not real. Was %s'%str(gwidth)
        assert gwidth > 0, 'gwidth not positive. Was %.3g'%gwidth
        logging.info('After grid search, gwidth=%.3g'%gwidth)

        ops = {
            'reg': 1e-2,
            'max_iter': 50,
            'tol_fun': 1e-4,
            'disp': True,
            'locs_bounds_frac': 10.0,
            'gwidth_lb': 1e-1,
            'gwidth_ub': 1e3,
            }

        V_opt, gwidth_opt, info = gof.GaussFSSD.optimize_locs_widths(p, tr,
                gwidth, V0, **ops)
        # Use the optimized parameters to construct a test
        k_opt = kernel.KGauss(gwidth_opt)
        fssd_opt = gof.FSSD(p, k_opt, V_opt, null_sim=null_sim, alpha=alpha)
        fssd_opt_result = fssd_opt.perform_test(te)
    return {'test_result': fssd_opt_result, 'time_secs': t.secs,
            'goftest': fssd_opt, 'opt_info': info,
            }

def job_fssdp_opt(p, data_source, tr, te, r, J):
    """
    The suffix p means that p is sampled to get a sample for computing the
    covariance matrix under H0.
    """
    null_sim = gof.FSSDH0SimCovDraw(n_draw=2000, n_simulate=2000, seed=r)
    return job_fssdq_opt(p, data_source, tr, te, r, J, null_sim=null_sim)

# Define our custom Job, which inherits from base class IndependentJob
class Ex3Job(IndependentJob):

    def __init__(self, aggregator, p, data_source,
            prob_label, rep, job_func, n_locs):
        #walltime = 60*59*24
        walltime = 60*59
        memory = int(tr_proportion*sample_size*1e-2) + 50

        IndependentJob.__init__(self, aggregator, walltime=walltime,
                               memory=memory)
        # p: an UnnormalizedDensity
        self.p = p
        self.data_source = data_source
        self.prob_label = prob_label
        self.rep = rep
        self.job_func = job_func
        self.n_locs = n_locs

    # we need to define the abstract compute method. It has to return an instance
    # of JobResult base class
    def compute(self):

        p = self.p
        data_source = self.data_source
        r = self.rep
        n_locs = self.n_locs
        job_func = self.job_func
        # sample_size is a global variable
        data = data_source.sample(sample_size, seed=r)
        with util.ContextTimer() as t:
            tr, te = data.split_tr_te(tr_proportion=tr_proportion, seed=r+21 )
            prob_label = self.prob_label
            logger.info("computing. %s. prob=%s, r=%d,\
                    J=%d"%(job_func.__name__, prob_label, r, n_locs))

            job_result = job_func(p, data_source, tr, te, r, n_locs)

            # create ScalarResult instance
            result = SingleResult(job_result)
            # submit the result to my own aggregator
            self.aggregator.submit_result(result)
            func_name = job_func.__name__
        logger.info("done. ex2: %s, prob=%s, r=%d, J=%d. Took: %.3g s "%(func_name,
            prob_label, r, n_locs, t.secs))

        # save result
        fname = '%s-%s-n%d_r%d_J%d_a%.3f_trp%.2f.p' \
                %(prob_label, func_name, sample_size, r, n_locs, alpha,
                        tr_proportion)
        glo.ex_save_result(ex, job_result, prob_label, fname)

# This import is needed so that pickle knows about the class Ex3Job.
# pickle is used when collecting the results from the submitted jobs.
from kgof.ex.ex3_vary_nlocs import Ex3Job
from kgof.ex.ex3_vary_nlocs import job_fssdq_med
from kgof.ex.ex3_vary_nlocs import job_fssdq_opt
from kgof.ex.ex3_vary_nlocs import job_fssdp_opt

#--- experimental setting -----
ex = 3

# sample size = n (the training and test sizes are n/2)
sample_size = 500

# number of test locations / test frequencies J
alpha = 0.05
tr_proportion = 0.5
# repetitions for each parameter setting
reps = 300

# list of number of test locations/frequencies
#Js = [5, 10, 15, 20, 25]
#Js = range(2, 6+1)
#Js = [2**x for x in range(5)]
Js = [2, 8, 32, 96, 384 ]
#Js = [2, 8, 32]

method_job_funcs = [ job_fssdq_med, job_fssdq_opt,
        #job_fssdp_opt,
        ]

# If is_rerun==False, do not rerun the experiment if a result file for the current
# setting already exists.
is_rerun = False
#---------------------------

def gaussbern_rbm_tuple(var, dx=50, dh=10, n=sample_size):
    """
    Get a tuple of Gaussian-Bernoulli RBM problems.
    We follow the parameter settings as described in section 6 of Liu et al.,
    2016.

    - var: Gaussian noise variance for perturbing B.
    - dx: observed dimension
    - dh: latent dimension

    Return p, a DataSource
    """
    with util.NumpySeedContext(seed=1000):
        B = np.random.randint(0, 2, (dx, dh))*2 - 1.0
        b = np.random.randn(dx)
        c = np.random.randn(dh)
        p = density.GaussBernRBM(B, b, c)

        B_perturb = B + np.random.randn(dx, dh)*np.sqrt(var)
        gb_rbm = data.DSGaussBernRBM(B_perturb, b, c, burnin=50)

    return p, gb_rbm

def get_pqsource(prob_label):
    """
    Return (p, ds), a tuple of
    - p: a Density representing the distribution p
    - ds: a DataSource, each corresponding to one parameter setting.
        The DataSource generates sample from q.
    """
    prob2tuples = {
            # H0 is true. vary d. P = Q = N(0, I)
            'sg5': (density.IsotropicNormal(np.zeros(5), 1),
                data.DSIsotropicNormal(np.zeros(5), 1) ),

            # P = N(0, I), Q = N( (0.2,..0), I)
            'gmd5': (density.IsotropicNormal(np.zeros(5), 1),
                data.DSIsotropicNormal(np.hstack((0.2, np.zeros(4))), 1) ),

            'gmd1': (density.IsotropicNormal(np.zeros(1), 1),
                data.DSIsotropicNormal(np.ones(1)*0.2, 1) ),

            # P = N(0, I), Q = N( (1,..0), I)
            'gmd100': (density.IsotropicNormal(np.zeros(100), 1),
                data.DSIsotropicNormal(np.hstack((1, np.zeros(99))), 1) ),

            # Gaussian variance difference problem. Only the variance
            # of the first dimenion differs. d varies.
            'gvd5': (density.Normal(np.zeros(5), np.eye(5) ),
                data.DSNormal(np.zeros(5), np.diag(np.hstack((2, np.ones(4)))) )),

            'gvd10': (density.Normal(np.zeros(10), np.eye(10) ),
                data.DSNormal(np.zeros(10), np.diag(np.hstack((2, np.ones(9)))) )),

            # Gaussian Bernoulli RBM. dx=50, dh=10. H0 is true
            'gbrbm_dx50_dh10_v0': gaussbern_rbm_tuple(0,
                dx=50, dh=10, n=sample_size),

            # Gaussian Bernoulli RBM. dx=5, dh=3. H0 is true
            'gbrbm_dx5_dh3_v0': gaussbern_rbm_tuple(0,
                dx=5, dh=3, n=sample_size),

            # Gaussian Bernoulli RBM. dx=50, dh=10.
            'gbrbm_dx50_dh10_v1em3': gaussbern_rbm_tuple(1e-3,
                dx=50, dh=10, n=sample_size),

            # Gaussian Bernoulli RBM. dx=5, dh=3. Perturb with noise = 1e-2.
            'gbrbm_dx5_dh3_v5em3': gaussbern_rbm_tuple(5e-3,
                dx=5, dh=3, n=sample_size),

            # Gaussian mixture of two components. Uniform mixture weights.
            # p = 0.5*N(0, 1) + 0.5*N(3, 0.01)
            # q = 0.5*N(-3, 0.01) + 0.5*N(0, 1)
            'gmm_d1': (
                density.IsoGaussianMixture(np.array([[0], [3.0]]), np.array([1, 0.01]) ),
                data.DSIsoGaussianMixture(np.array([[-3.0], [0]]), np.array([0.01, 1]) )
                ),

            # p = N(0, 1)
            # q = 0.1*N([-10, 0,..0], 0.001) + 0.9*N([0,0,..0], 1)
            'g_vs_gmm_d5': (
                    density.IsotropicNormal(np.zeros(5), 1),
                    data.DSIsoGaussianMixture(
                        np.vstack(( np.hstack((0.0, np.zeros(4))), np.zeros(5) )),
                        np.array([0.0001, 1]), pmix=[0.1, 0.9] )
                    ),

            'g_vs_gmm_d2': (
                    density.IsotropicNormal(np.zeros(2), 1),
                    data.DSIsoGaussianMixture(
                        np.vstack(( np.hstack((0.0, np.zeros(1))), np.zeros(2) )),
                        np.array([0.01, 1]), pmix=[0.1, 0.9] )
                    ),
            'g_vs_gmm_d1': (
                    density.IsotropicNormal(np.zeros(1), 1),
                    data.DSIsoGaussianMixture(np.array([[0.0], [0]]),
                        np.array([0.01, 1]), pmix=[0.1, 0.9] )
                    ),
            }
    if prob_label not in prob2tuples:
        raise ValueError('Unknown problem label. Need to be one of %s'%str(prob2tuples.keys()) )
    return prob2tuples[prob_label]

def run_problem(prob_label):
    """Run the experiment"""
    p, ds = get_pqsource(prob_label)

    # ///////  submit jobs //////////
    # create folder name string
    #result_folder = glo.result_folder()
    from kgof.config import expr_configs
    tmp_dir = expr_configs['scratch_path']
    foldername = os.path.join(tmp_dir, 'kgof_slurm', 'e%d'%ex)
    logger.info("Setting engine folder to %s" % foldername)

    # create parameter instance that is needed for any batch computation engine
    logger.info("Creating batch parameter instance")
    batch_parameters = BatchClusterParameters(
        foldername=foldername, job_name_base="e%d_"%ex, parameter_prefix="")

    # Use the following line if Slurm queue is not used.
    #engine = SerialComputationEngine()
    engine = SlurmComputationEngine(batch_parameters)
    n_methods = len(method_job_funcs)
    # repetitions x len(Js) x #methods
    aggregators = np.empty((reps, len(Js), n_methods ), dtype=object)
    for r in range(reps):
        for ji, J in enumerate(Js):
            for mi, f in enumerate(method_job_funcs):
                # name used to save the result
                func_name = f.__name__
                fname = '%s-%s-n%d_r%d_J%d_a%.3f_trp%.2f.p' \
                        %(prob_label, func_name, sample_size, r, J, alpha,
                                tr_proportion)
                if not is_rerun and glo.ex_file_exists(ex, prob_label, fname):
                    logger.info('%s exists. Load and return.'%fname)
                    job_result = glo.ex_load_result(ex, prob_label, fname)

                    sra = SingleResultAggregator()
                    sra.submit_result(SingleResult(job_result))
                    aggregators[r, ji, mi] = sra
                else:
                    # result not exists or rerun

                    # p: an UnnormalizedDensity object
                    job = Ex3Job(SingleResultAggregator(), p, ds, prob_label,
                            r, f, J)
                    agg = engine.submit_job(job)
                    aggregators[r, ji, mi] = agg

    # let the engine finish its business
    logger.info("Wait for all call in engine")
    engine.wait_for_all()

    # ////// collect the results ///////////
    logger.info("Collecting results")
    job_results = np.empty((reps, len(Js), n_methods), dtype=object)
    for r in range(reps):
        for ji, J in enumerate(Js):
            for mi, f in enumerate(method_job_funcs):
                logger.info("Collecting result (%s, r=%d, J=%rd)" %
                        (f.__name__, r, J))
                # let the aggregator finalize things
                aggregators[r, ji, mi].finalize()

                # aggregators[i].get_final_result() returns a SingleResult instance,
                # which we need to extract the actual result
                job_result = aggregators[r, ji, mi].get_final_result().result
                job_results[r, ji, mi] = job_result

    #func_names = [f.__name__ for f in method_job_funcs]
    #func2labels = exglobal.get_func2label_map()
    #method_labels = [func2labels[f] for f in func_names if f in func2labels]

    # save results
    results = {'job_results': job_results, 'data_source': ds,
            'alpha': alpha, 'repeats': reps, 'Js': Js,
            'p': p,
            'tr_proportion': tr_proportion,
            'method_job_funcs': method_job_funcs, 'prob_label': prob_label,
            'sample_size': sample_size,
            }

    # class name
    fname = 'ex%d-%s-me%d_n%d_rs%d_Jmi%d_Jma%d_a%.3f_trp%.2f.p' \
        %(ex, prob_label, n_methods, sample_size, reps, min(Js),
                max(Js), alpha, tr_proportion)

    glo.ex_save_result(ex, results, fname)
    logger.info('Saved aggregated results to %s'%fname)

def main():
    if len(sys.argv) != 2:
        print('Usage: %s problem_label'%sys.argv[0])
        sys.exit(1)
    prob_label = sys.argv[1]

    run_problem(prob_label)

if __name__ == '__main__':
    main()


text:
void bones_copy<direction>_<id>_<array>(<definition>) {
  cudaStreamSynchronize(kernel_stream);
  bones_memcpy(<array><flatten>+<offset>, device_<array>+<offset>, <variable_dimensions>*sizeof(<type>), cudaMemcpyDeviceToHost, <state>, <index>);
}