text:
require 'rubygems'

require 'digest/sha1'
require 'base64'

require 'cgi'

require 'basic_client/basic_client'
require 'basic_client/null_logger'

class IndivoClient
  include BasicClient

  def initialize(server_url, consumer_auth, username_domain='', logger=nil)
    @server_url = server_url
    @consumer = OAuth::Consumer.new consumer_auth[:consumer_key], consumer_auth[:consumer_secret], {:site => @server_url}
    @access_token = OAuth::AccessToken.new @consumer

    @username_domain = username_domain

    @logger = logger || NullLogger.new
  end

  def oauth_consumer
    @consumer
  end

  def oauth_token
    @access_token
  end

  # set the token after the fact
  # FIXME: should make a copy here
  def set_token(access_token_auth)
    if access_token_auth
      @access_token = OAuth::AccessToken.new @consumer, access_token_auth[:token], access_token_auth[:secret]
    else
      @access_token = OAuth::AccessToken.new @consumer
    end
    self
  end

  def set_token_from_string(token_str)
    t = CGI::parse(token_str)
    set_token({:token => t['oauth_token'], :secret => t['oauth_token_secret']})
  end

  def get_account_id(account_id)
    begin
      result = get_account_info(account_id)
      result['id']
    rescue WrappedHTTPError => e
      allow_not_found(e)
      nil
    end
  end

  def get_account_info(account_id)
    begin
      do_xml_http(:GET, "/accounts/#{account_id}", {})
    rescue Net::HTTPNotFound
      nil
    end
  end

  def create_account(full_name, contact_email, account_id = nil)
    account_id ||= generate_account_id(full_name, contact_email)

    account = do_xml_http(:POST, "/accounts/", {:account_id => account_id, :full_name => full_name, :contact_email => contact_email, :primary_secret_p => "1", :secondary_secret_p => "1"})
    return account['id'], account['secret'][0]
  end

  def account_add_password_auth(account_id, username, password=nil)
    params = {:system => 'password', :username => username}
    if password
      params[:password] = password
    end
    do_xml_http(:POST, "/accounts/#{account_id}/authsystems/", params)
  end

  def account_add_auth(account_id, auth_system, username)
    do_xml_http(:POST, "/accounts/#{account_id}/authsystems/", {:system => auth_system, :username => username})
  end

  def account_resend_secret_url(email)
    do_xml_http(:POST, "/accounts/#{email}/secret-resend", {})
  end

  def account_secret(email)
    begin
      secret = do_xml_http(:GET, "/accounts/#{email}/secret", {})
    rescue WrappedHTTPError => e
      allow_not_found(e)
      nil
    end
  end

  def create_record(last_name, first_name, email, phone_number, address_street, address_postal_code, address_locality, address_region, address_country)
    record = do_xml_http(:POST, "/records/", "
<Contact>
  <name>
    <fullName>#{CGI::escapeHTML(first_name)} #{CGI::escapeHTML(last_name)}</fullName>
    <givenName>#{CGI::escapeHTML(first_name)}</givenName>
    <familyName>#{CGI::escapeHTML(last_name)}</familyName>
  </name>
  <email type='personal'>#{CGI::escapeHTML(email)}</email>
  <address type='home'>
    <streetAddress>#{CGI::escapeHTML(address_street)}</streetAddress>
    <postalCode>#{CGI::escapeHTML(address_postal_code)}</postalCode>
    <locality>#{CGI::escapeHTML(address_locality)}</locality>
    <region>#{CGI::escapeHTML(address_region)}</region>
    <country>#{CGI::escapeHTML(address_country)}</country>
    <timezone></timezone>
  </address>
  <phoneNumber type='home'>#{CGI::escapeHTML(phone_number)}</phoneNumber>
</Contact>
")
    return record['id']
  end

  def set_demographics(indivo_record_id, date_of_birth, gender)
    document = do_xml_http(:POST, "/records/#{indivo_record_id}/documents/special/demographics", "
<Demographics>
  <dateOfBirth>#{CGI::escapeHTML(date_of_birth.to_s)}</dateOfBirth>
  <gender>#{CGI::escapeHTML(gender)}</gender>
</Demographics>
")
    document['id']
  end

  def get_contact(indivo_record_id)
    do_xml_http(:GET, "/records/#{indivo_record_id}/documents/special/contact" , {})
  end

  def get_demographics(indivo_record_id)
    do_xml_http(:GET, "/records/#{indivo_record_id}/documents/special/demographics", {})
  end

  def session_create(username, password)
    do_http :POST, "/oauth/internal/session_create", {'system' => 'password', 'username' => username, 'password' => password}
  end

  def session_create_by_auth_system(system, username)
    do_http :POST, "/oauth/internal/session_create", {'system' => system, 'username' => username}
  end

  def request_token_claim(token)
    do_http :POST, "/oauth/internal/request_tokens/#{token}/claim", {}
  end

  def request_token_info(token)
    doc = do_http :GET, "/oauth/internal/request_tokens/#{token}/info", {}
    doc.body
  end

  def request_token_approve(token, record_id)
    do_http :POST, "/oauth/internal/request_tokens/#{token}/approve", {:record_id => record_id}
  end

  def record_list(account_email)
    records_xml = do_xml_http(:GET, "/accounts/#{account_email}/records/", {})
    records_xml['Record'].collect{|r| r['id']}
  end

  def default_record
    record_list[0]
  end

  def basic_record(record_id)
    do_xml_http(:GET, "/records/#{record_id}", {})
  end

  def record_set_owner(record_id, owner_account_id)
    do_xml_http(:POST, "/records/#{record_id}/owner", owner_account_id)
  end

  def record_get_owner(record_id)
    begin
      owner_xml = do_xml_http(:GET, "/records/#{record_id}/owner", {})
    rescue WrappedHTTPError => e
      allow_not_found(e)
      return nil
    end

    return owner_xml
  end

  def record_shares(record_id)
    begin
      shares_xml = do_xml_http(:GET, "/records/#{record_id}/shares/", {})
      return shares_xml['Share'] || []
    rescue WrappedHTTPError => e
      allow_not_found(e)
      nil
    end
  end

  def record_share_add(record_id, email, zone)
    # for now no zone
    begin
      do_xml_http(:POST, "/records/#{record_id}/shares/", {:email => email})
    rescue WrappedHTTPError => e
      allow_not_found(e)
      nil
    end
  end

  def record_share_remove(record_id, email)
    do_xml_http(:DELETE, "/records/#{record_id}/shares/#{email}/delete", {})
  end

  def setup(record_id, app_name, setup_doc_content)
    token_str = do_http(:POST, "/records/#{record_id}/apps/#{app_name}/setup", setup_doc_content)
    #puts token_str
    # parse the token str as a querystring
    token = CGI.parse(token_str.body)
    #puts token
    {:token => token['oauth_token'][0], :secret => token['oauth_token_secret'][0]}
  end

  def notify(record_id, message, document_id=nil, app_url=nil)
    params = {:content => message}
    if document_id
      params[:document_id] = document_id
    end

    if app_url
      params[:document_id] = app_url
    end

    do_xml_http(:POST, "/records/#{record_id}/notify", params)
  end

  def test(record_id)
    do_xml_http(:GET, "/records/#{record_id}/test?foo=bar", {})
  end

  def doc_meta_external(record_id, app_email, external_id)
    do_xml_http(:GET, "/records/#{record_id}/documents/external/#{app_email}/#{external_id}/meta", {})
  end

  # read a document
  def document(record_id, document_id, options={})
    raw = options[:raw]

    if(raw)
      do_http(:GET, "/records/#{CGI::escape(record_id)}/documents/#{CGI::escape(document_id)}", {}).body.strip
    else
      do_xml_http(:GET, "/records/#{CGI::escape(record_id)}/documents/#{CGI::escape(document_id)}", {})
    end
  end

  def document_meta(record_id, document_id, options={})
    raw = options[:raw]

    if(raw)
      do_http(:GET, "/records/#{CGI::escape(record_id)}/documents/#{CGI::escape(document_id)}/meta", {}).body.strip
    else
      do_xml_http(:GET, "/records/#{CGI::escape(record_id)}/documents/#{CGI::escape(document_id)}/meta", {})
    end
  end

  def document_versions(record_id, document_id, options={})
    raw = options[:raw]

    if(raw)
      do_http(:GET, "/records/#{CGI::escape(record_id)}/documents/#{CGI::escape(document_id)}/versions/", {}).body.strip
    else
      do_xml_http(:GET, "/records/#{CGI::escape(record_id)}/documents/#{CGI::escape(document_id)}/versions/", {})
    end
  end

  def document_list(record_id, doc_type=nil)
    extra_url = ""
    if doc_type
      extra_url = "?type=#{doc_type}"
    end
    do_xml_http(:GET, "/records/#{CGI::escape(record_id)}/documents/#{extra_url}", {})
  end

  # create a new record document
  def document_new(record_id, app_email, doc_id, content)
    new_doc = do_xml_http(:PUT, "/records/#{CGI::escape(record_id)}/documents/external/#{app_email}/#{CGI::escape(doc_id)}", content)
  end

  # replace a document
  def document_replace(record_id, doc_id, content)
    new_doc = do_xml_http(:POST, "/records/#{CGI::escape(record_id)}/documents/#{doc_id}/replace", content)
  end

  # delete a recently added document
  def document_delete(record_id, doc_id)
    new_doc = do_xml_http(:DELETE, "/records/#{CGI::escape(record_id)}/documents/#{CGI::escape(doc_id)}", {})
  end

  # create a new record document linked to an existing doc
  def document_new_by_rel(record_id, doc_id, rel_type, app_email, external_id, content)
    new_doc = do_xml_http(:POST, "/records/#{record_id}/documents/#{doc_id}/rels/#{rel_type}/external/#{app_email}/#{external_id}", content)
  end

  # application-specific documents
  def app_documents(record_id, app_email, tag)
    params = {}
    if tag
      params['tag'] = tag
    end
    do_xml_http(:GET, "/records/#{CGI::escape(record_id)}/apps/#{app_email}/documents/", params)
  end

  def app_doc(record_id, app_email, doc_id)
    do_xml_http(:GET, "/records/#{CGI::escape(record_id)}/apps/#{app_email}/documents/#{doc_id}", {})
  end

  def app_doc_meta_external(record_id, app_email, external_id)
    do_xml_http(:GET, "/records/#{record_id}/apps/#{app_email}/documents/external/#{external_id}/meta", {})
  end

  # create a new app document
  def app_doc_store_external(record_id, app_email, doc_id, content)
    do_xml_http(:POST, "/records/#{CGI::escape(record_id)}/apps/#{app_email}/documents/external/#{CGI::escape(doc_id)}", content)
  end

  # update an app doc
  def app_doc_store(record_id, app_email, doc_id, content)
    do_xml_http(:POST, "/records/#{CGI::escape(record_id)}/apps/#{app_email}/documents/#{doc_id}/update", content)
  end

  # get an app doc by its external ID
  def app_doc_by_external_id(record_id, app_email, external_id)
    # find the metadata
    doc_meta = app_doc_meta_external record_id, app_email, external_id
    if doc_meta
      return {:id => doc_meta['id'], :content => app_doc(record_id, app_email, doc_meta['id'])}
    else
      return nil
    end
  end

  def send_message_to_record(record_id, message_id, subject, body)
    # This really ought to be a PUT, but due to a bug in Django, a PUT won't
    # work here.

    do_xml_http(:POST, "/records/#{record_id}/inbox/#{message_id}", :subject => subject, :body => body)
  end

  def generate_account_id(full_name, contact_email)
    basename = full_name.downcase.gsub(/[^a-zA-Z]/, '')

    email_hash = Digest::SHA1.hexdigest(contact_email).to_i(16)
    email_hash_digits = (email_hash % 1000).to_s

    basename + email_hash_digits + "@" + @username_domain
  end

  attr_reader :server_url
end


text:
package guru.nidi.android.log;

/**
 *
 */
public interface SimpleLog {
    void debug(String text);

    void info(String text);

    void warn(String text);

    void error(String text);
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef CRIMILD_MATHEMATICS_TRANSFORMATION_INVERSE_
#define CRIMILD_MATHEMATICS_TRANSFORMATION_INVERSE_

#include "Mathematics/Transformation.hpp"

namespace crimild {

    [[nodiscard]] inline constexpr Transformation inverse( const Transformation &t ) noexcept
    {
        return Transformation { t.invMat, t.mat, t.contents };
    }

}

#endif


text:
"""
Configuration functions for the logging package for Python. The core package
is based on PEP 282 and comments thereto in comp.lang.python, and influenced
by Apache's log4j system.

Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved.

To use, simply 'import logging' and log away!
"""

import sys, logging, logging.handlers, socket, struct, os, traceback

try:
    import _thread as thread
    import threading
except ImportError:
    thread = None

from socketserver import ThreadingTCPServer, StreamRequestHandler

DEFAULT_LOGGING_CONFIG_PORT = 9030

if sys.platform == "win32":
    RESET_ERROR = 10054   #WSAECONNRESET
else:
    RESET_ERROR = 104     #ECONNRESET

#
#   The following code implements a socket listener for on-the-fly
#   reconfiguration of logging.
#
#   _listener holds the server object doing the listening
_listener = None

def fileConfig(fname, defaults=None, disable_existing_loggers=True):
    """
    Read the logging configuration from a ConfigParser-format file.

    This can be called several times from an application, allowing an end user
    the ability to select from various pre-canned configurations (if the
    developer provides a mechanism to present the choices and load the chosen
    configuration).
    In versions of ConfigParser which have the readfp method [typically
    shipped in 2.x versions of Python], you can pass in a file-like object
    rather than a filename, in which case the file-like object will be read
    using readfp.
    """
    import configparser

    cp = configparser.ConfigParser(defaults)
    if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
        cp.readfp(fname)
    else:
        cp.read(fname)

    formatters = _create_formatters(cp)

    # critical section
    logging._acquireLock()
    try:
        logging._handlers.clear()
        del logging._handlerList[:]
        # Handlers add themselves to logging._handlers
        handlers = _install_handlers(cp, formatters)
        _install_loggers(cp, handlers, disable_existing_loggers)
    finally:
        logging._releaseLock()

def _resolve(name):
    """Resolve a dotted name to a global object."""
    name = name.split('.')
    used = name.pop(0)
    found = __import__(used)
    for n in name:
        used = used + '.' + n
        try:
            found = getattr(found, n)
        except AttributeError:
            __import__(used)
            found = getattr(found, n)
    return found

def _strip_spaces(alist):
    return map(lambda x: x.strip(), alist)

def _create_formatters(cp):
    """Create and return formatters"""
    flist = cp.get("formatters", "keys")
    if not len(flist):
        return {}
    flist = flist.split(",")
    flist = _strip_spaces(flist)
    formatters = {}
    for form in flist:
        sectname = "formatter_%s" % form
        opts = cp.options(sectname)
        if "format" in opts:
            fs = cp.get(sectname, "format", 1)
        else:
            fs = None
        if "datefmt" in opts:
            dfs = cp.get(sectname, "datefmt", 1)
        else:
            dfs = None
        c = logging.Formatter
        if "class" in opts:
            class_name = cp.get(sectname, "class")
            if class_name:
                c = _resolve(class_name)
        f = c(fs, dfs)
        formatters[form] = f
    return formatters

def _install_handlers(cp, formatters):
    """Install and return handlers"""
    hlist = cp.get("handlers", "keys")
    if not len(hlist):
        return {}
    hlist = hlist.split(",")
    hlist = _strip_spaces(hlist)
    handlers = {}
    fixups = [] #for inter-handler references
    for hand in hlist:
        sectname = "handler_%s" % hand
        klass = cp.get(sectname, "class")
        opts = cp.options(sectname)
        if "formatter" in opts:
            fmt = cp.get(sectname, "formatter")
        else:
            fmt = ""
        try:
            klass = eval(klass, vars(logging))
        except (AttributeError, NameError):
            klass = _resolve(klass)
        args = cp.get(sectname, "args")
        args = eval(args, vars(logging))
        h = klass(*args)
        if "level" in opts:
            level = cp.get(sectname, "level")
            h.setLevel(logging._levelNames[level])
        if len(fmt):
            h.setFormatter(formatters[fmt])
        if issubclass(klass, logging.handlers.MemoryHandler):
            if "target" in opts:
                target = cp.get(sectname,"target")
            else:
                target = ""
            if len(target): #the target handler may not be loaded yet, so keep for later...
                fixups.append((h, target))
        handlers[hand] = h
    #now all handlers are loaded, fixup inter-handler references...
    for h, t in fixups:
        h.setTarget(handlers[t])
    return handlers

def _install_loggers(cp, handlers, disable_existing_loggers):
    """Create and install loggers"""

    # configure the root first
    llist = cp.get("loggers", "keys")
    llist = llist.split(",")
    llist = list(map(lambda x: x.strip(), llist))
    llist.remove("root")
    sectname = "logger_root"
    root = logging.root
    log = root
    opts = cp.options(sectname)
    if "level" in opts:
        level = cp.get(sectname, "level")
        log.setLevel(logging._levelNames[level])
    for h in root.handlers[:]:
        root.removeHandler(h)
    hlist = cp.get(sectname, "handlers")
    if len(hlist):
        hlist = hlist.split(",")
        hlist = _strip_spaces(hlist)
        for hand in hlist:
            log.addHandler(handlers[hand])

    #and now the others...
    #we don't want to lose the existing loggers,
    #since other threads may have pointers to them.
    #existing is set to contain all existing loggers,
    #and as we go through the new configuration we
    #remove any which are configured. At the end,
    #what's left in existing is the set of loggers
    #which were in the previous configuration but
    #which are not in the new configuration.
    existing = list(root.manager.loggerDict.keys())
    #The list needs to be sorted so that we can
    #avoid disabling child loggers of explicitly
    #named loggers. With a sorted list it is easier
    #to find the child loggers.
    existing.sort()
    #We'll keep the list of existing loggers
    #which are children of named loggers here...
    child_loggers = []
    #now set up the new ones...
    for log in llist:
        sectname = "logger_%s" % log
        qn = cp.get(sectname, "qualname")
        opts = cp.options(sectname)
        if "propagate" in opts:
            propagate = cp.getint(sectname, "propagate")
        else:
            propagate = 1
        logger = logging.getLogger(qn)
        if qn in existing:
            i = existing.index(qn)
            prefixed = qn + "."
            pflen = len(prefixed)
            num_existing = len(existing)
            i = i + 1 # look at the entry after qn
            while (i < num_existing) and (existing[i][:pflen] == prefixed):
                child_loggers.append(existing[i])
                i = i + 1
            existing.remove(qn)
        if "level" in opts:
            level = cp.get(sectname, "level")
            logger.setLevel(logging._levelNames[level])
        for h in logger.handlers[:]:
            logger.removeHandler(h)
        logger.propagate = propagate
        logger.disabled = 0
        hlist = cp.get(sectname, "handlers")
        if len(hlist):
            hlist = hlist.split(",")
            hlist = _strip_spaces(hlist)
            for hand in hlist:
                logger.addHandler(handlers[hand])

    #Disable any old loggers. There's no point deleting
    #them as other threads may continue to hold references
    #and by disabling them, you stop them doing any logging.
    #However, don't disable children of named loggers, as that's
    #probably not what was intended by the user.
    for log in existing:
        logger = root.manager.loggerDict[log]
        if log in child_loggers:
            logger.level = logging.NOTSET
            logger.handlers = []
            logger.propagate = 1
        elif disable_existing_loggers:
            logger.disabled = 1

def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
    """
    Start up a socket server on the specified port, and listen for new
    configurations.

    These will be sent as a file suitable for processing by fileConfig().
    Returns a Thread object on which you can call start() to start the server,
    and which you can join() when appropriate. To stop the server, call
    stopListening().
    """
    if not thread:
        raise NotImplementedError("listen() needs threading to work")

    class ConfigStreamHandler(StreamRequestHandler):
        """
        Handler for a logging configuration request.

        It expects a completely new logging configuration and uses fileConfig
        to install it.
        """
        def handle(self):
            """
            Handle a request.

            Each request is expected to be a 4-byte length, packed using
            struct.pack(">L", n), followed by the config file.
            Uses fileConfig() to do the grunt work.
            """
            import tempfile
            try:
                conn = self.connection
                chunk = conn.recv(4)
                if len(chunk) == 4:
                    slen = struct.unpack(">L", chunk)[0]
                    chunk = self.connection.recv(slen)
                    while len(chunk) < slen:
                        chunk = chunk + conn.recv(slen - len(chunk))
                    #Apply new configuration. We'd like to be able to
                    #create a StringIO and pass that in, but unfortunately
                    #1.5.2 ConfigParser does not support reading file
                    #objects, only actual files. So we create a temporary
                    #file and remove it later.
                    file = tempfile.mktemp(".ini")
                    f = open(file, "w")
                    f.write(chunk)
                    f.close()
                    try:
                        fileConfig(file)
                    except (KeyboardInterrupt, SystemExit):
                        raise
                    except:
                        traceback.print_exc()
                    os.remove(file)
            except socket.error as e:
                if not isinstancetype(e.args, tuple):
                    raise
                else:
                    errcode = e.args[0]
                    if errcode != RESET_ERROR:
                        raise

    class ConfigSocketReceiver(ThreadingTCPServer):
        """
        A simple TCP socket-based logging config receiver.
        """

        allow_reuse_address = 1

        def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
                     handler=None):
            ThreadingTCPServer.__init__(self, (host, port), handler)
            logging._acquireLock()
            self.abort = 0
            logging._releaseLock()
            self.timeout = 1

        def serve_until_stopped(self):
            import select
            abort = 0
            while not abort:
                rd, wr, ex = select.select([self.socket.fileno()],
                                           [], [],
                                           self.timeout)
                if rd:
                    self.handle_request()
                logging._acquireLock()
                abort = self.abort
                logging._releaseLock()

    def serve(rcvr, hdlr, port):
        server = rcvr(port=port, handler=hdlr)
        global _listener
        logging._acquireLock()
        _listener = server
        logging._releaseLock()
        server.serve_until_stopped()

    return threading.Thread(target=serve,
                            args=(ConfigSocketReceiver,
                                  ConfigStreamHandler, port))

def stopListening():
    """
    Stop the listening server which was created with a call to listen().
    """
    global _listener
    if _listener:
        logging._acquireLock()
        _listener.abort = 1
        _listener = None
        logging._releaseLock()


text:
import hashlib
import os
import re
import subprocess
import time
import uuid

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.contrib.staticfiles.finders import find as find_static_path
from django.utils.encoding import force_bytes

from olympia.lib.jingo_minify_helpers import ensure_path_exists

def run_command(command):
    """Run a command and correctly poll the output and write that to stdout"""
    process = subprocess.Popen(
        command, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
            break
        if output:
            print(output.strip())
    return process.poll()

class Command(BaseCommand):
    help = ('Compresses css and js assets defined in settings.MINIFY_BUNDLES')

    # This command must not do any system checks because Django runs db-field
    # related checks since 1.10 which require a working MySQL connection.
    # We don't have that during our docker builds and since `compress_assets`
    # is being used while building our docker images we have to disable them.
    requires_system_checks = False

    checked_hash = {}
    bundle_hashes = {}

    missing_files = 0
    minify_skipped = 0

    def add_arguments(self, parser):
        """Handle command arguments."""
        parser.add_argument(
            '--force', action='store_true',
            help='Ignores modified/created dates and forces compression.')

    def generate_build_id(self):
        return uuid.uuid4().hex[:8]

    def update_hashes(self):
        # Adds a time based hash on to the build id.
        self.build_id = '%s-%s' % (
            self.generate_build_id(), hex(int(time.time()))[2:])

        build_id_file = os.path.realpath(
            os.path.join(settings.ROOT, 'build.py'))

        with open(build_id_file, 'w') as f:
            f.write('BUILD_ID_CSS = "%s"\n' % self.build_id)
            f.write('BUILD_ID_JS = "%s"\n' % self.build_id)
            f.write('BUILD_ID_IMG = "%s"\n' % self.build_id)
            f.write('BUNDLE_HASHES = %s\n' % self.bundle_hashes)

    def handle(self, **options):
        self.force_compress = options.get('force', False)

        # This will loop through every bundle, and do the following:
        # - Concat all files into one
        # - Cache bust all images in CSS files
        # - Minify the concatted files
        for ftype, bundle in settings.MINIFY_BUNDLES.items():
            for name, files in bundle.items():
                # Set the paths to the files.
                concatted_file = os.path.join(
                    settings.ROOT, 'static',
                    ftype, '%s-all.%s' % (name, ftype,))
                compressed_file = os.path.join(
                    settings.ROOT, 'static',
                    ftype, '%s-min.%s' % (name, ftype,))

                ensure_path_exists(concatted_file)
                ensure_path_exists(compressed_file)

                files_all = []
                for fn in files:
                    processed = self._preprocess_file(fn)
                    # If the file can't be processed, we skip it.
                    if processed is not None:
                        files_all.append(processed)

                # Concat all the files.
                tmp_concatted = '%s.tmp' % concatted_file
                if len(files_all) == 0:
                    raise CommandError(
                        'No input files specified in '
                        'MINIFY_BUNDLES["%s"]["%s"] in settings.py!' %
                        (ftype, name)
                    )
                run_command('cat {files} > {tmp}'.format(
                    files=' '.join(files_all),
                    tmp=tmp_concatted
                ))

                # Cache bust individual images in the CSS.
                if ftype == 'css':
                    bundle_hash = self._cachebust(tmp_concatted, name)
                    self.bundle_hashes['%s:%s' % (ftype, name)] = bundle_hash

                # Compresses the concatenations.
                is_changed = self._is_changed(concatted_file)
                self._clean_tmp(concatted_file)
                if is_changed or not os.path.isfile(compressed_file):
                    self._minify(ftype, concatted_file, compressed_file)
                else:
                    print(
                        'File unchanged, skipping minification of %s' % (
                            concatted_file))
                    self.minify_skipped += 1

        # Write out the hashes
        self.update_hashes()

        if self.minify_skipped:
            print(
                'Unchanged files skipped for minification: %s' % (
                    self.minify_skipped))

    def _preprocess_file(self, filename):
        """Preprocess files and return new filenames."""
        css_bin = filename.endswith('.less') and settings.LESS_BIN
        source = find_static_path(filename)
        target = source
        if css_bin:
            target = '%s.css' % source
            run_command('{lessc} {source} {target}'.format(
                lessc=css_bin,
                source=str(source),
                target=str(target)))
        return target

    def _is_changed(self, concatted_file):
        """Check if the file has been changed."""
        if self.force_compress:
            return True

        tmp_concatted = '%s.tmp' % concatted_file
        file_exists = (
            os.path.exists(concatted_file) and
            os.path.getsize(concatted_file) == os.path.getsize(tmp_concatted))
        if file_exists:
            orig_hash = self._file_hash(concatted_file)
            temp_hash = self._file_hash(tmp_concatted)
            return orig_hash != temp_hash
        return True  # Different filesize, so it was definitely changed

    def _clean_tmp(self, concatted_file):
        """Replace the old file with the temp file."""
        tmp_concatted = '%s.tmp' % concatted_file
        if os.path.exists(concatted_file):
            os.remove(concatted_file)
        os.rename(tmp_concatted, concatted_file)

    def _cachebust(self, css_file, bundle_name):
        """Cache bust images.  Return a new bundle hash."""
        self.stdout.write(
            'Cache busting images in %s\n' % re.sub('.tmp$', '', css_file))

        if not os.path.exists(css_file):
            return

        css_content = ''
        with open(css_file, 'r') as css_in:
            css_content = css_in.read()

        def _parse(url):
            return self._cachebust_regex(url, css_file)

        css_parsed = re.sub(r'url\(([^)]*?)\)', _parse, css_content)

        with open(css_file, 'w') as css_out:
            css_out.write(css_parsed)

        # Return bundle hash for cachebusting JS/CSS files.
        file_hash = hashlib.md5(force_bytes(css_parsed)).hexdigest()[0:7]
        self.checked_hash[css_file] = file_hash

        if self.missing_files:
            self.stdout.write(
                ' - Error finding %s images\n' % (self.missing_files,))
            self.missing_files = 0

        return file_hash

    def _minify(self, ftype, file_in, file_out):
        """Run the proper minifier on the file."""
        if ftype == 'js' and hasattr(settings, 'UGLIFY_BIN'):
            opts = {'method': 'UglifyJS', 'bin': settings.UGLIFY_BIN}
            run_command('{uglify} -v -o {target} {source} -m'.format(
                uglify=opts['bin'],
                target=file_out,
                source=file_in))
        elif ftype == 'css' and hasattr(settings, 'CLEANCSS_BIN'):
            opts = {'method': 'clean-css', 'bin': settings.CLEANCSS_BIN}
            run_command('{cleancss} -o {target} {source}'.format(
                cleancss=opts['bin'],
                target=file_out,
                source=file_in))

        self.stdout.write(
            'Minifying %s (using %s)\n' % (file_in, opts['method']))

    def _file_hash(self, url):
        """Open the file and get a hash of it."""
        if url in self.checked_hash:
            return self.checked_hash[url]

        file_hash = ''
        try:
            with open(url, 'rb') as f:
                file_hash = hashlib.md5(f.read()).hexdigest()[0:7]
        except IOError:
            self.missing_files += 1
            self.stdout.write(' - Could not find file %s\n' % url)

        self.checked_hash[url] = file_hash
        return file_hash

    def _cachebust_regex(self, img, parent):
        """Run over the regex; img is the structural regex object."""
        url = img.group(1).strip('"\'')
        if url.startswith('data:') or url.startswith('http'):
            return 'url(%s)' % url

        url = url.split('?')[0]
        full_url = os.path.join(
            settings.ROOT, os.path.dirname(parent), url)

        return 'url(%s?%s)' % (url, self._file_hash(full_url))


text:
<?php

namespace OpenOrchestra\FunctionalTests\UserAdminBundle\Controller;

use OpenOrchestra\BaseBundle\Tests\AbstractTest\AbstractWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

/**
 * Class AuthorizationControllersTest
 *
 * @group securityCheck
 */
class AuthorizationControllersTest extends AbstractWebTestCase
{
    /**
     * @var Client
     */
    protected $client;

    /**
     * Set up the test
     */
    public function setUp()
    {
        $this->client = static::createClient();
    }

    /**
     * Test token creation and usage
     */
    public function testTokenCreation()
    {
        $headers = array(
            'PHP_AUTH_USER' => 'test_key',
            'PHP_AUTH_PW' => 'test_secret',
            'HTTP_username' => 'p-admin',
            'HTTP_password' => 'p-admin',
        );
        $this->client->request('GET', '/oauth/access_token?grant_type=password', array(), array(), $headers);
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $this->assertSame('application/json', $this->client->getResponse()->headers->get('content-type'));
    }
}


text:
layout: post
title:  Quartz 01-quartz 入门使用介绍
date:  2017-12-19 14:43:25 +0800
categories: [Java]
tags: [java, java-tool, sh]
published: true
---

# Quartz

[Quartz](http://www.quartz-scheduler.org/) is a richly featured, open source job scheduling library that can be integrated within virtually
any Java application - from the smallest stand-alone application to the largest e-commerce system.

# 入门案例

## maven 引入

```xml
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
</dependency>
```

## 建立 Task

```java
package com.ryo.quartz.hello.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.err.println("Hello Quartz!");
    }

}
```

## 测试代码

```java
import com.ryo.quartz.hello.job.MyJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class AppMain {

    public static void main(String[] args) throws SchedulerException {
        // define the job and tie it to our MyJob class
        JobDetail job = JobBuilder.newJob(MyJob.class)
                .withIdentity("job1", "group1")
                .build();

        // Trigger the job to run now, and then repeat every 5 seconds
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(5)
                        .repeatForever())
                .build();

        // Grab the Scheduler instance from the Factory
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        // and start it off
        scheduler.start();
        // Tell quartz to schedule the job using our trigger
        scheduler.scheduleJob(job, trigger);
    }
}
```

## 运行结果

每 5S 执行一次我们的 Job

```
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Hello Quartz!
Hello Quartz!
Hello Quartz!
Hello Quartz!
```

# 拓展阅读

[Quartz 入门系列教程-00-序章](https://blog.csdn.net/ryo1060732496/article/details/79794802)

* any list
{:toc}


text:
package org.lwjgl.opencl;

import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;

/** Instances of this class may be passed to the {@link CL11#clSetEventCallback SetEventCallback} method. */
public abstract class CLEventCallback extends Callback implements CLEventCallbackI {

	/** Creates a {@code CLEventCallback} instance from the specified function pointer. */
	public static CLEventCallback create(long functionPointer) {
		if ( functionPointer == NULL )
			return null;

		CLEventCallbackI instance = Callback.get(functionPointer);
		return instance instanceof CLEventCallback
			? (CLEventCallback)instance
			: new Container(functionPointer, instance);
	}

	/** Creates a {@code CLEventCallback} instance that delegates to the specified {@code CLEventCallbackI} instance. */
	public static CLEventCallback create(CLEventCallbackI instance) {
		return instance instanceof CLEventCallback
			? (CLEventCallback)instance
			: new Container(instance.address(), instance);
	}

	protected CLEventCallback() {
		super(NULL);
		address = CLEventCallbackI.super.address();
	}

	private CLEventCallback(long functionPointer) {
		super(functionPointer);
	}

	private static final class Container extends CLEventCallback {

		private final CLEventCallbackI delegate;

		Container(long functionPointer, CLEventCallbackI delegate) {
			super(functionPointer);
			this.delegate = delegate;
		}

		@Override
		public void invoke(long event, int event_command_exec_status, long user_data) {
			delegate.invoke(event, event_command_exec_status, user_data);
		}

	}

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Autofac;
using MindTouch.Dream.Http;
using MindTouch.Tasking;
using MindTouch.Xml;

namespace MindTouch.Dream {
    using Yield = IEnumerator<IYield>;

    /// <summary>
    /// Provides a hosting environment for <see cref="IDreamService"/> based services.
    /// </summary>
    public class DreamHost : IDisposable {

        //--- Constants ---

        /// <summary>
        /// Default dream host port: 8081
        /// </summary>
        public const int DEFAULT_PORT = 8081;

        //--- Class Fields ---
        private static log4net.ILog _log = LogUtils.CreateLog();

        //--- Class Methods ---
        private static XUri MakeUri(IPAddress address, int port) {
            switch(address.AddressFamily) {
            case System.Net.Sockets.AddressFamily.InterNetwork:
                return new XUri(String.Format("http://{0}:{1}/", address, port));
            case System.Net.Sockets.AddressFamily.InterNetworkV6:
                return new XUri(String.Format("http://[{0}]:{1}/", address, port));
            }
            return null;
        }

        //--- Fields ---
        private IDreamEnvironment _env;
        private Plug _host;
        private List<HttpTransport> _transports = new List<HttpTransport>();
        private bool _disposed;

        //--- Constructors ---

        /// <summary>
        /// Create a new host with default settings.
        /// </summary>
        public DreamHost() : this(new XDoc("config"), null) { }

        /// <summary>
        /// Create a new host with provided configuration.
        /// </summary>
        /// <param name="config">Host configuration.</param>
        public DreamHost(XDoc config) : this(config, null) { }

        /// <summary>
        /// Create a new host with provided configuration and an Inversion of Control container.
        /// </summary>
        /// <remarks>
        /// The IoC container is also injected into default activator, so that <see cref="IDreamService"/> instances
        /// can be resolved from the container. The host configuration is provided to the container as a typed parameter.
        /// </remarks>
        /// <param name="config">Host configuration.</param>
        /// <param name="container">IoC Container.</param>
        public DreamHost(XDoc config, IContainer container) {
            if(config == null) {
                throw new ArgumentNullException("config");
            }

            // read host settings
            string appDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
            int limit = config["connect-limit"].AsInt ?? 0;
            int httpPort = config["http-port"].AsInt ?? DEFAULT_PORT;
            AuthenticationSchemes authenticationScheme = AuthenticationSchemes.Anonymous;
            string authShemes = config["authentication-shemes"].AsText;
            if(!String.IsNullOrEmpty(authShemes)) {
                try {
                    authenticationScheme = (AuthenticationSchemes)Enum.Parse(typeof(AuthenticationSchemes), authShemes, true);
                } catch(Exception e) {
                    _log.Warn(String.Format("invalid authetication scheme specified :{0}", authShemes), e);
                }
            }
            // read ip-addresses
            var addresses = new List<string>();
            foreach(XDoc ip in config["host|ip"]) {
                addresses.Add(ip.AsText);
            }
            if(addresses.Count == 0) {

                // if no addresses were supplied listen to all
                addresses.Add("*:" + httpPort);
            }

            // use default servername
            XUri publicUri = config["uri.public"].AsUri;
            if(publicUri == null) {

                // backwards compatibility
                publicUri = config["server-name"].AsUri;
                if(publicUri == null) {
                    foreach(IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName())) {
                        if(addr.AddressFamily == AddressFamily.InterNetwork) {
                            XUri.TryParse("http://" + addr, out publicUri);
                        }
                    }
                    if(publicUri == null) {
                        // failed to get an address out of dns, fall back to localhost
                        XUri.TryParse("http://localhost", out publicUri);
                    }
                }
                publicUri = publicUri.AtPath(config["server-path"].AsText ?? config["path-prefix"].AsText ?? string.Empty);
            }

            // create environment and initialize it
            _env = new DreamHostService(container);
            try {

                // initialize environment
                string apikey = config["apikey"].AsText ?? StringUtil.CreateAlphaNumericKey(32);
                XDoc serviceConfig = new XDoc("config");
                var storageType = config["storage/@type"].AsText ?? "local";
                if("s3".EqualsInvariant(storageType)) {
                    serviceConfig.Add(config["storage"]);
                } else {
                    serviceConfig.Elem("storage-dir", config["storage-dir"].AsText ?? config["service-dir"].AsText ?? appDirectory);
                }
                serviceConfig.Elem("apikey", apikey);
                serviceConfig.Elem("uri.public", publicUri);
                serviceConfig.Elem("connect-limit", limit);
                serviceConfig.Elem("guid", config["guid"].AsText);
                serviceConfig.AddAll(config["components"]);
                var memorize = config["memorize-aliases"];
                if(!memorize.IsEmpty) {
                    serviceConfig.Elem("memorize-aliases", memorize.AsBool);
                }
                _env.Initialize(serviceConfig);

                // initialize host plug
                _host = _env.Self.With("apikey", apikey);

                // load assemblies in 'services' folder
                string servicesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "services");
                if(Directory.Exists(servicesFolder)) {

                    // Note (arnec): Deprecated, but the suggested alternative really doesn't apply since we don't want to
                    // load services into a separate appdomain.
#pragma warning disable 618,612
                    AppDomain.CurrentDomain.AppendPrivatePath("services");
#pragma warning restore 618,612
                    foreach(string file in Directory.GetFiles(servicesFolder, "*.dll")) {

                        // register assembly blueprints
                        DreamMessage response = _host.At("load").With("name", Path.GetFileNameWithoutExtension(file)).Post(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait();
                        if(!response.IsSuccessful) {
                            _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file);
                        }
                    }
                }

                // add acccess-points
                AddListener(new XUri(String.Format("http://{0}:{1}/", "localhost", httpPort)), authenticationScheme);

                // check if user prescribed a set of IP addresses to use
                if(addresses != null) {

                    // listen to custom addresses (don't use the supplied port info, we expect that to be part of the address)
                    foreach(string address in addresses) {
                        if(!StringUtil.EqualsInvariantIgnoreCase(address, "localhost")) {
                            AddListener(new XUri(String.Format("http://{0}/", address)), authenticationScheme);
                        }
                    }
                } else {

                    // add listeners for all known IP addresses
                    foreach(IPAddress address in Dns.GetHostAddresses(Dns.GetHostName())) {
                        XUri uri = MakeUri(address, httpPort);
                        if(uri != null) {
                            AddListener(uri, authenticationScheme);
                            try {
                                foreach(string alias in Dns.GetHostEntry(address).Aliases) {
                                    AddListener(new XUri(String.Format("http://{0}:{1}/", alias, httpPort)), authenticationScheme);
                                }
                            } catch { }
                        }
                    }
                }
            } catch(Exception e) {
                if((e is HttpListenerException) && e.Message.EqualsInvariant("Access is denied")) {
                    _log.ErrorExceptionMethodCall(e, "ctor", "insufficient privileges to create HttpListener, make sure the application runs with Administrator rights");
                } else {
                    _log.ErrorExceptionMethodCall(e, "ctor");
                }
                try {
                    _env.Deinitialize();
                } catch { }
                throw;
            }
        }

        /// <summary>
        /// Finalizer to clean-up an undisposed host.
        /// </summary>
        ~DreamHost() {
            Dispose(false);
        }

        //--- Properties ---

        /// <summary>
        /// Http location of host <see cref="IDreamService"/>.
        /// </summary>
        public Plug Self { get { return _host; } }

        /// <summary>
        /// Global Id used for local:// uri's
        /// </summary>
        public Guid GlobalId { get { return _env.GlobalId; } }

        /// <summary>
        /// <see langword="True"/> if the host is running.
        /// </summary>
        public bool IsRunning { get { return _env.IsRunning; } }

        /// <summary>
        /// Root local:// uri for this host.
        /// </summary>
        public XUri LocalMachineUri { get { return _env.LocalMachineUri; } }

        /// <summary>
        /// Current host activity.
        /// </summary>
        public Tuplet<DateTime, string>[] ActivityMessages { get { return _env.ActivityMessages; } }

        //--- Methods ---

        /// <summary>
        /// Execute a set of scripts against the host.
        /// </summary>
        /// <remarks>
        /// This method is thread-blocking.  Please avoid using it if possible.
        /// </remarks>
        /// <param name="scripts">Scripts document.</param>
        /// <param name="path">Host path to post the scripts against.</param>
#if WARN_ON_SYNC
        [Obsolete("This method is thread-blocking.  Please avoid using it if possible.")]
#endif
        public void RunScripts(XDoc scripts, string path) {
            foreach(XDoc script in scripts["script | config"]) {
                RunScript(script, path);
            }
        }

        /// <summary>
        /// Execute a script against the host.
        /// </summary>
        /// <remarks>
        /// This method is thread-blocking.  Please avoid using it if possible.
        /// </remarks>
        /// <param name="script">Script document.</param>
        /// <param name="path">Host path to post the script against.</param>
#if WARN_ON_SYNC
        [Obsolete("This method is thread-blocking.  Please avoid using it if possible.")]
#endif
        public void RunScript(XDoc script, string path) {

            // check if a filename was provided
            string filename = script["@src"].AsText;
            if(filename != null) {

                // check if filename is relative
                if(!Path.IsPathRooted(filename) && (path != null)) {
                    filename = Path.Combine(path, filename);
                }

                // attempt to load script file
                if(!File.Exists(filename)) {
                    throw new FileNotFoundException(string.Format("script not found: {0}", filename));
                }
                script = XDocFactory.LoadFrom(filename, MimeType.XML);
            }

            // execute script
            if(script == null) {
                throw new Exception(string.Format("invalid script: {0}", script.AsText));
            }

            // convert <config> element into a <script> element
            if(script.HasName("config")) {
                XDoc doc = new XDoc("script");
                doc.Start("action").Attr("verb", "POST").Attr("path", "/host/services");
                doc.Add(script);
                doc.End();
                script = doc;
            }

            // execute script
            _host.At("execute").Post(script);
        }

        /// <summary>
        /// Block the current thread until the host shuts down.
        /// </summary>
        /// <remarks>
        /// This call does not initiate a shut down.
        /// </remarks>
        public void WaitUntilShutdown() {
            _env.WaitUntilShutdown();
        }

        /// <summary>
        /// Add a host activity.
        /// </summary>
        /// <param name="key">Activity key.</param>
        /// <param name="description">Description of activity.</param>
        public void AddActivityDescription(object key, string description) {
            _env.AddActivityDescription(key, description);
        }

        /// <summary>
        /// Remove a host activity.
        /// </summary>
        /// <param name="key">Activity key.</param>
        public void RemoveActivityDescription(object key) {
            _env.RemoveActivityDescription(key);
        }

        /// <summary>
        /// Update the host's info message.
        /// </summary>
        /// <param name="source">Message source.</param>
        /// <param name="message">Info message.</param>
        public void UpdateInfoMessage(string source, string message) {
            _env.UpdateInfoMessage(source, message);
        }

        /// <summary>
        /// Shut down and clean up the host's resources.
        /// </summary>
        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void AddListener(XUri uri, AuthenticationSchemes authenticationSheme) {
            switch(uri.Scheme.ToLowerInvariant()) {
            case Scheme.HTTP:
            case Scheme.HTTPS: {
                    HttpTransport transport = new Http.HttpTransport(_env, uri, authenticationSheme);
                    transport.Startup();
                    _transports.Add(transport);
                }
                break;
            default:
                throw new ArgumentException("unsupported scheme: " + uri.Scheme);
            }
        }

        private void Dispose(bool disposing) {
            if(_disposed) {
                return;
            }
            _disposed = true;
            if(disposing) {

                // shutdown the environment
                if(_env != null) {
                    try {
                        _env.Deinitialize();
                    } catch(Exception e) {
                        _log.ErrorExceptionMethodCall(e, "Destroy");
                    }
                }

                // stop transports
                if(_transports != null) {
                    foreach(Http.HttpTransport transport in _transports) {
                        if(transport != null) {
                            try {
                                transport.Shutdown();
                            } catch(Exception e) {
                                _log.ErrorExceptionMethodCall(e, "Destroy");
                            }
                        }
                    }
                    _transports.Clear();
                }
            }
            _host = null;
            _env = null;
            _transports = null;
        }
    }
}


text:
prepara('fonte','fontes','fontesGabarito');
prepara('entrada','entradas','entradasGabarito');
prepara('opcao','opcoes','multiplaEscolhas');


text:
namespace ph
{

DammertzDispatcher::DammertzDispatcher(
	const uint32  numWorkers,
	const Region& fullRegion) :

	DammertzDispatcher(numWorkers, fullRegion, 1.0_r, 16)
{}

DammertzDispatcher::DammertzDispatcher(
	const uint32      numWorkers,
	const Region&     fullRegion,
	const real        precisionStandard,
	const std::size_t initialDepthPerRegion) :

	DammertzDispatcher(
		numWorkers,
		fullRegion,
		precisionStandard,
		initialDepthPerRegion,
		16,
		64)
{}

DammertzDispatcher::DammertzDispatcher(
	const uint32      numWorkers,
	const Region&     fullRegion,
	const real        precisionStandard,
	const std::size_t initialDepthPerRegion,
	const std::size_t standardDepthPerRegion,
	const std::size_t terminusDepthPerRegion) :

	m_standardDepthPerRegion(std::max(standardDepthPerRegion, std::size_t(1))),
	m_terminusDepthPerRegion(std::max(terminusDepthPerRegion, std::size_t(1))),
	m_fullRegion            (fullRegion),
	m_pendingRegions        ()
{
	m_terminateThreshold = precisionStandard * 0.0002_r;
	m_splitThreshold     = 256.0_r * m_terminateThreshold;

	PH_ASSERT_GT(initialDepthPerRegion,  0);
	PH_ASSERT_GT(standardDepthPerRegion, 0);
	PH_ASSERT_GT(terminusDepthPerRegion, 0);

	// divide the full region initially to facilitate parallelism

	GridScheduler initialScheduler(
		numWorkers,
		WorkUnit(fullRegion, std::max(initialDepthPerRegion, std::size_t(1))));

	WorkUnit workUnit;
	while(initialScheduler.schedule(&workUnit))
	{
		m_pendingRegions.push(workUnit);
	}
}

bool DammertzDispatcher::dispatch(WorkUnit* const out_workUnit)
{
	PH_ASSERT(out_workUnit);

	if(m_pendingRegions.empty())
	{
		return false;
	}

	const WorkUnit newRegion = m_pendingRegions.front();
	m_pendingRegions.pop();

	*out_workUnit = newRegion;
	return true;
}

}// end namespace ph


text:
An explanation of each field in `settings.json`

## `fetch_url`

Absolute URL to a [`fetch-django`](https://github.com/zyphrus/fetch-django) server

#### Example

```json
"fetch_url" : "http://127.0.0.1"
```

## `fetch_save_paths`

A dictionary of `media_type`s to paths were to save to.

The key is the `media_type` name. If a given `media_type` does not have an
entry it defaults to the value of `*`.

#### Example

```json
"fetch_save_paths": {
	"*": "./fetched",
    "podcast": "./podcasts"
}
```
With this configuration downloading something with the `media_type` is `podcast`
it will be saved to `./podcast`, but something with the `media_type` `web_series`
will be saved in `./fetched`

## `sort_save_path`

A local path for files found by the Sorter.

Copies the file to `<sort_save_path>/<media_type>/<series_title>/<file_name>`

#### Example

```json
"sort_save_path" : "./sorted"
```

With this configuration any files picked up by the Sorter will be copied
to `./sorted/<media_type>/<series_title>/<file name>`

## `sort_search_paths`

A list of local paths to search through while running the Sorter

#### Example

```json
"sort_search_paths" : ["./fetched"]
```

With this configuration any files in `./fetched` that match the Sorter's
criteria will be sorted.

## Note

All of these fields names and functions are subject.

### Example of full settings

```json
{
	"fetch_url": "http://127.0.0.1",
	"fetch_save_paths" : {
		"*" : "./fetched",
		"podcast": "./podcasts"
	},

	"sort_save_path": "./sorted",
	"sort_search_paths" :[
		"./fetched"
	]
}
```


text:
<!DOCTYPE HTML>

		<title>Trumpet - Spread your Fake News</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>

		<link href="../static/css/shared/main.css" 																					th:href="@{/css/shared/main.css}" 						rel="stylesheet" />
		<link href="../static/css/shared/dialogs.css"     																			th:href="@{/css/shared/dialogs.css}"     				rel="stylesheet" />
		<link href="../static/css/shared/navigationBar.css" 																		th:href="@{/css/shared/navigationBar.css}" 				rel="stylesheet" />
		<link href="../static/css/shared/footerButtons.css" 																		th:href="@{/css/shared/footerButtons.css}"				rel="stylesheet" />
		<link href="../static/css/profilePage/profilePage.css" 																		th:href="@{/css/profilePage/profilePage.css}" 			rel="stylesheet" />
		<link href="../static/css/profilePage/profilePage_desktop.css" media="screen and (min-width:1000px)" 						th:href="@{/css/profilePage/profilePage_desktop.css}" 	rel="stylesheet" />
		<link href="../static/css/profilePage/profilePage_tablet.css"  media="screen and (min-width:620px) and (max-width:999px)" 	th:href="@{/css/profilePage/profilePage_tablet.css}" 	rel="stylesheet" />
		<link href="../static/css/profilePage/profilePage_mobile.css"  media="screen and (min-width:0px) and (max-width:619px)" 	th:href="@{/css/profilePage/profilePage_mobile.css}" 	rel="stylesheet" />

		<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
		<link th:href="@{/webjars/bootstrap/3.3.4/css/bootstrap.min.css}"
			rel="stylesheet" media="screen" />
			<link th:href="@{/webjars/bootstrap/3.3.4/css/bootstrap.min.css}"
			rel="stylesheet" media="screen" />

						 <button class="button" > Global </button>
						 <button class="button" > Meine Abos    </button>

						 <button th:text="${page.user.name}" class="button active" > </button>

							<button class="toggleSearch" th:onclick="${'openSearchBar()'}" > search </button>

						<input id="searchFieldInput" type="text" placeholder="Suchen" class="searchInputField"/>
						<input type="submit" value="Suchen" th:onclick="${'searchForUsersProfile()'}" class="searchButton" data-toggle="modal" data-target="#searchResults"/>

						<button class="toggleSearch" th:onclick="${'closeSearchBar()'}" > close </button>

 Followers

 Following

						<button class="followButton" th:onclick="'follow( "' + ${page.username} + '" , " ' + ${page.user.name} + ' " )'"> Follow </button>

						<button class="followButton" th:onclick="'unfollow( "' + ${page.username} + '" , " ' + ${page.user.name} + ' " )'"> Unfollow </button>

						<form class="fakeNews">
							<textarea id="postInputArea" placeholder="Covfefe..." class="fakeNewsInput" maxlength="146"></textarea>

max. 146

								<button class="trumpit" th:onclick="'trumpIt("' + ${page.user.name} + '")'"> Trump that </button>

						</form>

Suchergebnisse

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

 Follower

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

							keyboard_arrow_right

 Abbonements

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

							keyboard_arrow_right


text:
// This file is automatically generated.

package adila.db;

/*
 * Huawei Mate 8
 *
 * DEVICE: HWNXT
 * MODEL: NXT-L29
 */
final class hwnxt_nxt2dl29 {
    public static final String DATA = "Huawei|Mate 8|";
}


text:
import React, { PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import classNames from 'classnames';
import basicClassCreator from './utils/basicClassCreator';

const propTypes = {
    align: PropTypes.oneOf(['left', 'right']),
    className: PropTypes.string,
    ripple: PropTypes.bool,
    target: PropTypes.string.isRequired,
    valign: PropTypes.oneOf(['bottom', 'top'])
};

const defaultProps = {
    align: 'left',
    valign: 'bottom'
};

// eslint-disable-next-line react/prefer-stateless-function
class Menu extends React.Component {
    componentDidMount() {
        window.componentHandler.upgradeElements(findDOMNode(this));
    }

    componentWillUnmount() {
        const elt = findDOMNode(this);

        window.componentHandler.downgradeElements(elt);

        const parent = elt.parentElement;
        const grandparent = parent && parent.parentElement;

        if (parent && grandparent && parent.classList.contains('mdl-menu__container')) {
            grandparent.replaceChild(elt, parent);
        }
    }

    render() {
        const { align, children, className, ripple,
            target, valign, ...otherProps } = this.props;

        const classes = classNames('mdl-menu mdl-js-menu', {
            [`mdl-menu--${valign}-${align}`]: true,
            'mdl-js-ripple-effect': ripple
        }, className);

        return (
            <ul className={classes} data-mdl-for={target} {...otherProps}>
                {children}
            </ul>
        );
    }
}

Menu.propTypes = propTypes;
Menu.defaultProps = defaultProps;

export default Menu;
export const MenuItem = basicClassCreator('MenuItem', 'mdl-menu__item', 'li');


text:
using System.Collections.Generic;

namespace Nancy.OAuth2.Models
{
    public class AuthorizationRequest
    {
        public string ResponseType { get; set; }
        public string ClientId { get; set; }
        public string RedirectUri { get; set; }
        public IEnumerable<string> Scope { get; set; }
        public string State { get; set; }
    }
}


text:
package org.motechproject.server.messagecampaign.service;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.motechproject.server.messagecampaign.dao.AllCampaignEnrollments;
import org.motechproject.server.messagecampaign.domain.campaign.CampaignEnrollment;
import org.motechproject.server.messagecampaign.domain.campaign.CampaignEnrollmentStatus;
import org.motechproject.server.messagecampaign.search.Criterion;

import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.util.ReflectionTestUtils.setField;

public class CampaignEnrollmentServiceTest {

    @Mock
    AllCampaignEnrollments mockAllCampaignEnrollments;
    CampaignEnrollmentService service;

    @Before
    public void setUp() {
        initMocks(this);
        service = new CampaignEnrollmentService();
        setField(service, "allCampaignEnrollments", mockAllCampaignEnrollments);
    }

    @Test
    public void shouldSaveOrUpdateEnrollmentOnRegister() {
        CampaignEnrollment enrollment = mock(CampaignEnrollment.class);
        service.register(enrollment);
        verify(mockAllCampaignEnrollments).saveOrUpdate(enrollment);
    }

    @Test
    public void shouldSetInactiveStatusForEnrollmentOnUnregister() {
        CampaignEnrollment enrollment = new CampaignEnrollment("externalId", "cccaaName");
        service.unregister(enrollment);
        assertEquals(CampaignEnrollmentStatus.INACTIVE,enrollment.getStatus());
        ArgumentCaptor<CampaignEnrollment> campaignEnrollmentCaptor = ArgumentCaptor.forClass(CampaignEnrollment.class);
        verify(mockAllCampaignEnrollments).saveOrUpdate(campaignEnrollmentCaptor.capture());
        assertThat(campaignEnrollmentCaptor.getValue().getCampaignName(), is(enrollment.getCampaignName()));
        assertThat(campaignEnrollmentCaptor.getValue().getExternalId(), is(enrollment.getExternalId()));
        assertThat(campaignEnrollmentCaptor.getValue().getStatus(), is(CampaignEnrollmentStatus.INACTIVE));
    }

    @Test
    public void shouldSetInactiveStatusForEnrollmentByUnregisterBasedOnCampaignNameAndExternalId() {

        String externalId = "newExternalId";
        String campaignName = "NewCampaignName";
        CampaignEnrollment enrollment = new CampaignEnrollment(externalId, campaignName);
        when(mockAllCampaignEnrollments.findByExternalIdAndCampaignName(externalId, campaignName)).thenReturn(enrollment);

        service.unregister(enrollment.getExternalId(), enrollment.getCampaignName());

        ArgumentCaptor<CampaignEnrollment> campaignEnrollmentCaptor = ArgumentCaptor.forClass(CampaignEnrollment.class);
        verify(mockAllCampaignEnrollments).saveOrUpdate(campaignEnrollmentCaptor.capture());
        assertThat(campaignEnrollmentCaptor.getValue().getCampaignName(), is(enrollment.getCampaignName()));
        assertThat(campaignEnrollmentCaptor.getValue().getExternalId(), is(enrollment.getExternalId()));
        assertThat(campaignEnrollmentCaptor.getValue().getStatus(), is(CampaignEnrollmentStatus.INACTIVE));
    }

    @Test
    public void shouldSearchTheCampaignEnrollmentsBasedOnTheGivenQuery() {
        Criterion primaryCriterion = mock(Criterion.class);
        List<CampaignEnrollment> primaryCriterionFilteredEnrollments = mock(List.class);
        when(primaryCriterion.fetch(mockAllCampaignEnrollments)).thenReturn(primaryCriterionFilteredEnrollments);

        Criterion secondaryCriterion1 = mock(Criterion.class);
        List<CampaignEnrollment> secondaryCriterion1FilteredEnrollments = mock(List.class);
        when(secondaryCriterion1.filter(primaryCriterionFilteredEnrollments)).thenReturn(secondaryCriterion1FilteredEnrollments);

        Criterion secondaryCriterion2 = mock(Criterion.class);
        List<CampaignEnrollment> expectedFilteredEnrollments = mock(List.class);
        when(secondaryCriterion2.filter(secondaryCriterion1FilteredEnrollments)).thenReturn(expectedFilteredEnrollments);

        CampaignEnrollmentsQuery enrollmentQuery = mock(CampaignEnrollmentsQuery.class);
        when(enrollmentQuery.getPrimaryCriterion()).thenReturn(primaryCriterion);
        when(enrollmentQuery.getSecondaryCriteria()).thenReturn(asList(secondaryCriterion1, secondaryCriterion2));

        Assert.assertEquals(expectedFilteredEnrollments, service.search(enrollmentQuery));
    }
}


text:
evaluate '05/26/2010' into :str_date1;
evaluate '05/20/2010' into :str_date2;
evaluate '11:11:11 AM 05/26/2010' into :str_timestamp1;
evaluate '11:11:11 AM 05/20/2010' into :str_timestamp2;
evaluate '11:11:11.123 AM 05/26/2010' into :str_datetime1;
evaluate '11:11:11.123 AM 05/20/2010' into :str_datetime2;

evaluate cast('05/26/2010' as date) into :date_date1;
evaluate cast('05/20/2010' as date) into :date_date2;
evaluate cast('11:11:11 AM 05/26/2010' as timestamp) into :timestamp_timestamp1;
evaluate cast('11:11:11 AM 05/20/2010' as timestamp) into :timestamp_timestamp2;
evaluate cast('11:11:11.123 AM 05/26/2010' as datetime) into :datetime_datetime1;
evaluate cast('11:11:11.123 AM 05/20/2010' as datetime) into :datetime_datetime2;

-- datediff
-- 1 string_date - string_date
prepare s from 'select datediff (?, ?) as case1 into :result'
execute s using :str_date1, :str_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case1;

-- 2 string_date - string_timestamp
prepare s from 'select datediff (?, ?) as case2 into :result'
execute s using :str_date1, :str_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case2;

-- 3 string_date - string_datetime
prepare s from 'select datediff (?, ?) as case3 into :result'
execute s using :str_date1, :str_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case3;

-- 4 string_date - date
prepare s from 'select datediff (?, ?) as case4 into :result'
execute s using :str_date1, :date_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case4;

-- 5 string_date - timestamp
prepare s from 'select datediff (?, ?) as case5 into :result'
execute s using :str_date1, :timestamp_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case5;

-- 6 string_date - datetime
prepare s from 'select datediff (?, ?) as case6 into :result'
execute s using :str_date1, :datetime_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case6;

-- 7 string_timestamp - string_date
prepare s from 'select datediff (?, ?) as case7 into :result'
execute s using :str_timestamp1, :str_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case7;

-- 8 string_timestamp - string_timestamp
prepare s from 'select datediff (?, ?) as case8 into :result'
execute s using :str_timestamp1, :str_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case8;

-- 9 string_timestamp - string_datetime
prepare s from 'select datediff (?, ?) as case9 into :result'
execute s using :str_timestamp1, :str_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case9;

-- 10 string_timestamp - date
prepare s from 'select datediff (?, ?) as case10 into :result'
execute s using :str_timestamp1, :str_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case10;

-- 11 string_timestamp - timestamp
prepare s from 'select datediff (?, ?) as case11 into :result'
execute s using :str_timestamp1, :str_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case11;

-- 12 string_timestamp - datetime
prepare s from 'select datediff (?, ?) as case12 into :result'
execute s using :str_timestamp1, :str_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case12;

-- 13 string_datetime - string_date
prepare s from 'select datediff (?, ?) as case13 into :result'
execute s using :str_datetime1, :str_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case13;

-- 14 string_datetime - string_timestamp
prepare s from 'select datediff (?, ?) as case14 into :result'
execute s using :str_datetime1, :str_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case14;

-- 15 string_datetime - string_datetime
prepare s from 'select datediff (?, ?) as case15 into :result'
execute s using :str_datetime1, :str_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case15;

-- 16 string_datetime - date
prepare s from 'select datediff (?, ?) as case16 into :result'
execute s using :str_datetime1, :date_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case16;

-- 17 string_datetime - timestamp
prepare s from 'select datediff (?, ?) as case17 into :result'
execute s using :str_datetime1, :timestamp_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case17;

-- 18 string_datetime - datetime
prepare s from 'select datediff (?, ?) as case18 into :result'
execute s using :str_datetime1, :datetime_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case18;

-- 19 date - string_date
prepare s from 'select datediff (?, ?) as case19 into :result'
execute s using :date_date1, :str_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case19;

-- 20 date - string_timestamp
prepare s from 'select datediff (?, ?) as case20 into :result'
execute s using :date_date1, :str_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case20;

-- 21 date - string_datetime
prepare s from 'select datediff (?, ?) as case21 into :result'
execute s using :date_date1, :str_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case21;

-- 22 date - date
prepare s from 'select datediff (?, ?) as case22 into :result'
execute s using :date_date1, :date_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case22;

-- 23 date - timestamp
prepare s from 'select datediff (?, ?) as case23 into :result'
execute s using :date_date1, :timestamp_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case23;

-- 24 date - datetime
prepare s from 'select datediff (?, ?) as case24 into :result'
execute s using :date_date1, :datetime_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case24;

-- 25 timestamp - string_date
prepare s from 'select datediff (?, ?) as case25 into :result'
execute s using :timestamp_timestamp1, :str_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case25;

-- 26 timestamp - string_timestamp
prepare s from 'select datediff (?, ?) as case26 into :result'
execute s using :timestamp_timestamp1, :str_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case26;

-- 27 timestamp - string_datetime
prepare s from 'select datediff (?, ?) as case27 into :result'
execute s using :timestamp_timestamp1, :str_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case27;

-- 28 timestamp - date
prepare s from 'select datediff (?, ?) as case28 into :result'
execute s using :timestamp_timestamp1, :date_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case28;

-- 29 timestamp - timestamp
prepare s from 'select datediff (?, ?) as case29 into :result'
execute s using :timestamp_timestamp1, :timestamp_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case29;

-- 30 timestamp - datetime
prepare s from 'select datediff (?, ?) as case30 into :result'
execute s using :timestamp_timestamp1, :datetime_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case30;

-- 31 datetime - string_date
prepare s from 'select datediff (?, ?) as case31 into :result'
execute s using :datetime_datetime1, :str_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case31;

-- 32 datetime - string_timestamp
prepare s from 'select datediff (?, ?) as case32 into :result'
execute s using :datetime_datetime1, :str_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case32;

-- 33 datetime - string_datetime
prepare s from 'select datediff (?, ?) as case33 into :result'
execute s using :datetime_datetime1, :str_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case33;

-- 34 datetime - date
prepare s from 'select datediff (?, ?) as case34 into :result'
execute s using :datetime_datetime1, :date_date2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case34;

-- 35 datetime - timestamp
prepare s from 'select datediff (?, ?) as case35 into :result'
execute s using :datetime_datetime1, :timestamp_timestamp2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case35;

-- 36 datetime - datetime
prepare s from 'select datediff (?, ?) as case36 into :result'
execute s using :datetime_datetime1, :datetime_datetime2
deallocate prepare s;

evaluate 6 into :expected;
select case when :expected = :result then 'YES' else 'NO' end as case36;


text:
$(document).ready(function(){
    $("#searchForm").css("background-color", $("#leftPane").css("background-color"));

		$('#customLogo').click(
        function(event) {
            $(this).attr('target', '_parent');
            return true;
        }
    );
});

/**
 * {Refactored}
 * @description Marks the current page in TOC
 * @param url - the page that is marked as selected in TOC
 */
function markSelectItem(url) {
    debug('markSelectItem(', url);
    url = normalizeLink(url);
    if ($.cookie("wh_pn") !== undefined && parseInt($.cookie("wh_pn")) > -1 && $.cookie("wh_pn") != "") {
        currentTOCSelection = parseInt($.cookie("wh_pn"));
    } else {
        currentTOCSelection = "none";
    }

    if (startsWith(url, '../')) {
        url = url.substr(url.lastIndexOf('../') + 3);
    }

    var relp = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'));
    debug('relp:' + relp);
    var toFind = url.indexOf("#") != -1 ? url.substring(0, url.indexOf("#")): url;
    debug('markSelectItem(' + toFind + ') - loaded');

    if (currentTOCSelection != "none") {
        var newloc = '#contentBlock a[href^="' + toFind + '"]';
        var closest = 65000;
        var diff = 65000;
        $(newloc).each(function () {
            if (Math.abs($(this).parents('li').index('li') - currentTOCSelection) < diff) {
                diff = Math.abs($(this).parents('li').index('li') - currentTOCSelection);
                var findIndexFor = $(this).closest('li');
                closest = $('#contentBlock li').index(findIndexFor);
            }
        });
        var loc = '#contentBlock li:eq(' + currentTOCSelection + ') a[href="' + toFind + '"]';
        if ($(loc).length == 0) {
            loc = '#contentBlock li:eq(' + closest + ') a[href="' + toFind + '"]';
        }

        if ( wh.protocol == 'https' ) {
            $.cookie('wh_pn', closest, { secure: true });
        } else {
            $.cookie('wh_pn', closest);
        }

    } else {
        var loc = '#contentBlock a[href^="' + toFind + '"]';
    }

    if ($(loc).length == 0) {
        loc = '#contentBlock a[href^="' + toFind + '"]';
    }
    log.info('search:' + toFind);
    lastLoadedPage = url;
    if (lastLoadedPage != "") {
        toggleItem($(loc).first().parent(), true);
    }
    var item = $(loc).first();
    $('#contentBlock li span').removeClass('menuItemSelected');

    showParents();
    item.parent('li span').addClass('menuItemSelected');

    // Scroll TOC to make selectedItem visible
    scrollToVisibleItem();
}


text:
{-# LANGUAGE NoImplicitPrelude #-}

{-

Chapter Exercises

A warm-up stretch

These exercises are designed to be a warm-up and get you using
some of the stuff we've learned in the last few chapters. While these
exercises comprise code fragments from "real" code, they are simpli-
fied in order to be discrete exercises. That will allow us to highlight
and practice some of the type manipulation from Traversable and
Reader, both of which are tricky.

The first simplified part is that we're going to set up some toy
data; in the real programs these are taken from, the data is coming
from somewhere else — a database, for example. We just need
some lists of numbers. We're going to use some functions from
Control.Applicative and Data.Maybe, so we'll import those at the
top of our practice file. We'll call our lists of toy data by common
variable names for simplicity.

-}

module ReaderPractice where

import Control.Applicative
  ( (<*>)
  , liftA2
  )
import Data.Bool
  ( Bool
    ( True
    )
  , (&&)
  , otherwise
  )
import Data.Eq
  ( Eq
  , (==)
  )
import Data.Foldable
  ( foldl
  )
import Data.Function
  ( ($)
  )
import Data.Functor
  ( (<$>)
  , fmap
  )
import Data.List
  ( zip
  )
import Data.Maybe
  ( Maybe
    ( Just
    , Nothing
    )
  )
import Data.Ord
  ( (>)
  , (<)
  )
import Data.Traversable
  ( sequenceA
  )
import Prelude
  ( Integer
  , Integral
  , Num
  , (+)
  , even
  )
import System.IO
 ( IO
 , print
 )

x :: [Integer]
x = [1, 2, 3]

y :: [Integer]
y = [4, 5, 6]

z :: [Integer]
z = [7, 8, 9]

{-

The next thing we want to do is write some functions that zip
those lists together and uses lookup to find the value associated with
a specified key in our zipped lists. For demonstration purposes, it's
nice to have the outputs be predictable, so we recommend writing
some that are concrete values, as well as one that can be applied to a
variable:

lookup :: Eq a => a -> [(a, b)] -> Maybe b

-- zip x and y using 3 as the lookup key
xs :: Maybe Integer
xs = undefined

-- zip y and z using 6 as the lookup key
ys :: Maybe Integer
ys = undefined

-- it's also nice to have one that
-- will return Nothing, like this one
-- zip x and y using 4 as the lookup key
zs :: Maybe Integer
zs = lookup 4 $ zip x y

-- now zip x and z using a variable lookup key
z' :: Integer -> Maybe Integer
z' n = undefined

-}

lookup :: Eq a => a -> [(a, b)] -> Maybe b
lookup _ []                         = Nothing
lookup e ((k, v) : kvs) | e == k    = Just v
                        | otherwise = lookup e kvs

-- zip x and y using 3 as the lookup key
xs :: Maybe Integer
xs = lookup 3 $ zip x y

-- zip y and z using 6 as the lookup key
ys :: Maybe Integer
ys = lookup 6 $ zip y z

-- it's also nice to have one that
-- will return Nothing, like this one
-- zip x and y using 4 as the lookup key
zs :: Maybe Integer
zs = lookup 4 $ zip x y

-- now zip x and z using a variable lookup key
z' :: Integer -> Maybe Integer
z' n = lookup n $ zip x z

{-

Now we want to add the ability to make a Maybe (,) of values using
Applicative. Have x1 make a tuple of xs and ys, and x2 make a tuple of
of ys and zs. Also, write x3 which takes one input and makes a tuple
of the results of two applications of z' from above.

x1 :: Maybe (Integer, Integer)
x1 = undefined

x2 :: Maybe (Integer, Integer)
x2 = undefined

x3 :: Integer -> (Maybe Integer, Maybe Integer)
x3 = undefined

Your outputs from those should look like this:

*ReaderPractice> x1
Just (6,9)

*ReaderPractice> x2
Nothing

*ReaderPractice> x3 3
(Just 9,Just 9)

-}

x1 :: Maybe (Integer, Integer)
x1 = liftA2 (,) xs ys

x2 :: Maybe (Integer, Integer)
x2 = liftA2 (,) ys zs

x3 :: Integer -> (Maybe Integer, Maybe Integer)
x3 = liftA2 (,) z' z'

{-

Next, we're going to make some helper functions. Let's use uncurry
to allow us to add the two values that are inside a tuple:

uncurry :: (a -> b -> c) -> (a, b) -> c

-- that first argument is a function
-- in this case, we want it to be addition
-- summed is just uncurry with addition as
-- the first argument
summed :: Num c => (c, c) -> c
summed = undefined

-}

uncurry :: (a -> b -> c) -> (a, b) -> c
uncurry f (x', y') = f x' y'

-- that first argument is a function
-- in this case, we want it to be addition
-- summed is just uncurry with addition as
-- the first argument
summed :: Num c => (c, c) -> c
summed = uncurry (+)

{-

And now we'll make a function similar to some we've seen before
that lifts a boolean function over two partially-applied functions:

-- use &&, >3, <8
bolt :: Integer -> Bool
bolt = undefined

-}

bolt :: Integer -> Bool
bolt = liftA2 (&&) (> 3) (< 8)

{-

Finally, we'll be using fromMaybe in the main exercise, so let's look
at that:

fromMaybe :: a -> Maybe a -> a

You give it a default value and a Maybe value. If the Maybe value
is a Just a, it will return the a value. If the Maybe value is a Nothing,
it returns the default value instead:

*ReaderPractice> fromMaybe 0 xs
6

*ReaderPractice> fromMaybe 0 zs
0

-}

fromMaybe :: a -> Maybe a -> a
fromMaybe d Nothing   = d
fromMaybe _ (Just x') = x'

{-

Now we'll cobble together a main function, so that in one function
call we can execute several things at once.

main :: IO ()
main = do print $ sequenceA [Just 3, Just 2, Just 1]
          print $ sequenceA [x, y]
          print $ sequenceA [xs, ys]
          print $ summed <$> ((,) <$> xs <*> ys)
          print $ fmap summed ((,) <$> xs <*> zs)
          print $ bolt 7
          print $ fmap bolt z

When you run this in GHCi, your results should look like this:

*ReaderPractice> main
Just [3,2,1]
[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]
Just [6,9]
Just 15
Nothing
True
[True,False,False]

-}

main                                            :: IO ()
main = do print $ sequenceA [Just 3             :: Maybe Integer, Just 2, Just 1]
          print $ sequenceA [x, y]
          print $ sequenceA [xs, ys]
          print $ summed <$> ((,) <$> xs <*> ys)
          print $ fmap summed ((,) <$> xs <*> zs)
          print $ bolt 7
          print $ fmap bolt z
          --
          print $ sequenceA [(> 3), (< 8), even :: Integer -> Bool] 7
          --
          print $ foldl (&&) True $ sequA (7    :: Integer)
          print $ sequA $ fromMaybe 0 s'
          print $ bolt $ fromMaybe 0 ys

{-

Next, we're going to add one that combines sequenceA and Reader
in a somewhat surprising way (add this to your main function):

print $ sequenceA [(>3), (<8), even] 7

The type of sequenceA is
sequenceA :: (Applicative f, Traversable t) => t (f a) -> f (t a)
-- so in this:
sequenceA [(>3), (<8), even] 7
-- f ~ (->) a and t ~ []

We have a Reader for the Applicative (functions) and a traversable
for the list. Pretty handy. We're going to call that function sequA for
the purposes of the following exercises:

sequA :: Integral a => a -> [Bool]
sequA m = sequenceA [(>3), (<8), even] m

-}

sequA :: Integral a => a -> [Bool]
sequA = sequenceA [(> 3), (< 8), even]

{-

And henceforth let

summed <$> ((,) <$> xs <*> ys)

be known as s'.

-}

s' :: Maybe Integer
s' = summed <$> ((,) <$> xs <*> ys)

{-

OK, your turn. Within the main function above, write the following
(you can delete everything after do now if you prefer — just remember
to use print to be able to print the results of what you're adding):

1. fold the boolean conjunction operator over the list of results of
sequA (applied to some value).

2. apply sequA to s'; you'll need fromMaybe.

3. apply bolt to ys; you'll need fromMaybe.

-}


text:
package jp.ddo.chiroru.sqllogger.proxy;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

import jp.ddo.chiroru.sqllogger.model.LogInfo;
import jp.ddo.chiroru.sqllogger.model.Query;

public class PreparedStatementProxyStrategy
extends AbstractProxyStrategy
implements ProxyStrategy {

    private Long startTime;

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

    public PreparedStatementProxyStrategy(Object target, LogInfo logInfo) {
        super(target, logInfo);
        enwrapTargetMethodName.add("executeQuery");
        enwrapTargetMethodName.add("executeUpdate");
        enwrapTargetMethodName.add("execute");
        enwrapTargetMethodName.add("executeBatch");
        enwrapTargetMethodName.add("setInt");
        enwrapTargetMethodName.add("setString");
    }

    @Override
    public boolean isProxyMethod(String methodName) {
        if (enwrapTargetMethodName.contains(methodName))
            return true;

        return false;
    }

    @Override
    protected void preProcess(Method method, Object[] arguments) {
        startTime = System.currentTimeMillis();
        if (method.getName().matches("^set.*")) {
            Query q = logInfo.getQuery();
            q.putParameter(arguments[0], arguments[1]);
        }
    }

    @Override
    protected void postProcess(Method method, Object[] arguments) {
        long elapsed = System.currentTimeMillis() - startTime;
        if (!method.getName().matches("^set.*")) {
            logInfo.setElapsed(elapsed);
            logInfo.setExecuteQuery(true);
        }
    }

    @Override
    protected Object enwrapTarget(Object o, Method method) {
        if (method.getName().equals("executeQuery")) {
            return ProxyFactory.getProxy(traceId, ResultSet.class, (ResultSet)o, new ResultSetProxyStrategy(o, logInfo));
        }

        return o;
    }

}


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

    <groupId>it.unibo.cesop.demo</groupId>
    <artifactId>CESOPSemanticSearch</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>CESOPSemanticSearch</name>

    <build>
        <finalName>CESOPSemanticSearch</finalName>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <!-- Make this jar executable -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>it.unibo.cesop.demo.Programma</mainClass>
                            <classpathPrefix>dependency-jars/</classpathPrefix>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

            <!-- Copy project dependency -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!-- exclude junit, we need runtime dependency only -->
                            <includeScope>runtime</includeScope>
                            <outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

    <dependencies>

        <!--SPARK WEB SERVER -->
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>2.5.5</version>
        </dependency>

        <!-- Google GSON -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

        <!-- Jade HTML Render -->
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-template-jade</artifactId>
            <version>2.5.5</version>
        </dependency>

        <!-- SolrJ -->
        <!-- <dependency>
            <artifactId>solr-solrj</artifactId>
            <groupId>org.apache.solr</groupId>
            <version>1.4.1</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>-->

        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>6.6.0</version>
        </dependency>

    </dependencies>

</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Text;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Xml;
using System.Security.Cryptography.Xml;

namespace OpenF2.AppCode
{
    class SAMLValidator
    {
        private static string SAML2_PROTOCOL_NS = "urn:oasis:names:tc:SAML:2.0:protocol";

        private static bool SignatureIsTrustedAndValid(XmlDocument doc)
        {
            SignedXml sxml = new SignedXml(doc);
            XmlNodeList nodeList = doc.GetElementsByTagName("Signature", "http://www.w3.org/2000/09/xmldsig#");
            if (nodeList.Count <= 0)
            {
                throw new CryptographicException("Verification failed: No Signature was found in the document.");
            }
            if (nodeList.Count >= 2)
            {
                throw new CryptographicException("Verification failed: More that one signature was found for the document.");
            }

            XmlElement certificateElem = (XmlElement)doc.GetElementsByTagName("X509Certificate")[0];
            string certificate = certificateElem.InnerText;

            byte[] certData = Convert.FromBase64String(certificate);
            X509Certificate2 cert = new X509Certificate2(certData);
            PublicKey pk = cert.PublicKey;

            sxml.LoadXml((XmlElement)nodeList[0]);

            // create certificate
            return sxml.CheckSignature(cert, true);
        }
        public static bool IsValid(XmlDocument doc)
        {
            XmlElement docElement = doc.DocumentElement;
            if (docElement.NamespaceURI != SAML2_PROTOCOL_NS || docElement.LocalName != "Response")
            {
                throw new CryptographicException("Invalid response structure");
            }
            return SignatureIsTrustedAndValid(doc);
        }

    }
}


text:
@interface JKSubTagViewController : UITableViewController

@end


text:
My instances represent IEEE-754 floating-point double-precision numbers.  They have about 16 digits of accuracy and their range is between plus and minus 10^307. Some valid examples are:

	8.0 13.3 0.3 2.5e6 1.27e-30 1.27e-31 -12.987654e12

Mainly: no embedded blanks, little e for tens power, and a digit on both sides of the decimal point.  It is actually possible to specify a radix for Float constants.  This is great for teaching about numbers, but may be confusing to the average reader:

	3r20.2 --> 6.66666666666667
	8r20.2 --> 16.25

If you don't have access to the definition of IEEE-754, you can figure out what is going on by printing various simple values in Float hex.  It may help you to know that the basic format is...
	sign		1 bit
	exponent	11 bits with bias of 1023 (16r3FF) to produce an exponent
						in the range -1023 .. +1024
				- 16r000:
					significand = 0: Float zero
					significand ~= 0: Denormalized number (exp = -1024, no hidden '1' bit)
				- 16r7FF:
					significand = 0: Infinity
					significand ~= 0: Not A Number (NaN) representation
	mantissa	53 bits, but only 52 are stored (20 in the first word, 32 in the second).  This is because a normalized mantissa, by definition, has a 1 to the right of its floating point, and IEEE-754 omits this redundant bit to gain an extra bit of precision instead.  People talk about the mantissa without its leading one as the FRACTION, and with its leading 1 as the SIGNFICAND.

The single-precision format is...
	sign		1 bit
	exponent	8 bits, with bias of 127, to represent -126 to +127
                    - 0x0 and 0xFF reserved for Float zero (mantissa is ignored)
                    - 16r7F reserved for Float underflow/overflow (mantissa is ignored)
	mantissa	24 bits, but only 23 are stored
This format is used in FloatArray (qv), and much can be learned from the conversion routines, Float asIEEE32BitWord, and Float class fromIEEE32Bit:.

Thanks to Rich Harmon for asking many questions and to Tim Olson, Bruce Cohen, Rick Zaccone and others for the answers that I have collected here.


text:
convert -size 32x32 xc:#7f7f7f gray1.png
convert -size 32x32 xc:#3f3f3f darkgray1.png
convert -size 32x32 xc:#ffffff white.png
convert -size 32x32 xc:#ff0000 red.png
convert -size 32x32 xc:#7f7fff lightblue.png
convert -size 32x32 xc:#0000ff darkblue.png
convert -size 32x32 xc:#00ff00 brightgreen.png
convert -size 32x32 xc:#007f00 darkgreen.png
convert -size 32x32 xc:#7f0000 darkred.png
convert -size 32x32 xc:#ff00ff pink.png
convert -size 32x32 xc:#ffff00 yellow.png
convert -size 32x32 xc:#00ffff cyan.png

montage gray1.png darkgray1.png white.png red.png lightblue.png darkblue.png brightgreen.png darkgreen.png darkred.png pink.png yellow.png cyan.png -geometry 32x32 -tile 15x1 test.png