text:
import hashlib, urllib
import sys, os, os.path
from shutil import copy2 as copyfile
from glob import glob
from optparse import OptionParser
from tempfile import NamedTemporaryFile
import subprocess

FILE_FORMATS = ['avi', 'mpg', 'mpeg', 'mp4', 'rmvb', 'mkv', 'mov', 'wmv',]

def convert(z):
    idx = [ 0xe, 0x3,  0x6, 0x8, 0x2 ]
    mul = [   2,   2,    5,   4,   3 ]
    add = [   0, 0xd, 0x10, 0xb, 0x5 ]

    b = []
    for i in xrange(len(idx)):
        a = add[i]
        m = mul[i]
        i = idx[i]

        t = a + int(z[i], 16)
        v = int(z[t:t+2], 16)
        b.append( ("%x" % (v*m))[-1] )

    return ''.join(b)

def split_fn_ext(filename):
    """
    Return tuple of directory and filename and extenstion.
    """
    l = filename.rpartition('.')
    d = filename.rpartition('/')
    l = d[2].rpartition('.')
    di = ''
    if d[0] == '':
        di = ''
    else:
        di = d[0] + '/'
    return (di, l[0], l[2])

def split_ext(filename):
    """
    Return tuple of filename and extenstion.
    """
    l = filename.rpartition('.')
    return (l[0], l[2])

def gen_hashname(fname):
    hp = split_fn_ext(fname)
    r = hp[0] + '.' + hp[1] + '.hash'
    verbose("hashname: " + r);
    return r

def gen_url(fname):
    hashpath=gen_hashname(fname)
    #message(os.path.basename(hashpath), "hash", 1)
    first_line=""
    if os.path.exists(hashpath):
        verbose("hash exists");
        with open(hashpath, 'r') as f:
            hexdigest = f.readline()
        verbose("cached hash %s" % (hexdigest))
        message(os.path.basename(fname), "Cached hash %s" % (hexdigest), 1)
    else:
        hashsum = hashlib.md5();
        hashsum.update(open(fname).read(10485760))
        hexdigest = hashsum.hexdigest()
        verbose("generated hash: " + hexdigest);
        with open(hashpath, 'w') as f:
            f.write(hexdigest)

    url = "http://napiprojekt.pl/unit_napisy/dl.php?l=PL&f=%s&t=%s&v=other&kolejka=false&nick=&pass=&napios=%s" % (
            hexdigest, convert(hexdigest), os.name)
    verbose("url: " + url);
    return url

def run_command(command):
    verbose("running: [%s]" % ', '.join(map(str, command)));
    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

def get_subtitle(fname):
    txtpath=split_ext(fname)[0] + '.txt'
    srtpath=split_ext(fname)[0] + '.srt'
    hashpath=gen_hashname(fname)

    verbose("txtpath: " + txtpath);
    verbose("srtpath: " + srtpath);
    verbose("hashpath: " + hashpath);

    if os.path.exists(txtpath):
        message(os.path.basename(fname), "OK (exists)", 1)
    else:
        message(os.path.basename(fname), "Searching...", 1)
        url = gen_url(fname)
        f_archive7z = NamedTemporaryFile(delete=False)
        verbose("f_archive7z: " + str(f_archive7z));
        f_archive7z.write(urllib.urlopen(url).read())
        f_archive7z.close() # flush buffers
        f_newtxt = NamedTemporaryFile(delete=False)
        verbose("f_newtxt: " + str(f_newtxt));
        f_newtxt.close()

        # XXX Use this when resolved - http://bugs.python.org/issue5689
        if os.system("7z x -y -so -piBlm8NTigvru0Jr0 %s 2>/dev/null >\"%s\"" % (f_archive7z.name, f_newtxt.name)):
            message(os.path.basename(fname), "FAIL", 1)
        else:
            try:
                command = ["file", f_newtxt.name]
                txtype = 0
                for line in run_command(command):
                    if line.find('UTF') > 0:
                        txtype = 1
                verbose("txtype: " + str(txtype))
                if txtype == 0:
                    message(os.path.basename(fname), "Trying to make UTF", 1)
                    f_newtxtu8 = NamedTemporaryFile(delete=False)
                    verbose("f_newtxtu8: " + str(f_newtxtu8));
                    f_newtxtu8.close()
                    os.system("iconv -f windows-1250 -t utf-8 -o %s %s" % (f_newtxtu8.name, f_newtxt.name))
                    verbose("copy " + str(f_newtxtu8.name) + " to " + str(f_newtxt));
                    copyfile(f_newtxtu8.name, f_newtxt.name)
                    os.remove(f_newtxtu8.name)
                if options.subrip:
                    message(os.path.basename(fname), "Trying to make SRT", 1)
                    if 0 != os.system("mplayer -frames 0 -really-quiet -vo null -ao null -subcp utf8 -sub \"%s\" -dumpsrtsub \"%s\"" %(
                        f_newtxt.name, fname)) or 0 != os.system("mv dumpsub.srt \"%s\"" %(srtpath)):
                        message(os.path.basename(fname), "Failed to make SRT", 1)
                verbose("copy " + str(f_newtxt.name) + " to " + str(txtpath));
                copyfile(f_newtxt.name, txtpath)
                os.remove(hashpath)
                message(os.path.basename(fname), "OK", 1)
            except:
                message(os.path.basename(fname), sys.exc_info(), 1)
            finally:
                os.remove(f_archive7z.name)
                os.remove(f_newtxt.name)

def get_files(dirpath):
    def add_file(l, directory, files):
        for f in files:
            path = os.path.join(directory, f)
            if os.path.isfile(path) and split_ext(f)[1].lower() in FILE_FORMATS:
                l.append(path)

    l = []
    if dirpath and os.path.isdir(dirpath):
        os.path.walk(dirpath, add_file, l)
    else:
        message(dirpath, 'NOT FOUND', 0)
    return l

def message(file, message, type):
    if not options.silent:
        if type == 1:
            print("%s - %s" % (file, message))
        else:
            print("%s - %s" % (file, message))

def verbose(message):
    if not options.silent:
        if options.verbose:
            print("> %s" % message)

def which(program):
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

def needed_software(name):
    verbose("checking " + name)
    if which(name) is None:
        print('You must install %s to use this program.' % (name))
        sys.exit(2)

if __name__=='__main__':
    usage = "usage: %prog [options] FILE1 FILE2 ..."
    parser = OptionParser(usage)
    parser.add_option("-e", "--ext", dest="ext", metavar="EXT1,EXT2",
                      help="follow up additional extensions")
    parser.add_option("-s", "--silent", dest="silent", action="store_true",
                      help="silent mode")
    parser.add_option("-r", "--subrip", dest="subrip", action="store_true",
                      help="use mplayer for generating .srt")
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                      help="be more verbose")
    (options, args) = parser.parse_args()

    if not args:
        parser.print_help()
        sys.exit(1)

    needed_software("iconv")
    needed_software("mplayer")
    needed_software("7z")
    needed_software("mv")

    verbose("options.ext " + str(options.ext));
    verbose("options.subrip " + str(options.subrip));
    verbose("options.silent " + str(options.silent));
    verbose("options.verbose " + str(options.verbose));

    # add new extesions to the list
    if options.ext:
        l = options.ext.split(',')
        FILE_FORMATS.extend([ x.lower() for x in l ])

    # detect dirs
    filelist = []
    for f in args:
        if os.path.isdir(f):
            filelist.extend(get_files(f))
        else:
            filelist.append(f)

    # main action
    for f in filelist:
        if os.path.isfile(f):
            verbose("file " + f);
            get_subtitle(f)
        else:
            message(f, "NOT FOUND", 0)


text:
import PropTypes, { shape } from 'prop-types';

import { nodePropTypes } from 'models/node';
import { positionPropTypes } from 'models/position';
import { linkagesPropTypes } from 'models/linkage';

const beliefsPropTypes = PropTypes.objectOf(PropTypes.string);
const beliefsMSBNPropTypes = PropTypes.objectOf(beliefsPropTypes);

export const subNetworkInferenceResultsPropTypes = PropTypes.objectOf(
  PropTypes.objectOf(PropTypes.number),
);

export const networkConnection = shape({
  color: PropTypes.string.isRequired,
  networkId: PropTypes.string.isRequired,
  networkName: PropTypes.string.isRequired,
  nodeId: PropTypes.string.isRequired,
});

export const linkedNodePropTypes = shape({
  connections: PropTypes.arrayOf(networkConnection).isRequired,
  nodeId: PropTypes.string.isRequired,
});

const networkShape = {
  height: PropTypes.number.isRequired,
  id: PropTypes.string.isRequired,
  kind: PropTypes.string.isRequired,
  linkages: linkagesPropTypes.isRequired,
  beliefs: PropTypes.oneOfType([beliefsPropTypes, beliefsMSBNPropTypes]).isRequired,
  name: PropTypes.string.isRequired,
  nodes: PropTypes.arrayOf(nodePropTypes),
  positions: PropTypes.objectOf(positionPropTypes),
  propertiesPanelVisible: PropTypes.bool.isRequired,
  selectedNodes: PropTypes.arrayOf(PropTypes.string).isRequired,
  width: PropTypes.number.isRequired,
};

export const networkPropTypes = shape({
  ...networkShape,
  subnetworks: PropTypes.arrayOf(shape(networkShape)),
});

export const subnetworkPropTypes = PropTypes.shape({
  ...networkShape,
  color: PropTypes.string.isRequired,
});

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PLACEHOLDER_TITLE</title>

<frameset cols="*, 400" frameborder="0" framespacing="0">
  <frame src="PLACEHOLDER_MAPINDEX" name="mapIndex" noresize="noresize" frameborder="0" marginwidth="0" marginheight="0" />
  <frame src="PLACEHOLDER_DETAIL_FILE" name="unitDetailsIndex" noresize="noresize" frameborder="0" marginwidth="0" marginheight="0" />
  <noframes>

This page uses frames. The current browser you are using does not support frames.

  </noframes>
</frameset>


text:
require 'rubygems'
require 'epic'

module YMDP
  # Contains all the functions which are available from inside a view file, whether that view
  # is HTML, JavaScript or CSS.
  #
  module ApplicationView

    extend self

    # Returns an array of the country codes of all languages supported by the application,
    # which is determined by the language-specific folders in "app/assets/yrb".
    #
    # ==== Examples
    #
    #   supported_languages
    #   # => ["en-US", "de-DE", "es-ES", "es-MX"]
    #
    def supported_languages
      YAML.load_file("./config/idiom.yml")["locales"].keys
    end

    def translations
      @translations ||= {}

      Dir["./config/locales/**/*.yml"].each do |file|
        @translations.merge!(YAML.load_file(file)) do |key, old, new|
          old.merge new
        end
      end

      @translations
    end

    # Returns an array of country codes of English-speaking countries supported
    # by the application, based on the language-specific folders located in "app/assets/yrb".
    #
    # ==== Examples
    #
    #   english_languages
    #   # => ["en-US", "en-AU", "en-SG", "en-MY"]
    #
    def english_languages
      supported_languages.select do |lang|
        lang =~ /^en/
      end
    end

    # Includes a JavaScript file in a view.  If the filename is a full path, the
    # JavaScript file will be linked as an external asset.  If not, the file will
    # linked as a local asset located in the YMDP application's assets directory.
    #
    # === Local JavaScript Assets
    #
    #   javascript_include("application.js")
    #
    # will produce:
    #
    #
    #
    # === External JavaScript Assets
    #
    #   javascript_include("http://www.myserver.com/javascripts/application.js")
    #
    # will produce:
    #
    #
    #
    def javascript_include(filename, options={})
      if filename == :defaults
        render_default_javascripts(options)
        filename = "defaults.js"
      end
      unless filename =~ /^http/
        filename = "#{@assets_directory}/javascripts/#{filename}"
      end
      ""
    end

    def combo(filenames, options={})
      paths = filenames.map do |filename|
        "javascripts/#{filename}"
      end.join("&")
      ""
    end

    # Renders a link to include Firebug Lite for debugging JavaScript in Internet Explorer.
    #
    def include_firebug_lite
      javascript_include "http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"
    end

    # Renders a partial into the current view. HTML partial names must be preceded with an underscore.
    #
    # == Rendering an HTML partial
    #
    # HTML partials are located in <tt>app/views</tt>. HTML view files can be Haml or ERB.
    # Haml is recommended and takes preference. HTML partials are named <tt>_filename.html.haml</tt>
    # or <tt>_filename.html.erb</tt>.
    #
    #   render :partial => 'sidebar'
    #
    # will find <tt>app/views/_sidebar.html.haml</tt> or <tt>app/views/_sidebar.html.erb</tt>
    # and render its contents into the current view.
    #
    # Specify a full path to indicate a specific template.
    #
    #   render :partial => 'sidebar.html.erb'
    #
    # will find <tt>app/views/_sidebar.html.erb'</tt> and render it even if
    # <tt>app/views/_sidebar.html.haml</tt> exists.
    #
    #   render :partial => 'shared/sidebar'
    #
    # will find <tt>app/views/shared/_sidebar.html.haml</tt> and render its contents into the current view.
    #
    # == Rendering a JavaScript partial
    #
    # You can render a single JavaScript file or send an array to concatenate a set of JavaScript
    # files together asone script block.
    #
    # === Rendering a single JavaScript partial
    #
    # JavaScript partials are located in <tt>app/javascripts</tt> and are named <tt>filename.js</tt>
    #
    #   render :javascript => 'application'
    #
    # will find <tt>app/javascripts/application.js</tt> and render its contents into the current view
    # in an inline script block.
    #
    #   render :javascript => 'shared/sidebar'
    #
    # will find <tt>app/javascripts/shared/sidebar.js</tt> and render its contents into the current
    # view in an inline script block.
    #
    # == Rendering a stylesheet partial
    #
    # Stylesheets are located at <tt>app/stylesheets</tt> and are named <tt>_filename_.css</tt>
    #
    #
    # === Rendering multiple partials
    #
    # Pass an array to <tt>render</tt> to combine multiple files into a single
    # inline block.  This is useful for compression and validation, as it allows a set of
    # files to be compressed or validated in a single context.
    #
    #   render :javascript => ['application', 'flash', 'debug']
    #
    # will combine the contents of <tt>app/javascripts/application.js</tt>,
    # <tt>app/javascripts/application.js</tt>, and <tt>app/javascripts/application.js</tt>
    # into a single script block in the current view.
    #
    # Pass a <tt>:filename</tt> parameter to set the name of the combined file.  Currently the
    # combined file only exists on disc while it's being compressed and/or validated, but
    # in the future this may be expanded to save multiple files as a single external asset.
    #
    #   render :javascript => ['application', 'flash', 'debug'], :filename => 'javascripts'
    #
    # Currently the <tt>:filename</tt> parameter is simply a convenience.
    #
    # Multiple partials of any type can be rendered.
    #
    # For example:
    #
    #   render :partial => ['header', 'footer', 'sidebar'], :filename => 'html_layouts'
    #
    # will find <tt>app/views/_header.html.haml</tt>, <tt>app/views/_footer.html.haml</tt>,
    # and <tt>app/views/_sidebar.html.haml</tt> and write them to a temporary file called
    # <tt>tmp/html_layouts</tt> before rendering that file into the current view.
    #
    # This feature is intended mainly for JavaScript and CSS.
    #
    # For example:
    #
    #   render :stylesheet => ['application', 'colors'], :filename => 'styles'
    #
    # will render <tt>app/stylesheets/application.css</tt> and <tt>app/stylesheets/colors.css</tt>
    # as a single temporary file called <tt>tmp/styles</tt> before rendering that file into
    # the current view.
    #
    # If compression and validation options are turned on, the resulting temporary file will be
    # compressed and/or validated before being rendered into the current view.  This will result
    # in a more efficient compression and a more effective validation.
    #
    def render(params)
      output = []

      unless params.has_key?(:tags)
        params[:tags] = true
      end

      output << render_html_partial(params)
      output << render_javascript_partial(params) if params[:javascript]
      output << render_stylesheet_partial(params) if params[:stylesheet]

      output.flatten.join("\n")
    end

    private

    # Renders an HTML, Haml or ERB partial.
    #
    def render_html_partial(params)
      output = []

      if params[:partial]
        Array(params[:partial]).each do |partial|
          output << render_partial(partial)
        end
      end
      output
    end

    # Renders an HTML partial.
    #
    def render_partial(filename)
      output = ''
      path = find_partial(filename)

      if path && File.exists?(path)
        template = File.read(path)
        if path =~ /haml$/
          output = process_haml(template, path)
        else
          output = process_erb(template)
        end
      else
        raise "Could not find partial: #{filename}"
      end
      output
    end

    # Searches all the possible paths to find a match for this partial name.
    #
    def find_partial(full_path)
      path = nil
      ["views", "views/shared"].each do |dir|

        p = full_path.split("/")
        filename = p.pop

        filename = "_#{filename}"
        p.push(filename)

        final_path = p.join("/")

        basic_path = "#{BASE_PATH}/app/#{dir}/#{final_path}.html"

        ["", ".haml", ".erb"].each do |extension|
          if File.exists?(basic_path + extension)
            path ||= basic_path + extension
          end
        end
      end

      path
    end

    def render_default_javascripts(options={})
      library_path = options[:library] || configuration.javascript_library || "jquery"

      # Javascripts need to be loaded in a certain order, this is why we don't just load everything at once
      #
      default_javascripts = ['application', 'params', 'browser', 'data', 'ajax', 'user', 'init', 'reporter', 'debug', 'tag_helper', 'launcher', 'logger', 'i18n', 'flash', 'ab_testing', 'education', 'authorization']

      filenames = filter_filenames(default_javascripts, options)

      filenames = filenames.map do |filename|
        File.join(File.dirname(__FILE__), "..", "javascripts", library_path, "#{filename}.js")
      end

      output = combine_files(filenames)
      write_javascript_asset(output, "defaults")
    end

    def filter_filenames(filenames, options={})
      if options[:only]
        filenames = filenames.select do |filename|
          options[:only].include?(filename)
        end
      end
      if options[:except]
        filenames = filenames.reject do |filename|
          options[:except].include?(filename)
        end
      end
      filenames
    end

    def render_javascript_partial(params)
      filename = params[:filename] || Array(params[:javascript]).join("_")

      if configuration.external_assets["javascripts"]
        tags = false
      else
        tags = params[:tags]
      end

      output = []

      # Render a JavaScript partial.
      #
      if params[:javascript]
        content = render_javascripts(Array(params[:javascript]), params[:filename])
        unless content.blank?
          output << "" if tags
        end
      end

      output = output.join("\n")

      if configuration.external_assets["javascripts"] && params[:tags]
        write_javascript_asset(output, filename)

        ""
      else
        output
      end
    end

    def write_javascript_asset(output, filename)
      path = "#{server_path}/assets/javascripts/#{filename}.js"

      $stdout.puts "Writing #{path}"

      File.open(path, "w") do |f|
        f.write(output)
      end
    end

    def write_stylesheet_asset(output, filename)
      path = "#{server_path}/assets/stylesheets/#{filename}.css"

      $stdout.puts "Writing #{path}"

      output = Array(output).join("\n")

      File.open(path, "w") do |f|
        f.write(output)
      end
    end

    # Renders a JavaScript partial.
    #
    def render_javascripts(filenames, combined_filename=nil)
      filenames_str = combined_filename || filenames.join().gsub("/", "_")

      filenames.map! do |filename|
        filename.gsub!(/\.js$/, "")
        "#{BASE_PATH}/app/javascripts/#{filename}.js"
      end

      output = combine_files(filenames)
      tmp_filename = "#{TMP_PATH}/#{filenames_str}.js"

      validate = F.save_to_file(output, tmp_filename)

      if validate && configuration.validate["embedded_js"]["build"] && !js_validator.validate(tmp_filename)
        raise "JavaScript Errors embedded in #{display_path(tmp_filename)}"
      end

      output
    end

    def js_validator
      @js_validator ||= Epic::Validator::JavaScript.new
    end

    # Render a CSS partial.
    #
    def render_stylesheet_partial(params)
      filename = params[:filename] || Array(params[:stylesheet]).join("_")
      external_asset = params[:tags] && configuration.external_assets["stylesheets"]
      output = []
      if params[:stylesheet]
        content = render_stylesheets(Array(params[:stylesheet]), params[:filename])
        unless content.blank?
          output << "" unless external_asset
        end
      end

      if external_asset
        write_stylesheet_asset(output, filename)

        "<link rel='stylesheet' type='text/css' href='#{assets_directory}/stylesheets/#{filename}.css'></link>"
      else
        output
      end
    end

    # Renders a CSS partial.
    #
    def render_stylesheets(filenames, combined_filename=nil)
      filenames_str = combined_filename || filenames.join().gsub("/", "_")
      tmp_filename = "#{TMP_PATH}/#{filenames_str}.css"

      filenames.map! do |filename|
        filename.gsub!(/\.css$/, "")
        f = "#{BASE_PATH}/app/stylesheets/#{filename}.css"
        if !File.exists?(f)
          f = "#{BASE_PATH}/app/stylesheets/#{filename}"
        end
        f
      end

      output = combine_files(filenames)

      validate = F.save_to_file(output, tmp_filename)

      output
    end

    # Concatenates all files into one long string.
    #
    def combine_files(filenames)
      output = []
      filenames.each do |filename|
        output << render_without_compression(filename, false)
      end
      output.join("\n")
    end

    # Renders together a set of files without
    # compression, so they can be compressed as a single block.
    #
    def render_without_compression(path="", tags=true)
      path ||= ""
      output = ""

      if File.exists?("#{path}.coffee")
        path = "#{path}.coffee"
        $stdout.puts("Parsing #{path}")
        template = File.read(path)
        output = process_coffee(template)
      elsif File.exists?("#{path}.scss")
        path = "#{path}.scss"
        $stdout.puts("Parsing #{path}")
        template = File.read(path)
        output = process_scss(template)
      elsif File.exists?(path)
        $stdout.puts("Parsing #{path}")
        template = File.read(path)
        output = process_erb(template)
      end

      output
    end
  end

  class View
    include YMDP::ApplicationView

    def initialize(assets_directory)
      @assets_directory = assets_directory
    end
  end
end


text:
<?php // phpcs:ignoreFile

/**
 * This contains the information needed to convert the function signatures for php 8.2 to php 8.1 (and vice versa)
 *
 * This file has three sections.
 * The 'added' section contains function/method names from FunctionSignatureMap (And alternates, if applicable) that do not exist in php 8.1
 * The 'removed' section contains the signatures that were removed in php 8.2
 * The 'changed' section contains functions for which the signature has changed for php 8.2.
 *     Each function in the 'changed' section has an 'old' and a 'new' section,
 *     representing the function as it was in PHP 8.1 and in PHP 8.2, respectively
 *
 * @see CallMap.php
 *
 * @phan-file-suppress PhanPluginMixedKeyNoKey (read by Phan when analyzing this file)
 */
return [
  'added' => [
    'mysqli_execute_query' => ['mysqli_result|bool', 'mysqli'=>'mysqli', 'query'=>'non-empty-string', 'params='=>'list<string>|null'],
    'mysqli::execute_query' => ['mysqli_result|bool', 'query'=>'non-empty-string', 'params='=>'list<string>|null'],
    'openssl_cipher_key_length' => ['positive-int|false', 'cipher_algo'=>'non-empty-string'],
    'curl_upkeep' => ['bool', 'handle'=>'CurlHandle'],
    'ini_parse_quantity' => ['int', 'shorthand'=>'non-empty-string'],
    'memory_reset_peak_usage' => ['void'],
  ],

  'changed' => [
    'str_split' => [
       'old' => ['non-empty-list<string>', 'string'=>'string', 'length='=>'positive-int'],
       'new' => ['list<string>', 'string'=>'string', 'length='=>'positive-int'],
    ],
  ],

  'removed' => [
  ],
];


text:
// ------------------------------------
// Constants
// ------------------------------------
export const HEADER_TABS = 'HEADER_TABS'

// ------------------------------------
// Actions
// ------------------------------------
export function headerTabsChange (tab) {
  return {
    type    : HEADER_TABS,
    tab     : tab
  }
}

/*  This is a thunk, meaning it is a function that immediately
    returns a function for lazy evaluation. It is incredibly useful for
    creating async actions, especially when combined with redux-thunk! */

// export const doubleAsync = () => {
//   return (dispatch, getState) => {
//     return new Promise((resolve) => {
//       setTimeout(() => {
//         dispatch({
//           type    : COUNTER_DOUBLE_ASYNC,
//           payload : getState().counter
//         })
//         resolve()
//       }, 200)
//     })
//   }
// }

export const actions = {
  headerTabsChange
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [HEADER_TABS]    : (state, action) => { action.tabs }
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  headerTabs: 'member'
}

export default function consoleReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}


text:
package eu.drus.jpa.unit.decorator.jpa;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import javax.persistence.Cache;
import javax.persistence.EntityManagerFactory;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import eu.drus.jpa.unit.spi.Constants;
import eu.drus.jpa.unit.spi.ExecutionContext;
import eu.drus.jpa.unit.spi.FeatureResolver;
import eu.drus.jpa.unit.spi.TestInvocation;

@RunWith(MockitoJUnitRunner.class)
public class SecondLevelCacheDecoratorTest {

    @Mock
    private TestInvocation invocation;

    @Mock
    private FeatureResolver resolver;

    @Mock
    private ExecutionContext ctx;

    @Mock
    private EntityManagerFactory emf;

    @Mock
    private Cache cache;

    @Before
    public void setupMocks() throws Exception {
        when(invocation.getContext()).thenReturn(ctx);
        when(invocation.getFeatureResolver()).thenReturn(resolver);
        when(ctx.getData(eq(Constants.KEY_ENTITY_MANAGER_FACTORY))).thenReturn(emf);
        when(emf.getCache()).thenReturn(cache);
    }

    @Test
    public void testEvictionOfSecondLevelCacheIsDisabled() throws Throwable {
        // GIVEN
        final SecondLevelCacheDecorator fixture = new SecondLevelCacheDecorator();

        // WHEN
        fixture.beforeTest(invocation);
        fixture.afterTest(invocation);

        // THEN
        verifyNoMoreInteractions(cache, emf);
    }

    @Test
    public void testEvictionOfSecondLevelCacheIsRunInBeforeTestPhaseIfConfiguredForIt() throws Throwable {
        // GIVEN
        when(resolver.shouldEvictCacheBefore()).thenReturn(Boolean.TRUE);
        final SecondLevelCacheDecorator fixture = new SecondLevelCacheDecorator();

        // WHEN
        fixture.beforeTest(invocation);

        // THEN
        verify(cache).evictAll();
        verify(emf, times(0)).close();
    }

    @Test
    public void testEvictionOfSecondLevelCacheIsNotRunInBeforeTestPhaseIfNotConfiguredForIt() throws Throwable {
        // GIVEN
        when(resolver.shouldEvictCacheBefore()).thenReturn(Boolean.FALSE);
        final SecondLevelCacheDecorator fixture = new SecondLevelCacheDecorator();

        // WHEN
        fixture.beforeTest(invocation);

        // THEN
        verifyNoMoreInteractions(cache, emf);
    }

    @Test
    public void testEvictionOfSecondLevelCacheIsRunInAfterTestPhaseIfConfiguredForIt() throws Throwable {
        // GIVEN
        when(resolver.shouldEvictCacheAfter()).thenReturn(Boolean.TRUE);
        final SecondLevelCacheDecorator fixture = new SecondLevelCacheDecorator();

        // WHEN
        fixture.afterTest(invocation);

        // THEN
        verify(cache).evictAll();
        verify(emf, times(0)).close();
    }

    @Test
    public void testEvictionOfSecondLevelCacheIsNotRunInAfterTestPhaseIfNotConfiguredForIt() throws Throwable {
        // GIVEN
        when(resolver.shouldEvictCacheAfter()).thenReturn(Boolean.FALSE);
        final SecondLevelCacheDecorator fixture = new SecondLevelCacheDecorator();

        // WHEN
        fixture.afterTest(invocation);

        // THEN
        verifyNoMoreInteractions(cache, emf);
    }

    @Test
    public void testRequiredPriority() {
        // GIVEN
        final SecondLevelCacheDecorator fixture = new SecondLevelCacheDecorator();

        // WHEN
        final int priority = fixture.getPriority();

        // THEN
        assertThat(priority, equalTo(0));
    }
}


text:
<?php

namespace Symfony\Bridge\Twig\Tests\Extension;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Twig\Environment;
use Twig\Node\Expression\FilterExpression;
use Twig\Source;

class RoutingExtensionTest extends TestCase
{
    /**
     * @dataProvider getEscapingTemplates
     */
    public function testEscaping($template, $mustBeEscaped)
    {
        $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0));
        $twig->addExtension(new RoutingExtension($this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock()));

        $nodes = $twig->parse($twig->tokenize(new Source($template, '')));

        $this->assertSame($mustBeEscaped, $nodes->getNode('body')->getNode(0)->getNode('expr') instanceof FilterExpression);
    }

    public function getEscapingTemplates()
    {
        return array(
            array('{{ path("foo") }}', false),
            array('{{ path("foo", {}) }}', false),
            array('{{ path("foo", { foo: "foo" }) }}', false),
            array('{{ path("foo", foo) }}', true),
            array('{{ path("foo", { foo: foo }) }}', true),
            array('{{ path("foo", { foo: ["foo", "bar"] }) }}', true),
            array('{{ path("foo", { foo: "foo", bar: "bar" }) }}', true),

            array('{{ path(name = "foo", parameters = {}) }}', false),
            array('{{ path(name = "foo", parameters = { foo: "foo" }) }}', false),
            array('{{ path(name = "foo", parameters = foo) }}', true),
            array('{{ path(name = "foo", parameters = { foo: ["foo", "bar"] }) }}', true),
            array('{{ path(name = "foo", parameters = { foo: foo }) }}', true),
            array('{{ path(name = "foo", parameters = { foo: "foo", bar: "bar" }) }}', true),
        );
    }
}


text:
<ion-view cache-view="false">
    <ion-nav-bar class="bar-positive" align-title="center">
        <ion-nav-title style="font-size: 12px">
            {{(data.deviceStateChange.name + ': ' + data.deviceStateChange.state)}}
            Bike Speed & Distance & Cadence
        </ion-nav-title>
        <ion-nav-back-button>
        </ion-nav-back-button>
        <ion-nav-buttons side="right">
            <button class="button button-clear" ng-click="buttonListenClick()" ng-disabled="!data.selectedDevice.antDeviceNumber">
                Listen
                Stop
            </button>
        </ion-nav-buttons>
    </ion-nav-bar>

    <ion-tabs tabs-type="tabs-icon-only">
        <ion-tab title="Device List" icon-on="ion-ios-search-strong" icon-off="ion-ios-search">
            <ion-content class="padding" style="padding-top: 45px">
                <button class="button button-calm button-block button-small" ng-hide="spinner.show" ng-click="buttonStartSearchClick()">
                    Start search
                </button>
                <button class="button button-calm button-block button-small" ng-show="spinner.show" ng-click="buttonStopSearchClick()">
                    Stop search
                </button>

                        <ion-spinner icon="android"></ion-spinner>

                        <input type="radio" name="group" ng-model="data.selectedDevice" ng-value="dev">

                            {{dev.deviceDisplayName}} - {{dev.antDeviceType}}

            </ion-content>
        </ion-tab>

        <ion-tab title="Statistics" icon-on="ion-ios-list-outline" icon-off="ion-ios-list-outline">
            <ion-content class="padding" style="padding-top: 45px">

odML Data Checks

                        <ion-spinner icon="android" ng-if="data.subscribed"></ion-spinner>

{{section.name}}

                                     0">

            </ion-content>
        </ion-tab>

        <ion-tab title="Bike SD" icon-on="ion-ios-cloud-upload" icon-off="ion-ios-cloud-upload-outline">
            <ion-content style="padding-top: 50px" scroll="true">

Selected Experiment ID: {{global.selectedExperiment.experimentId}}

Selected Profile: {{global.selectedProfile.profileName}}

                        <button class="button button-block button-positive icon-right ion-ios-cloud-upload-outline" ng-click="uploadMeasurement()">
                            Upload Measurement to EEGBase
                        </button>
                        <ion-spinner icon="lines" ng-if="showUploadSpinner"></ion-spinner>

            </ion-content>
        </ion-tab>

    </ion-tabs>

</ion-view>


text:
package comeon.ui.preferences.wikis;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import comeon.ui.preferences.SubController;
import comeon.ui.preferences.main.PreferencesController;

import java.beans.PropertyChangeEvent;

@Singleton
public final class WikiSubController extends SubController<WikiModel, WikiSubPanel> {

    @Inject
    public WikiSubController(final PreferencesController mainController) {
        super(mainController);
    }

    @Override
    protected void registerViewInterval(final WikiSubPanel view) {
        view.getNameField().getDocument().addDocumentListener(new AbstractDocumentListener() {
            @Override
            protected void doUpdate(final String text) {
                getModel().setName(text);
            }
        });
        view.getUrlField().getDocument().addDocumentListener(new AbstractDocumentListener() {
            @Override
            protected void doUpdate(final String text) {
                getModel().setUrl(text);
            }
        });
        view.getDisplayNameField().getDocument().addDocumentListener(new AbstractDocumentListener() {
            @Override
            protected void doUpdate(final String text) {
                getModel().setDisplayName(text);
            }
        });
        view.getLoginField().getDocument().addDocumentListener(new AbstractDocumentListener() {
            @Override
            protected void doUpdate(final String text) {
                getModel().setLogin(text);
            }
        });
        view.getPasswordField().getDocument().addDocumentListener(new AbstractDocumentListener() {
            @Override
            protected void doUpdate(final String text) {
                getModel().setPassword(text);
            }
        });
    }

    @Override
    public void propertyChange(final PropertyChangeEvent evt) {
        // Noop
    }

    @Override
    protected void doCommit(final WikiModel source, final WikiModel target, final int index) {
        target.setName(source.getName());
        target.setUrl(source.getUrl());
        target.setDisplayName(source.getDisplayName());
        target.setLogin(source.getLogin());
        target.setPassword(source.getPassword());
        getMainController().update(target, index);
    }

    @Override
    protected void onModelChangedInternal(final WikiModel oldModel, final WikiModel newModel) {
        getView().getNameField().setText(newModel.getName());
        getView().getUrlField().setText(newModel.getUrl());
        getView().getDisplayNameField().setText(newModel.getDisplayName());
        getView().getLoginField().setText(newModel.getLogin());
        getView().getPasswordField().setText(newModel.getPassword());
    }

    @Override
    protected WikiModel makeNewModel() {
        return new WikiModel();
    }

    @Override
    protected void addModel(final WikiModel model) {
        getMainController().add(model);
    }

    @Override
    public void remove(final int index) {
        getMainController().removeWiki(index);
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Biatora trichogena Norman

### Remarks
null


text:
package com.dotsub.converter.importer.impl;

import com.dotsub.converter.exception.FileFormatException;
import com.dotsub.converter.importer.SubtitleImportHandler;
import com.dotsub.converter.model.Configuration;
import com.dotsub.converter.model.SubtitleItem;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.String.format;

/**
 * Created by: Brooks Lyrette
 * For: Dotsub LLC.
 * Date: 16-01-08.
 */
public class WebVttImportHandler implements SubtitleImportHandler {

    private static final Log log = LogFactory.getLog(WebVttImportHandler.class);
    private static final Pattern pattern =
            Pattern.compile(".*(\\d+):(\\d+):(\\d+).(\\d+).*-->.*(\\d+):(\\d+):(\\d+).(\\d+).*");
    private static final Pattern hourlessPattern =
            Pattern.compile(".*(\\d+):(\\d+).(\\d+).*-->.*(\\d+):(\\d+).(\\d+).*");

    @Override
    public String getFormatName() {
        return "WebVTT";
    }

    @Override
    public List<SubtitleItem> importFile(InputStream inputStream, Configuration configuration) throws IOException {
        Iterator lines = IOUtils.lineIterator(new InputStreamReader(inputStream, "UTF-8"));

        List<SubtitleItem> items = new ArrayList<>();
        int lineNumber = 0;

        while (lines.hasNext()) {
            String line = (String) lines.next();
            log.debug(line);
            lineNumber++;

            if (processHeader(lineNumber, line)) {
                continue;
            }
            //header is done including its terminator. first line is an cue ID or a time.
            Matcher matcher = pattern.matcher(line);
            Matcher hourLessMatcher = hourlessPattern.matcher(line);
            log.debug("Checking: " + line);
            if (!matcher.matches() && !hourLessMatcher.matches()) {
                //grab next line to see if it is the time this was just an ID
                line = (String) lines.next();
                lineNumber++;
                matcher = pattern.matcher(line);
                hourLessMatcher = hourlessPattern.matcher(line);
                if (!matcher.matches() && !hourLessMatcher.matches()) {
                    throw new FileFormatException("file does not match expected vtt format");
                }
            }
            log.debug(line);

            int start = 0;
            int end = 0;
            if (matcher.matches()) {
                start += (Integer.parseInt(matcher.group(1)) * 3600000);
                start += Integer.parseInt(matcher.group(2)) * 60000;
                start += Integer.parseInt(matcher.group(3)) * 1000;
                start += Integer.parseInt(matcher.group(4));
                end += (Integer.parseInt(matcher.group(5)) * 3600000);
                end += Integer.parseInt(matcher.group(6)) * 60000;
                end += Integer.parseInt(matcher.group(7)) * 1000;
                end += Integer.parseInt(matcher.group(8));
            }
            else {
                start += Integer.parseInt(hourLessMatcher.group(1)) * 60000;
                start += Integer.parseInt(hourLessMatcher.group(2)) * 1000;
                start += Integer.parseInt(hourLessMatcher.group(3));
                end += Integer.parseInt(hourLessMatcher.group(4)) * 60000;
                end += Integer.parseInt(hourLessMatcher.group(5)) * 1000;
                end += Integer.parseInt(hourLessMatcher.group(6));
            }
            int duration = end - start;
            String content;
            StringBuilder caption = new StringBuilder("");
            while (lines.hasNext() && (content = (String) lines.next()) != null && !content.trim().equals("")) {
                lineNumber++;
                content = content.trim();
                caption.append("\n");
                caption.append(content);
            }
            lineNumber++;
            //replace all non supported info
            String subtitleContent = caption.toString().replaceAll("<(.|\n)*?>", "");
            log.debug(
                    format("creating a new caption from: \t times:%d ms to %d ms  \t content: %s \t",
                            start, duration, subtitleContent));
            SubtitleItem item = new SubtitleItem(start, duration, subtitleContent);
            items.add(item);
        }
        return items;
    }

    private boolean processHeader(int lineNumber, String line) throws FileFormatException {
        //line 1 has to contain WEBVTT
        if (line.contains("WEBVTT") && lineNumber == 1) {
            return true;
        }
        else if (!line.contains("WEBVTT") && lineNumber == 1) {
            throw new FileFormatException("file does not match expected vtt format");
        }
        //Metadata is in the form of x: y . All of those can be ignored in our case.
        else if (line.matches("^[\\w]+:[^:]+")) {
            return true;
        }
        else if (line.equals("")) {
            return true;
        }
        return false;
    }
}


text:
cd "${0%/*}"

./tools/appify ./fez.sh FezDecrypter
cd ../
cp ./FezDecrypter/bin/Debug/FezDecrypter.exe ./Mac/FezDecrypter.app/Contents/MacOS/fezdecrypter.exe
cd ./Mac
./tools/setfileicon ./decrypter.icns ./FezDecrypter.app
echo Build succeeded.


text:
class O2ReplyServer;

/// Simple OAuth2 authenticator.
class O2: public QObject {
    Q_OBJECT
    Q_ENUMS(GrantFlow)

public:
    enum GrantFlow {GrantFlowAuthorizationCode, GrantFlowImplicit};

    /// Authorization flow: Authorization Code (default, see http://tools.ietf.org/html/draft-ietf-oauth-v2-15#section-4.1) or Implicit (see http://tools.ietf.org/html/draft-ietf-oauth-v2-15#section-4.2)
    Q_PROPERTY(GrantFlow grantFlow READ grantFlow WRITE setGrantFlow NOTIFY grantFlowChanged)
    GrantFlow grantFlow();
    void setGrantFlow(GrantFlow value);

    /// Are we authenticated?
    Q_PROPERTY(bool linked READ linked NOTIFY linkedChanged)
    bool linked();

    /// Extra tokens available after a successful OAuth exchange
    Q_PROPERTY(QMap extraTokens READ extraTokens)
    QVariantMap extraTokens() const;

    /// Authentication token.
    Q_PROPERTY(QString token READ token WRITE setToken NOTIFY tokenChanged)
    QString token();
    void setToken(const QString &v);

    /// Client ID.
    /// O2 instances with the same (client ID, client secret) share the same "linked" and "token" properties.
    Q_PROPERTY(QString clientId READ clientId WRITE setClientId NOTIFY clientIdChanged)
    QString clientId();
    void setClientId(const QString &value);

    /// Client secret.
    /// O2 instances with the same (client ID, client secret) share the same "linked" and "token" properties.
    Q_PROPERTY(QString clientSecret READ clientSecret WRITE setClientSecret NOTIFY clientSecretChanged)
    QString clientSecret();
    void setClientSecret(const QString &value);

    /// Scope of authentication.
    Q_PROPERTY(QString scope READ scope WRITE setScope NOTIFY scopeChanged)
    QString scope();
    void setScope(const QString &value);

    /// Request URL.
    Q_PROPERTY(QString requestUrl READ requestUrl WRITE setRequestUrl NOTIFY requestUrlChanged)
    QString requestUrl();
    void setRequestUrl(const QString &value);

    /// Token request URL.
    Q_PROPERTY(QString tokenUrl READ tokenUrl WRITE setTokenUrl NOTIFY tokenUrlChanged)
    QString tokenUrl();
    void setTokenUrl(const QString &value);

    /// Token refresh URL.
    Q_PROPERTY(QString refreshTokenUrl READ refreshTokenUrl WRITE setRefreshTokenUrl NOTIFY refreshTokenUrlChanged)
    QString refreshTokenUrl();
    void setRefreshTokenUrl(const QString &value);

    /// TCP port number to use in local redirections.
    /// The OAuth 2.0 "redirect_uri" will be set to "http://localhost:<localPort>/".
    /// If localPort is set to 0 (default), O2 will replace it with a free one.
    Q_PROPERTY(int localPort READ localPort WRITE setLocalPort NOTIFY localPortChanged)
    int localPort();
    void setLocalPort(int value);

public:
    /// Constructor.
    /// @param  parent  Parent object.
    explicit O2(QObject *parent = 0);

    /// Destructor.
    virtual ~O2();

    /// Get authentication code.
    QString code();

    /// Get refresh token.
    QString refreshToken();

    /// Get token expiration time (seconds from Epoch).
    int expires();

    /// Sets the storage object to use for storing the OAuth tokens on a peristent medium
    void setStore(O2AbstractStore *store);

public slots:
    /// Authenticate.
    Q_INVOKABLE virtual void link();

    /// De-authenticate.
    Q_INVOKABLE virtual void unlink();

    /// Refresh token.
    void refresh();

signals:
    /// Emitted when client needs to open a web browser window, with the given URL.
    void openBrowser(const QUrl &url);

    /// Emitted when client can close the browser window.
    void closeBrowser();

    /// Emitted when authentication/deauthentication succeeded.
    void linkingSucceeded();

    /// Emitted when authentication/deauthentication failed.
    void linkingFailed();

    /// Emitted when a token refresh has been completed or failed.
    void refreshFinished(QNetworkReply::NetworkError error);

    // Property change signals
    void grantFlowChanged();
    void linkedChanged();
    void tokenChanged();
    void clientIdChanged();
    void clientSecretChanged();
    void scopeChanged();
    void requestUrlChanged();
    void tokenUrlChanged();
    void refreshTokenUrlChanged();
    void localPortChanged();

protected slots:
    /// Handle verification response.
    virtual void onVerificationReceived(QMap<QString, QString>);

    /// Handle completion of a token request.
    virtual void onTokenReplyFinished();

    /// Handle failure of a token request.
    virtual void onTokenReplyError(QNetworkReply::NetworkError error);

    /// Handle completion of a refresh request.
    virtual void onRefreshFinished();

    /// Handle failure of a refresh request.
    virtual void onRefreshError(QNetworkReply::NetworkError error);

protected:
    /// Build HTTP request body.
    QByteArray buildRequestBody(const QMap<QString, QString> &parameters);

    /// Set authentication code.
    void setCode(const QString &v);

    /// Set refresh token.
    void setRefreshToken(const QString &v);

    /// Set token expiration time.
    void setExpires(int v);

    /// Set extra tokens found in OAuth response
    void setExtraTokens(QVariantMap extraTokens);

protected:
    QString clientId_;
    QString clientSecret_;
    QString scope_;
    QString code_;
    QString redirectUri_;
    QUrl requestUrl_;
    QUrl tokenUrl_;
    QUrl refreshTokenUrl_;
    QNetworkAccessManager *manager_;
    O2ReplyServer *replyServer_;
    O2ReplyList timedReplies_;
    quint16 localPort_;
    GrantFlow grantFlow_;
    O2AbstractStore *store_;
    QVariantMap extraTokens_;
};

#endif // O2_H


text:
package io.netty.util;

import java.util.concurrent.TimeUnit;

/**
 * A task which is executed after the delay specified with
 * {@link Timer#newTimeout(TimerTask, long, TimeUnit)}.
 */
public interface TimerTask {

    /**
     * Executed after the delay specified with
     * {@link Timer#newTimeout(TimerTask, long, TimeUnit)}.
     *
     * @param timeout a handle which is associated with this task
     */
    void run(Timeout timeout) throws Exception;
}


text:
require 'spec_helper'

describe 'openldap::server::access' do

  let(:title) { 'foo' }

  let :pre_condition do
    "class {'openldap::server':}"
  end

  on_supported_os.each do |os, facts|
    context "on #{os}" do
      let(:facts) do
        facts
      end

      context 'when Class[openldap::server] is not declared' do
        let(:pre_condition) { }
        it { expect { is_expected.to compile }.to raise_error(/class ::openldap::server has not been evaluated/) }
      end

      context 'with composite namevar' do
        let(:title) {
          'to attrs=userPassword,shadowLastChange by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com'
        }
        it { is_expected.to compile.with_all_deps }
        it {
          is_expected.to contain_openldap_access('to attrs=userPassword,shadowLastChange by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com')
        }
      end

      context 'with composite namevar, what includes dn and filter' do
        let(:title) {
          'to dn.one="ou=users,dc=example,dc=com" filter=(objectClass=person) by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com'
        }
        it { is_expected.to compile.with_all_deps }
        it {
          is_expected.to contain_openldap_access('to dn.one="ou=users,dc=example,dc=com" filter=(objectClass=person) by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com')
        }
      end

      context 'with composite namevar, what includes dn and attrs' do
        let(:title) {
          'to dn.one="ou=users,dc=example,dc=com" attrs=userPassword,shadowLastChange by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com'
        }
        it { is_expected.to compile.with_all_deps }
        it {
          is_expected.to contain_openldap_access('to dn.one="ou=users,dc=example,dc=com" attrs=userPassword,shadowLastChange by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com')
        }
      end

      context 'with composite namevar, what includes dn, filter and attrs' do
        let(:title) {
          'to dn.one="ou=users,dc=example,dc=com" filter=(objectClass=person) attrs=userPassword,shadowLastChange by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com'
        }
        it { is_expected.to compile.with_all_deps }
        it {
          is_expected.to contain_openldap_access('to dn.one="ou=users,dc=example,dc=com" filter=(objectClass=person) attrs=userPassword,shadowLastChange by dn="cn=admin,dc=example,dc=com" on dc=example,dc=com')
        }
      end
    end
  end
end


text:
using System.Collections.Generic;
using TechTalk.SpecFlow;

namespace Specs.Steps
{
    public class State
    {
        public static dynamic OriginalInstance
        {
            get
            {
                return ScenarioContext.Current["OrginalInstance"];
            }
            set
            {
                ScenarioContext.Current.Add("OrginalInstance", value);
            }
        }

        public static IList<dynamic> OriginalSet
        {
            get
            {
                return ScenarioContext.Current["OrginalSet"] as IList<dynamic>;
            }
            set
            {
                ScenarioContext.Current.Add("OrginalSet", value);
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using NPoco;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;

namespace Umbraco.Cms.Infrastructure.Persistence.Dtos
{
    [TableName(TableName)]
    [PrimaryKey("pk")]
    [ExplicitColumns]
    public class DictionaryDto  // public as required to be accessible from Deploy for the RepairDictionaryIdsWorkItem.
    {
        public const string TableName = Cms.Core.Constants.DatabaseSchema.Tables.DictionaryEntry;

        [Column("pk")]
        [PrimaryKeyColumn]
        public int PrimaryKey { get; set; }

        [Column("id")]
        [Index(IndexTypes.UniqueNonClustered)]
        public Guid UniqueId { get; set; }

        [Column("parent")]
        [NullSetting(NullSetting = NullSettings.Null)]
        [ForeignKey(typeof(DictionaryDto), Column = "id")]
        [Index(IndexTypes.NonClustered, Name = "IX_" + TableName + "_Parent")]
        public Guid? Parent { get; set; }

        [Column("key")]
        [Length(450)]
        [Index(IndexTypes.UniqueNonClustered, Name = "IX_" + TableName + "_key")]
        public string Key { get; set; } = null!;

        [ResultColumn]
        [Reference(ReferenceType.Many, ColumnName = "UniqueId", ReferenceMemberName = "UniqueId")]
        public List<LanguageTextDto>? LanguageTextDtos { get; set; }
    }
}


text:
<?php

/**
 * @file
 * Contains \Docker\Drupal\Command\NginxSetHostCommand.
 */

namespace Docker\Drupal\Command\Nginx;

use Docker\Drupal\Application;
use Docker\Drupal\Extension\ApplicationConfigExtension;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Docker\Drupal\Style\DruDockStyle;
use Docker\Drupal\Extension\ApplicationContainerExtension;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Filesystem\Filesystem;
use Alchemy\Zippy\Zippy;
use GuzzleHttp\Client;

/**
 * Class NginxSetHostCommand
 *
 * @package Docker\Drupal\Command\Nginx
 */
class NginxSetHostCommand extends Command {

  protected function configure() {
    $this
      ->setName('nginx:sethost')
      ->setDescription('Add nginx host to DD and host OS')
      ->setHelp("This command will add a host server_name & reload NGINX config.");
  }

  protected function execute(InputInterface $input, OutputInterface $output) {
    $application = new Application();
    $cta = new ApplicationContainerExtension();
    $cfa = new ApplicationConfigExtension();

    $io = new DruDockStyle($input, $output);
    $io->section("Nginx ::: add host");

    if ($config = $application->getAppConfig($io)) {
      $appname = $config['appname'];
      $apphost = $config['host'];
    }
    $system_appname = isset($appname) ? strtolower(str_replace(' ', '', $appname)) : 'app';

    if (!isset($apphost)) {
      $apphost = 'drudock.localhost';
    }

    $currenthost = $apphost;
    $helper = $this->getHelper('question');
    $question = new Question('Please enter new hostname : [' . $currenthost . '] ', $currenthost);
    $newhost = $helper->ask($input, $output, $question);

    if ($application->getOs() == 'Darwin') {
      $cfa->setHostConfig($newhost, $io, $system_appname);
    }

    if (file_exists('.config.yml')) {
      // Update app config.yaml.
      $config = Yaml::parse(file_get_contents('.config.yml'));
      $config['host'] = $newhost;
      $yaml = Yaml::dump($config);
      file_put_contents('.config.yml', $yaml);
      // Update docker-compose.yaml file.
      $base_yaml = file_get_contents('./docker_' . $system_appname . '/docker-compose.yml');
      $base_compose = Yaml::parse($base_yaml);
      $base_compose['services']['nginx']['environment']['VIRTUAL_HOST'] = $config['host'];
      $app_yaml = Yaml::dump($base_compose, 8, 2);
      $application->renderFile('./docker_' . $system_appname . '/docker-compose.yml', $app_yaml);
    }
    else {
      $io->error('You\'re not currently in an APP directory. APP .config.yml not found.');
      exit;
    }

    if (file_exists('./app/www/sites/default/drushrc.php')) {
      $drushrc = file_get_contents('./app/www/sites/default/drushrc.php');
      $newhosts = explode(' ', $newhost);
      $newhost = $newhosts[0];
      $currenthosts = explode(' ', $currenthost);
      $host = $currenthosts[0];
      $drushrc = str_replace($host, $newhost, $drushrc);
      file_put_contents('./app/www/sites/default/drushrc.php', $drushrc);
    }

    $application->setNginxHost($io);

    if ($cta->checkForAppContainers($appname, $io)) {
      $command = $cta->getComposePath($appname, $io) . 'exec -T nginx nginx -s reload 2>&1';
      $application->runcommand($command, $io);
    }
  }
}


text:
:mod:`sms`
==========

.. module:: king_phisher.sms
   :synopsis:

This module provides functionality for sending free SMS messages by emailing a
carriers SMS gateway.

Data
----

.. autodata:: CARRIERS
   :annotation:

.. autodata:: DEFAULT_FROM_ADDRESS
   :annotation:

Functions
---------

.. autofunction:: get_smtp_servers(domain)

.. autofunction:: lookup_carrier_gateway

.. autofunction:: send_sms


text:
module TestLib
    #http://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby
  def integer?(value)
    [                          # In descending order of likeliness:
      /^[-+]?[1-9]([0-9]*)?$/, # decimal
      /^0[0-7]+$/,             # octal
      /^0x[0-9A-Fa-f]+$/,      # hexadecimal
      /^0b[01]+$/              # binary
    ].each do |match_pattern|
      return true if value =~ match_pattern
    end
    return false
  end
  def do_input_checks(min_port,max_port)
    do_min_port_check(min_port)
    do_max_port_check(min_port,max_port)
  end

  def do_min_port_check(min_port)
    puts "min_port"
    raise "min_port is not an integer" unless integer?(min_port)
    raise "min_port has to be larger then 1024" unless min_port.to_i >= 1024
  end

  def do_max_port_check(min_port,max_port)
    raise "max_port is not an integer" unless integer?(max_port)
    raise "max_port can not exceed 65535" unless max_port.to_i <= 65535
    if (max_port.to_i - min_port.to_i) < 1 then
      raise "there should be at least one port in the min/max port range"
    end
  end
end


text:
from django.conf.urls import patterns, url

urlpatterns = patterns(
    'mosaic.views',

    url(r'^mosaic/$', 'mosaic_list', name='mosaic_list'),
    url(r'^mosaic/(?P<mosaic_id>.*)/$', 'mosaic_detail', name='mosaic_detail'),

    url(r'^$', 'index', name='index'),

)


text:
struct Button
{

	Button(Ogre::Real x, Ogre::Real y, const Ogre::String& text, Gorilla::Layer* layer)
		: hovered(false)
	{
		caption = layer->createCaption(14, x,y, text);
		caption->size(64,25);
		caption->align(Gorilla::TextAlign_Centre);
		caption->vertical_align(Gorilla::VerticalAlign_Middle);
		caption->background(Gorilla::rgb(255,255,255,32));
	}

	bool isOver(const Ogre::Vector2& pos)
	{
		bool result = caption->intersects(pos);
		if (result && !hovered)
			caption->background(Gorilla::rgb(255,255,255,128));
		else if (!result && hovered)
			caption->background(Gorilla::rgb(255,255,255,32));
		hovered = result;
		return result;
	}

	bool                 hovered;
	Gorilla::Caption*    caption;

};

struct D3Panel
{

	D3Panel(Gorilla::Silverback* silverback, Ogre::SceneManager* sceneMgr, const Ogre::Vector2& size)
		: mSize(size)
	{

		mScreen = silverback->createScreenRenderable(Ogre::Vector2(mSize.x,mSize.y), "dejavu");
		mNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
		mNode->attachObject(mScreen);

		mGUILayer = mScreen->createLayer(0);
		mBackground = mGUILayer->createRectangle(0,0, mSize.x * 100, mSize.y * 100);
		mBackground->background_gradient(Gorilla::Gradient_NorthSouth, Gorilla::rgb(94,97,255,5), Gorilla::rgb(94,97,255,50));
		mBackground->border(2, Gorilla::rgb(255,255,255,150));

		mMousePointerLayer = mScreen->createLayer(15);
		mMousePointer = mMousePointerLayer->createRectangle(0,0,10,18);
		mMousePointer->background_image("mousepointer");

	}

	~D3Panel()
	{
		mScreen->destroy(mGUILayer);
		mScreen->destroy(mMousePointerLayer);
	}

	Button* check(const Ogre::Ray& ray, bool& isOver)
	{

		isOver = false;

		Ogre::Matrix4 transform;
		transform.makeTransform(mNode->getPosition(), mNode->getScale(), mNode->getOrientation());

		Ogre::AxisAlignedBox aabb = mScreen->getBoundingBox();
		aabb.transform(transform);
		std::pair<bool, Ogre::Real> result = Ogre::Math::intersects(ray, aabb);

		if (result.first == false)
			return 0;

		Ogre::Vector3 a,b,c,d;
		Ogre::Vector2 halfSize = mSize * 0.5f;
		a = transform * Ogre::Vector3(-halfSize.x,-halfSize.y,0);
		b = transform * Ogre::Vector3( halfSize.x,-halfSize.y,0);
		c = transform * Ogre::Vector3(-halfSize.x, halfSize.y,0);
		d = transform * Ogre::Vector3( halfSize.x, halfSize.y,0);

		result = Ogre::Math::intersects(ray, c, b, a);
		if (result.first == false)
			result = Ogre::Math::intersects(ray, c, d, b);
		if (result.first == false)
			return 0;

		if (result.second > 6.0f)
			return 0;

		isOver = true;

		Ogre::Vector3 hitPos = ( ray.getOrigin() + (ray.getDirection() * result.second) );
		Ogre::Vector3 localPos = transform.inverse() * hitPos;
		localPos.x += halfSize.x;
		localPos.y -= halfSize.y;
		localPos.x *= 100;
		localPos.y *= 100;

		// Cursor clip
		localPos.x = Ogre::Math::Clamp<Ogre::Real>(localPos.x, 0, (mSize.x * 100) - 10);
		localPos.y = Ogre::Math::Clamp<Ogre::Real>(-localPos.y, 0, (mSize.y * 100) - 18);

		mMousePointer->position(localPos.x, localPos.y);

		for (size_t i=0;i < mButtons.size();i++)
		{
			if (mButtons[i]->isOver(mMousePointer->position()))
				return mButtons[i];
		}

		return 0;
	}

	Gorilla::Caption* makeCaption(Ogre::Real x, Ogre::Real y, const Ogre::String& text)
	{
		return mGUILayer->createCaption(14, x, y, text);
	}

	Button* makeButton(Ogre::Real x, Ogre::Real y, const Ogre::String& text)
	{
		Button* button = new Button(x,y, text, mGUILayer);
		mButtons.push_back(button);
		return button;
	}

	Gorilla::ScreenRenderable*     mScreen;
	Ogre::SceneNode*     mNode;
	Gorilla::Layer*      mGUILayer, *mMousePointerLayer;
	Gorilla::Rectangle*  mBackground, *mMousePointer;
	Ogre::Vector2        mSize;

	std::vector<Button*> mButtons;

};

class FPSCameraController;

class Gorilla3DSequence : public BaseSequence {
public:
	typedef BaseSequence Parent;

public:
	Gorilla3DSequence();
	virtual ~Gorilla3DSequence();

	void setUp();

	void createHUD();
	void createControlPanel();

	virtual bool frameStarted(const Ogre::FrameEvent& evt);

	virtual bool mouseMoved( const OIS::MouseEvent &arg );

	virtual bool keyPressed(const OIS::KeyEvent &e);
	virtual bool keyReleased(const OIS::KeyEvent &e);

private:
	Ogre::Real              mTimer, mTimer2;
	D3Panel*                mPowerPanel;
	Gorilla::Rectangle*     mPowerValue, *mPowerValueBackground;
	Button*                 mPowerUpButton;
	Button*                 mPowerDownButton;
	Ogre::Real              mBasePower;
	Ogre::SceneNode*        mNode;

	Ogre::Real              mNextUpdate;
	Ogre::ManualObject*     mReferenceObject;

	Ogre::Vector3 body_position_;
	std::unique_ptr<FPSCameraController> cam_controller_;
};


text:
<?php

namespace Sylius\Bundle\ProductBundle\Controller;

use Doctrine\Common\Persistence\ObjectRepository;
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Variation\Generator\VariantGeneratorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Variant controller.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
 */
class VariantController extends ResourceController
{
    /**
     * Generate all possible variants for given product id.
     */
    public function generateAction(Request $request)
    {
        if (null === $productId = $request->get('productId')) {
            throw new NotFoundHttpException('No product given.');
        }

        $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);

        $product = $this->findProductOr404($productId);
        $this->getGenerator()->generate($product);

        $manager = $this->container->get('sylius.manager.product');
        $manager->persist($product);
        $manager->flush();

        $this->flashHelper->addSuccessFlash($configuration, 'generate');

        return $this->redirectHandler->redirectToResource($configuration, $product);
    }

    /**
     * Get variant generator.
     *
     * @return VariantGeneratorInterface
     */
    protected function getGenerator()
    {
        return $this->container->get('sylius.generator.product_variant');
    }

    /**
     * Get product repository.
     *
     * @return ObjectRepository
     */
    protected function getProductRepository()
    {
        return $this->container->get('sylius.repository.product');
    }

    /**
     * Get product or 404.
     *
     * @param int $id
     *
     * @return ProductInterface
     *
     * @throws NotFoundHttpException
     */
    protected function findProductOr404($id)
    {
        if (!$product = $this->getProductRepository()->find($id)) {
            throw new NotFoundHttpException('Requested product does not exist.');
        }

        return $product;
    }
}


text:
package org.switchyard.config.model.composite;

import org.switchyard.config.model.TypedModel;
import org.switchyard.config.model.composer.ContextMapperModel;
import org.switchyard.config.model.composer.MessageComposerModel;
import org.switchyard.config.model.selector.OperationSelectorModel;

/**
 * The "binding" configuration model.
 *
 * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc.
 */
public interface BindingModel extends TypedModel {

    /** The "binding" name. */
    public static final String BINDING = "binding";

    /**
     * Gets the name attribute of this Model (not the name of the wrapped Configuration).
     * @return the name
     */
    public String getName();

    /**
     * Sets the name attribute of this Model (not the name of the wrapped Configuration).
     * @param name the name
     * @return this BindingModel (useful for chaining)
     */
    public BindingModel setName(String name);

    /**
     * Gets the parent service model.  This method will return null if
     * the binding model is attached to a reference instead of a service.
     * @return the parent composite model
     */
    public CompositeServiceModel getService();

    /**
     * Gets the parent reference model.  This method will return null if
     * the binding model is attached to a service instead of a reference.
     * @return the parent composite model
     */
    public CompositeReferenceModel getReference();

    /**
     * Is this binding attached to a service?
     * @return true if this is a service binding, false if it's a reference binding.
     */
    public boolean isServiceBinding();

    /**
     * Is this binding attached to a reference?
     * @return true if this is a reference binding, false if it's a service binding.
     */
    public boolean isReferenceBinding();

    /**
     * Gets the child operation selector model.
     * @return the child operation selector model
     */
    public OperationSelectorModel getOperationSelector();

    /**
     * Sets the child operation selector model.
     * @param model the child operation selector model
     * @return this model(useful for chaining)
     */
    public BindingModel setOperationSelector(OperationSelectorModel model);

    /**
     * Gets the child context mapper model.
     * @return the child context mapper model
     */
    public ContextMapperModel getContextMapper();

    /**
     * Gets the child message composer model.
     * @return the child message composer model
     */
    public MessageComposerModel getMessageComposer();

    /**
     * Sets the child context mapper model.
     * @param model the context mapper model to set
     * @return this BindingModel (useful for chaining)
     */
    public BindingModel setContextMapper(ContextMapperModel model);

    /**
     * Sets the child message composer model.
     * @param model the message composer model to set
     * @return this BindingModel (useful for chaining)
     */
    public BindingModel setMessageComposer(MessageComposerModel model);
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Senparc.Weixin.HttpUtility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

#if NET462
using System.Web;
#else
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
#endif

namespace Senparc.Weixin.HttpUtility.Tests
{
    [TestClass()]
    public class UrlUtilityTests
    {
        [TestMethod()]
        public void GenerateOAuthCallbackUrlTest()
        {
#if NET462
            Func<string, string, string, HttpContextBase> getHttpContextBase = (url, queryString, baseUrl) =>
             {
                 var context = new Mock<HttpContextBase>();
                 var request = new Mock<HttpRequestBase>();
                 var response = new Mock<HttpResponseBase>();

                 request.Setup(r => r.Url).Returns(new Uri(url));
                 request.Setup(r => r.ApplicationPath).Returns(baseUrl);

                 context.Setup(c => c.Request).Returns(request.Object);
                 context.Setup(c => c.Response).Returns(response.Object);
                 context.Setup(c => c.Response).Returns(response.Object);
                 return context.Object;

                 var httpContext = new HttpContext(new HttpRequest("Senparc", url, queryString), new HttpResponse(null));
                 var httpContextBase = new HttpContextWrapper(httpContext);

                 return httpContextBase;
             };
#else
            Func<string, string, string, HttpContext> getHttpContextBase = (url, queryString, baseUrl) =>
             {
                 var uri = new Uri(url);

                 var scheme = uri.Scheme;
                 var path = uri.LocalPath;

                 var httpContext = new DefaultHttpContext();
                 httpContext.Request.Path = path;
                 httpContext.Request.Host = new HostString(uri.Host, uri.Port);
                 httpContext.Request.Scheme = scheme;
                 httpContext.Request.QueryString = new QueryString(uri.Query);
                 httpContext.Request.PathBase = baseUrl;
                 return httpContext;
             };
#endif

            string virtualPath = null;//虚拟路径

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index", "", virtualPath);
                var callbackUrl = Senparc.Weixin.AspNetHttpUtility.UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n普通 HTTP Url:" + callbackUrl);
                Assert.AreEqual(
    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex",
    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = Senparc.Weixin.AspNetHttpUtility.UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数 HTTP Url:" + callbackUrl);
                Assert.AreEqual(
    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:8080/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = Senparc.Weixin.AspNetHttpUtility.UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数、带端口 HTTP Url:" + callbackUrl);
                Assert.AreEqual(
    "https://sdk.weixin.senparc.com:8080/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%3a8080%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index", "", virtualPath);
                var callbackUrl = Senparc.Weixin.AspNetHttpUtility.UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n普通 HTTPS Url:" + callbackUrl);
                Assert.AreEqual(
    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex",
    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = Senparc.Weixin.AspNetHttpUtility.UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数 HTTPS Url:" + callbackUrl);
                Assert.AreEqual(
    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:1433/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = Senparc.Weixin.AspNetHttpUtility.UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数、带端口 HTTPS Url:" + callbackUrl);
                Assert.AreEqual(
    "https://sdk.weixin.senparc.com:1433/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
    callbackUrl, true);
            }

            //虚拟路径
            {
                virtualPath = "/VirtualPath";
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:1433/VirtualPath/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                //Console.WriteLine("\r\nhttpContext.Request.AbsoluteUri():"+httpContext.Request.AbsoluteUri());
                var callbackUrl = Senparc.Weixin.AspNetHttpUtility.UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数、带端口 HTTPS Url:" + callbackUrl);

#if NET462
                var expectedUrl = "https://sdk.weixin.senparc.com:1433/VirtualPath/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fVirtualPath%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1";
#else
                //.NET Standard(.NET Core)下因为模拟会存在偏差(无法自动识别Url中的VirtualPath为特殊的虚拟目录,所以会出现重复),因此以下结果是可以接受的
                var expectedUrl = "https://sdk.weixin.senparc.com:1433/VirtualPath/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fVirtualPath%2fVirtualPath%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1";
#endif
                Assert.AreEqual(expectedUrl, callbackUrl, true);
            }
        }
    }
}


text:
///////////////////////////////////////////////////////////////////////////////
//
//  Plain calculator example demonstrating the grammar. The parser is a
//  syntax checker only and does not do any semantic evaluation.
//
//  [ JDG May 10, 2002 ]        spirit1
//  [ JDG March 4, 2007 ]       spirit2
//  [ HK November 30, 2010 ]    spirit2/utree
//
///////////////////////////////////////////////////////////////////////////////

// #define BOOST_SPIRIT_DEBUG

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_utree.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>

#include <iostream>
#include <string>

#if BOOST_PHOENIX_VERSION == 0x2000
namespace boost { namespace phoenix
{
    // There's a bug in the Phoenix V2 type deduction mechanism that prevents
    // correct return type deduction for the math operations below. Newer
    // versions of Phoenix will be switching to BOOST_TYPEOF. In the meantime,
    // we will use the specializations helping with return type deduction
    // below:
    template <>
    struct result_of_plus<spirit::utree&, spirit::utree&>
    {
        typedef spirit::utree type;
    };

    template <>
    struct result_of_minus<spirit::utree&, spirit::utree&>
    {
        typedef spirit::utree type;
    };

    template <>
    struct result_of_multiplies<spirit::utree&, spirit::utree&>
    {
        typedef spirit::utree type;
    };

    template <>
    struct result_of_divides<spirit::utree&, spirit::utree&>
    {
        typedef spirit::utree type;
    };

    template <>
    struct result_of_negate<spirit::utree&>
    {
        typedef spirit::utree type;
    };
}}
#endif

namespace client
{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;
    namespace spirit = boost::spirit;

    ///////////////////////////////////////////////////////////////////////////////
    //  Our calculator grammar
    ///////////////////////////////////////////////////////////////////////////////
    template <typename Iterator>
    struct calculator : qi::grammar<Iterator, ascii::space_type, spirit::utree()>
    {
        calculator() : calculator::base_type(expression)
        {
            using qi::uint_;
            using qi::_val;
            using qi::_1;

            expression =
                term                            [_val = _1]
                >> *(   ('+' >> term            [_val = _val + _1])
                    |   ('-' >> term            [_val = _val - _1])
                    )
                ;

            term =
                factor                          [_val = _1]
                >> *(   ('*' >> factor          [_val = _val * _1])
                    |   ('/' >> factor          [_val = _val / _1])
                    )
                ;

            factor =
                uint_                           [_val = _1]
                |   '(' >> expression           [_val = _1] >> ')'
                |   ('-' >> factor              [_val = -_1])
                |   ('+' >> factor              [_val = _1])
                ;

            BOOST_SPIRIT_DEBUG_NODE(expression);
            BOOST_SPIRIT_DEBUG_NODE(term);
            BOOST_SPIRIT_DEBUG_NODE(factor);
        }

        qi::rule<Iterator, ascii::space_type, spirit::utree()> expression, term, factor;
    };
}

///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Expression parser...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Type an expression...or [q or Q] to quit\n\n";

    using boost::spirit::ascii::space;
    using boost::spirit::utree;
    typedef std::string::const_iterator iterator_type;
    typedef client::calculator<iterator_type> calculator;

    calculator calc; // Our grammar

    std::string str;
    while (std::getline(std::cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        std::string::const_iterator iter = str.begin();
        std::string::const_iterator end = str.end();
        utree ut;
        bool r = phrase_parse(iter, end, calc, space, ut);

        if (r && iter == end)
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded: " << ut << "\n";
            std::cout << "-------------------------\n";
        }
        else
        {
            std::string rest(iter, end);
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "stopped at: \": " << rest << "\"\n";
            std::cout << "-------------------------\n";
        }
    }

    std::cout << "Bye... :-) \n\n";
    return 0;
}


text:
package com.gemstone.gemfire.internal.shared;

import java.io.Closeable;
import java.nio.channels.Channel;

/**
 * Common base methods for {@link Channel} read/write operations (usually buffered).
 */
public interface StreamChannel extends Channel, Closeable {

  /**
   * Return the thread if waiting for read/write on this channel.
   */
  Thread getParkedThread();

  /**
   * Set the thread waiting for read/write on this channel (null to clear).
   */
  void setParkedThread(Thread thread);

  /**
   * Maximum time to wait before giving up read/write on channel
   */
  long getParkNanosMax();
}


text:
trait BufferMut {}
struct Ctx<D>(D);

trait BufferUdpStateContext<B> {}
impl<B: BufferMut, C> BufferUdpStateContext<B> for C {}

trait StackContext
where
    Ctx<()>: for<'a> BufferUdpStateContext<&'a ()>,
{
    type Dispatcher;
}

trait TimerContext {
    type Handler;
}
impl<C> TimerContext for C
where
    C: StackContext,
    //~^ ERROR: is not satisfied [E0277]
{
    type Handler = Ctx<C::Dispatcher>;
    //~^ ERROR: is not satisfied [E0277]
}

struct EthernetWorker<C>(C)
where
    Ctx<()>: for<'a> BufferUdpStateContext<&'a ()>;
impl<C> EthernetWorker<C> {}
//~^ ERROR: is not satisfied [E0277]

fn main() {}


text:
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.

#ifndef GLES2_RENDERER_MATERIAL_H
#define GLES2_RENDERER_MATERIAL_H

#include <RendererConfig.h>

#if defined(RENDERER_ENABLE_GLES2)

#include <RendererMaterial.h>
#include "GLES2Renderer.h"

#if defined(RENDERER_ANDROID)
#include "android/AndroidSamplePlatform.h"
#elif defined(RENDERER_IOS)
#include "ios/IosSamplePlatform.h"
#endif

#include <set>

#include <set>

namespace SampleRenderer
{

class GLES2RendererMaterial : public RendererMaterial
{
	public:
		GLES2RendererMaterial(GLES2Renderer &renderer, const RendererMaterialDesc &desc);
		virtual ~GLES2RendererMaterial(void);
		virtual void setModelMatrix(const float *matrix)
		{
			PX_FORCE_PARAMETER_REFERENCE(matrix);
			PX_ALWAYS_ASSERT();
		}
		virtual const Renderer& getRenderer() const { return m_renderer; }

		/* Actually executes glUniform* and submits data saved in the m_program[m_currentPass].vsUniformsVec4/psUniformsVec4 */
		void submitUniforms();

	private:
		virtual void bind(RendererMaterial::Pass pass, RendererMaterialInstance *materialInstance, bool instanced) const;
		virtual void bindMeshState(bool instanced) const;
		virtual void unbind(void) const;
		virtual void bindVariable(Pass pass, const Variable &variable, const void *data) const;

        VariableType 	GLTypetoVariableType(GLenum type);
		GLint			getAttribLocation(size_t usage, size_t index, Pass pass);
		std::string 	mojoSampleNameToOriginal(Pass pass, const std::string& name);

	private:
		GLES2RendererMaterial &operator=(const GLES2RendererMaterial&) { return *this; }

	private:
        void loadCustomConstants(Pass pass);

        friend class GLES2Renderer;
        friend class GLES2RendererVertexBuffer;
        friend class GLES2RendererDirectionalLight;
        GLES2Renderer &m_renderer;

		GLenum       m_glAlphaTestFunc;

		mutable struct shaderProgram {
			GLuint      vertexShader;
			GLuint      fragmentShader;
			GLuint      program;

			GLint       modelMatrixUniform;
			GLint       viewMatrixUniform;
			GLint       projMatrixUniform;
			GLint       modelViewMatrixUniform;
			GLint       boneMatricesUniform;
			GLint		modelViewProjMatrixUniform;

			GLint       positionAttr;
			GLint       colorAttr;
			GLint       normalAttr;
			GLint       tangentAttr;
			GLint       boneIndexAttr;
			GLint       boneWeightAttr;

			GLint       texcoordAttr[8];

			mutable std::set<std::string>	vsUniformsCollected;
			mutable std::set<std::string>	psUniformsCollected;

			size_t		vsUniformsTotal;
			size_t		psUniformsTotal;

			char*		vsUniformsVec4;
			GLuint		vsUniformsVec4Location;
			size_t		vsUniformsVec4Size;
			size_t		vsUniformsVec4SizeInBytes;
			char*		psUniformsVec4;
			GLuint		psUniformsVec4Location;
			size_t		psUniformsVec4Size;
			size_t		psUniformsVec4SizeInBytes;

			mojoResult* vertexMojoResult;
			mojoResult* fragmentMojoResult;

			shaderProgram();
			~shaderProgram();
		}	m_program[NUM_PASSES];

		mutable Pass	m_currentPass;
};

}

#endif // #if defined(RENDERER_ENABLE_GLES2)
#endif


text:
fpsgame
====

A simple FPS fight game based on 0 A.D..which is an open-source game engine and a free software also.You can get more information on this [link](https://play0ad.com/).


text:
<?php

namespace Payroll\Model;

/*
Classes imported via namespace to implement an InputFilter
for our model.
*/
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

/*
This class represent the blueprint for each location object in our application.
It outlines the properties associated with a location as well as an input filter
used to validate data in the data array.
*/
class Location implements InputFilterAwareInterface
{
  public $locationId;
  public $locationName;
  protected $inputFilter;

  /*
   In order to work with Zend\Db's TableGateway class, we need to implement the exchangeArray() method.
   This method simply copies the data from the passed in array to our entity's properties.
  */
  public function exchangeArray($data)
  {
    $this->locationId = (!empty($data['location_id'])) ? $data['location_id'] : null;
    $this->locationName = (!empty($data['location_name'])) ? $data['location_name'] : null;
  }

  /*
  Objects must implement either the exchangeArray() or populate() methods to support hydration
  (putting data array into class properties), and the getArrayCopy() method to support extraction
  (take data out of data array).
  */
  public function getArrayCopy()
  {
    return get_object_vars($this);
  }

  /*
  Though we don't actually use this method it must be implemented by virtue of the interface-->InputFilterAwareInterface.
  */
  public function setInputFilter(InputFilterInterface $inputFilter)
  {
    throw new \Exception("Not used");
  }

  /*
  Sets up our method to filter the data from the forms that will be stored in our
  models.
  */
  public function getInputFilter()
  {
    if (!$this->inputFilter) {
      $inputFilter = new InputFilter();

      $inputFilter->add(array(
        'name' => 'location_id',
        'required' => true,
        'filters' => array(
          array('name' => 'Int'),
        ),
      ));

      $inputFilter->add(array(
        'name' => 'location_name',
        'required' => true,
        'filters' => array(
          array('name' => 'StripTags'),
          array('name' => 'StringTrim'),
        ),
        'validators' => array(
          array(
            'name' => 'Regex',
            'options' => array(
              'pattern' => '/^[A-Za-z]+(\s*|\s+[0-9]*|\s+[A-Za-z]*|[A-Za-z\s]*)$/',
              'setMessage' => 'invalid name no special characters allowed or numbers attached to words.',
            ),
          ),

          array(
            'name' => 'StringLength',
            'options' => array(
              'encoding' => 'UTF-8',
              'min' => 1,
              'max' => 100,
            ),
          ),
        ),
      ));

      $this->inputFilter = $inputFilter;
    }

    return $this->inputFilter;
  }
}


text:
package org.jkiss.dbeaver.ext.generic.edit;

import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.ext.generic.model.GenericTable;
import org.jkiss.dbeaver.ext.generic.model.GenericTableColumn;
import org.jkiss.dbeaver.ext.generic.model.GenericTableIndex;
import org.jkiss.dbeaver.ext.generic.model.GenericTableIndexColumn;
import org.jkiss.dbeaver.model.edit.DBECommandContext;
import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer;
import org.jkiss.dbeaver.model.impl.DBSObjectCache;
import org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLIndexManager;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSEntityAttribute;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.rdb.DBSIndexType;
import org.jkiss.dbeaver.ui.UITask;
import org.jkiss.dbeaver.ui.editors.object.struct.EditIndexPage;
import org.jkiss.utils.CommonUtils;

import java.util.Collections;
import java.util.Map;

/**
 * Generic index manager
 */
public class GenericIndexManager extends SQLIndexManager<GenericTableIndex, GenericTable> {

    @Nullable
    @Override
    public DBSObjectCache<? extends DBSObject, GenericTableIndex> getObjectsCache(GenericTableIndex object)
    {
        return object.getTable().getContainer().getIndexCache();
    }

    @Override
    protected GenericTableIndex createDatabaseObject(
        DBRProgressMonitor monitor, DBECommandContext context, final GenericTable parent,
        Object from)
    {
        return new UITask<GenericTableIndex>() {
            @Override
            protected GenericTableIndex runTask() {
                EditIndexPage editPage = new EditIndexPage(
                    "Create index",
                    parent,
                    Collections.singletonList(DBSIndexType.OTHER));
                if (!editPage.edit()) {
                    return null;
                }
                final GenericTableIndex index = parent.getDataSource().getMetaModel().createIndexImpl(
                    parent,
                    !editPage.isUnique(),
                    null,
                    0,
                    null,
                    editPage.getIndexType(),
                    false);
                StringBuilder idxName = new StringBuilder(64);
                idxName.append(CommonUtils.escapeIdentifier(parent.getName()));
                int colIndex = 1;
                for (DBSEntityAttribute tableColumn : editPage.getSelectedAttributes()) {
                    if (colIndex == 1) {
                        idxName.append("_").append(CommonUtils.escapeIdentifier(tableColumn.getName()));
                    }
                    index.addColumn(
                        new GenericTableIndexColumn(
                            index,
                            (GenericTableColumn) tableColumn,
                            colIndex++,
                            !Boolean.TRUE.equals(editPage.getAttributeProperty(tableColumn, EditIndexPage.PROP_DESC))));
                }
                idxName.append("_IDX");
                index.setName(DBObjectNameCaseTransformer.transformObjectName(index, idxName.toString()));
                return index;
            }
        }.execute();
    }

}


text:
mod responder;
mod redirect;
mod flash;
mod named_file;
mod stream;
mod response;
mod failure;

pub mod content;
pub mod status;

pub use self::response::{Response, ResponseBuilder, Body, DEFAULT_CHUNK_SIZE};
pub use self::responder::Responder;
pub use self::redirect::Redirect;
pub use self::flash::Flash;
pub use self::named_file::NamedFile;
pub use self::stream::Stream;
pub use self::failure::Failure;
#[doc(inline)] pub use self::content::Content;

/// Type alias for the `Result` of a `Responder::respond` call.
pub type Result<'r> = ::std::result::Result<self::Response<'r>, ::http::Status>;


text:
Java Collection Benchmark
=========================
A collection of microbenchmarks to compare different implementation of various Java collection data structures.

Data structures tested:
* Primitive integer array list
* More to come... (Planned: Object lists, sorted lists, queues, maps and sets)

Tested libraries:
* [FastUtils](http://fastutil.di.unimi.it/)
* [Gs](https://github.com/goldmansachs/gs-collection)
* [Hppc](http://labs.carrotsearch.com/hppc.html)
* [Jdk](http://docs.oracle.com/javase/7/docs/api/java/util/package-summary.html)
* [Joda](http://www.joda.org/joda-primitives/)
* [Trove](https://bitbucket.org/robeden/trove/)
* Planned: [Koloboke](https://github.com/OpenHFT/Koloboke), [Javolution](http://javolution.org/)

#### [:checkered_flag: Latest results](http://marcotc.github.io/java-collection-benchmark-results.htm)

### Implementation details
Current implementation uses [Caliper](https://code.google.com/p/caliper/) for microbenchmarking. ([JMH](http://openjdk.java.net/projects/code-tools/jmh/) was considered, but I couldn't find a way to accurately measure the number of objects created during a benchmark run)