text:
/* $Id: alist.h,v 1.10 2007/08/28 07:20:43 tbox Exp $ */

#ifndef ISCCC_ALIST_H
#define ISCCC_ALIST_H 1

/*! \file isccc/alist.h */

#include <stdio.h>

#include <isc/lang.h>
#include <isccc/types.h>

ISC_LANG_BEGINDECLS

isccc_sexpr_t *
isccc_alist_create(void);

isc_boolean_t
isccc_alist_alistp(isccc_sexpr_t *alist);

isc_boolean_t
isccc_alist_emptyp(isccc_sexpr_t *alist);

isccc_sexpr_t *
isccc_alist_first(isccc_sexpr_t *alist);

isccc_sexpr_t *
isccc_alist_assq(isccc_sexpr_t *alist, const char *key);

void
isccc_alist_delete(isccc_sexpr_t *alist, const char *key);

isccc_sexpr_t *
isccc_alist_define(isccc_sexpr_t *alist, const char *key, isccc_sexpr_t *value);

isccc_sexpr_t *
isccc_alist_definestring(isccc_sexpr_t *alist, const char *key, const char *str);

isccc_sexpr_t *
isccc_alist_definebinary(isccc_sexpr_t *alist, const char *key, isccc_region_t *r);

isccc_sexpr_t *
isccc_alist_lookup(isccc_sexpr_t *alist, const char *key);

isc_result_t
isccc_alist_lookupstring(isccc_sexpr_t *alist, const char *key, char **strp);

isc_result_t
isccc_alist_lookupbinary(isccc_sexpr_t *alist, const char *key, isccc_region_t **r);

void
isccc_alist_prettyprint(isccc_sexpr_t *sexpr, unsigned int indent, FILE *stream);

ISC_LANG_ENDDECLS

#endif /* ISCCC_ALIST_H */


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

		 <!--
		 			This package contains the model driven version of the Register action.  We have separated it into
		 			a separate package for the sake of clarity.  Note, we are extending the chapterThreePublic package
		 			so that we can inherit all of the components.  We will reuse many of them.  We merely want to
		 			take advantage of the modularization of Struts 2 to make the sample code more clear.  Note also
		 			that we are still  using the same namespace as in the original chapter three version.
		 -->

    <package name="chapterThreeModelDriven" namespace="/chapterThree" extends="chapterThreePublic">

      	<action name="RegistrationMD" >
					<result>/chapterThree/Registration_MD.jsp</result>
        </action>

        <action name="RegisterMD" class="manning.chapterThree.modelDriven.ModelDrivenRegister">
					<result>/chapterThree/RegistrationSuccess.jsp</result>
					<result name="input">/chapterThree/Registration_MD.jsp</result>
        </action>

     </package>

</struts>

redpajama_set_name: RedPajamaGithub


text:
class CreateConferenceCalls < ActiveRecord::Migration
  def change
    create_table :conference_calls do |t|
      t.string :code, :unique => true

      t.timestamps
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Sect. sci. Acad. roum. 22: 93 (1939)

#### Original name
Puccinia callistephi Savul.

### Remarks
null


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.badrobot.commands;

import com.badrobot.BadPreferences;
import com.badrobot.OI;
import edu.wpi.first.wpilibj.Utility;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.tables.ITable;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Drives the robot in a straight line (using the gyro) for either
 * the set amount of time or the default time.
 *
 * @author Isaac
 */
public class DriveStraightForward extends BadCommand
{
    double bearing;
    static double DRIVE_SPEED;
    static String driveSpeedKey = "CLIMBING_DRIVE_SPEED";
    static double Kp = .05;

    public double setSpeed;
    public double dontEatTheMotors;
    public double gyroAngle;
    private double scaleFactor;
    private long startTime;
    private long driveTime;
    private double distance = 0;

    public int state = DRIVING_STRAIGHT;
    public static final int DRIVING_STRAIGHT = 0,
                            TURNING_RIGHT = 1,
                            TURNING_LEFT = 2,
                            FINISHED = 3;

    /**
     * Runs the command for the default time length.
     */
    public DriveStraightForward()
    {
        requires((Subsystem) driveTrain);
        driveTime = 5*1000000;
    }

    /**
     * Runs the command for the set time length.
     * @param setTime Time length in seconds.
     */
    public DriveStraightForward(double setTime)
    {
        long temp = (long) setTime*1000000;
        driveTime = temp;
        distance = -1;
    }

    public DriveStraightForward(double setTime, double distanceInInches)
    {
        driveTime = -1;
        distance = distanceInInches;
    }

    public String getConsoleIdentity()
    {
        return "DriveStraightForward";
    }

    double delayTime;
    protected void initialize()
    {
        setSpeed = .8;
        scaleFactor = 1;

        //driveTrain.getGyro().reset();
        bearing = driveTrain.getGyro().getAngle();
        startTime = Utility.getFPGATime();      //returns fpga time in MICROseconds.

        DRIVE_SPEED = Double.parseDouble(BadPreferences.getValue(driveSpeedKey, ".8"));
        delayTime = Double.parseDouble(BadPreferences.getValue("DRIVE_STRAIGHT_FORWARD_WITH_DISTANCE_DELAY", "2.4"));

    }

    private int lockedOnIterations = 0;
    protected void execute()
    {
        //with time
        if (distance <= 0)
        {

            driveTrain.getTrain().drive(DRIVE_SPEED,
                    -(driveTrain.getGyro().getAngle() - bearing) * Kp);
        }

        //with distance
        else
        {
            if (driveTrain.getDistanceToWall() < distance && Utility.getFPGATime() - startTime > delayTime*1000000)
            {
                lockedOnIterations++;
            }
            else
            {
                if (lockedOnIterations > 0)
                    lockedOnIterations = 0;

                    driveTrain.getTrain().drive(DRIVE_SPEED,
                            -(driveTrain.getGyro().getAngle() - bearing) * Kp);

            }
        }
    }

    protected boolean isFinished()
    {

        //if by time
        if (driveTime > 0 && Utility.getFPGATime() >= startTime + driveTime)
        {
            driveTrain.tankDrive(0, 0);
            state = FINISHED;
            return true;
        }
        else if (distance > 0 && driveTrain.getDistanceToWall() <= distance && lockedOnIterations >= 3)
        {
            return true;
        }

        return false;
    }

    protected void end()
    {
        driveTrain.tankDrive(0,0);
    }

    protected void interrupted()
    {

    }

    public void valueChanged(ITable itable, String key, Object value, boolean bln) {
    }

    protected void addNetworkTableValues(ITable table) {
    }

    public void registerPreferencesValues()
    {
    }
}


text:
/*
 * Jicofo, the Jitsi Conference Focus.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jitsi.jicofo.osgi;

import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.device.*;
import org.jitsi.impl.neomedia.transform.csrc.*;
import org.jitsi.impl.neomedia.transform.srtp.*;
import org.jitsi.impl.osgi.framework.*;
import org.jitsi.service.configuration.*;

import org.osgi.framework.*;

import java.util.*;

/**
 * Represents the entry point of the OSGi environment of the Jitsi Meet
 * conference focus application.
 *
 * @author Pawel Domas
 */
public class OSGi
{
    /**
     * Indicates whether 'mock' protocol providers should be used instead of
     * original Jitsi protocol providers. For the purpose of unit testing.
     */
    private static boolean useMockProtocols = false;

    /**
     * The <tt>OSGiLauncher</tt> instance which
     * represents the launched OSGi instance.
     */
    private static OSGiLauncher launcher;

    /**
     * <tt>BundleActivator</tt> bundle activator launched on startup/shutdown of
     * the OSGi system.
     */
    private static BundleActivator activator;

    /**
     * The locations of the OSGi bundles (or rather of the class files of their
     * <tt>BundleActivator</tt> implementations) comprising Jitsi Meet Focus.
     * An element of the <tt>BUNDLES</tt> array is an array of <tt>String</tt>s
     * and represents an OSGi start level.
     */
    private static String[][] getBUNDLES()
    {

        String[] protocols =
            {
                "org/jitsi/impl/protocol/xmpp/XmppProtocolActivator"
            };

        String[] mockProtocols =
            {
                "mock/MockActivator"
            };

        String[][] bundles = {
            {
                "net/java/sip/communicator/impl/libjitsi/LibJitsiActivator"
            },
            {
                "net/java/sip/communicator/util/UtilActivator",
                //"net/java/sip/communicator/impl/fileaccess/FileAccessActivator"
            },
            {
                "net/java/sip/communicator/impl/configuration/ConfigurationActivator"
            },
            {
                //"net/java/sip/communicator/impl/resources/ResourceManagementActivator"
            },
            {
                //"net/java/sip/communicator/impl/dns/DnsUtilActivator"
            },
            {
                "net/java/sip/communicator/impl/credentialsstorage/CredentialsStorageActivator"
            },
            {
                "net/java/sip/communicator/impl/netaddr/NetaddrActivator"
            },
            {
                //"net/java/sip/communicator/impl/packetlogging/PacketLoggingActivator"
            },
            {
                //"net/java/sip/communicator/service/gui/internal/GuiServiceActivator"
            },
            {
                "net/java/sip/communicator/service/protocol/media/ProtocolMediaActivator"
            },
            {
                //"net/java/sip/communicator/service/notification/NotificationServiceActivator",
                //"net/java/sip/communicator/impl/globaldisplaydetails/GlobalDisplayDetailsActivator"
            },
            useMockProtocols
                ? new String[]
                    {
                        "mock/media/MockMediaActivator"
                    }
                : new String[]
                    {
                        //"net/java/sip/communicator/impl/neomedia/NeomediaActivator"
                    },
            {
                //"net/java/sip/communicator/impl/certificate/CertificateVerificationActivator"
            },
            {
                //"net/java/sip/communicator/impl/version/VersionActivator"
            },
            {
                "net/java/sip/communicator/service/protocol/ProtocolProviderActivator"
            },
            {
                "net/java/sip/communicator/plugin/reconnectplugin/ReconnectPluginActivator"
            },
            // Shall we use mock protocol providers ?
            useMockProtocols ? mockProtocols : protocols,
            {
                "org/jitsi/jicofo/FocusBundleActivator"
            },
            {
                "org/jitsi/videobridge/log/LoggingBundleActivator"
            },
            useMockProtocols
                ? new String[] { "mock/MockMainMethodActivator" }
                : new String[] { }
        };

        return bundles;
    }

    static
    {
        /*
         * Before we start OSGi and, more specifically, the very Jitsi
         * Videobridge application, set the default values of the System
         * properties which affect the (optional) behavior of the application.
         */
        setSystemPropertyDefaults();
    }

    /**
     * Sets default values on <tt>System</tt> properties which affect the
     * (optional) behavior of the Jitsi Videobridge application and the
     * libraries that it utilizes. Because <tt>ConfigurationServiceImpl</tt>
     * will override <tt>System</tt> property values, the set default
     * <tt>System</tt> property values will not prevent the user from overriding
     * them.
     */
    private static void setSystemPropertyDefaults()
    {
        /*
         * XXX A default System property value specified bellow will eventually
         * be set only if the System property in question does not have a value
         * set yet.
         */

        Map<String,String> defaults = new HashMap<String,String>();
        String true_ = Boolean.toString(true);
        String false_ = Boolean.toString(false);

        /*
         * The design at the time of this writing considers the configuration
         * file read-only (in a read-only directory) and provides only manual
         * editing for it.
         */
        defaults.put(
                ConfigurationService.PNAME_CONFIGURATION_FILE_IS_READ_ONLY,
                true_);

        defaults.put(
                DeviceConfiguration.PROP_AUDIO_SYSTEM,
                AudioSystem.LOCATOR_PROTOCOL_AUDIOSILENCE);

        defaults.put(
                MediaServiceImpl.DISABLE_VIDEO_SUPPORT_PNAME,
                true_);

        // It makes no sense for Jitsi Videobridge to pace its RTP output.
        defaults.put(
                DeviceConfiguration.PROP_VIDEO_RTP_PACING_THRESHOLD,
                Integer.toString(Integer.MAX_VALUE));

        /*
         * XXX Explicitly support JitMeet by default because is is the primary
         * use case of Jitsi Videobridge right now.
         */
        defaults.put(
                SsrcTransformEngine
                    .DROP_MUTED_AUDIO_SOURCE_IN_REVERSE_TRANSFORM,
                true_);
        defaults.put(SRTPCryptoContext.CHECK_REPLAY_PNAME, false_);

        for (Map.Entry<String,String> e : defaults.entrySet())
        {
            String key = e.getKey();

            if (System.getProperty(key) == null)
                System.setProperty(key, e.getValue());
        }
    }

    /**
     * Indicates whether mock protocol providers should be used instead of
     * original Jitsi protocol providers.
     */
    public static boolean isUseMockProtocols()
    {
        return useMockProtocols;
    }

    /**
     * Make OSGi use mock protocol providers instead of original Jitsi protocols
     * implementation.
     * @param useMockProtocols <tt>true</tt> if Jitsi protocol providers should
     *                         be replaced with mock version.
     */
    public static void setUseMockProtocols(boolean useMockProtocols)
    {
        OSGi.useMockProtocols = useMockProtocols;
    }

    /**
     * Starts the OSGi infrastructure.
     *
     * @param activator the <tt>BundleActivator</tt> that will be launched after
     *                  OSGi starts.
     */
    public static synchronized void start(BundleActivator activator)
    {
        if (OSGi.activator != null)
            throw new IllegalStateException("activator");

        OSGi.activator = activator;

        if (launcher == null)
        {
            launcher = new OSGiLauncher(getBUNDLES());
        }

        launcher.start(activator);
    }

    /**
     * Stops the Jitsi Meet Focus bundles and the OSGi implementation.
     *
     * The <tt>BundleActivator</tt> that has been passed to
     * {@link #start(BundleActivator)} will be launched after shutdown.
     */
    public static synchronized void stop()
    {
        if (launcher != null && activator != null)
        {
            launcher.stop(activator);

            activator = null;
        }
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package astar;

/**
 *
 * @author Pubudu
 */
public class Grid {
    public static final int SIZE = 5;
    public static final int SCALE = 1;
    private final Coordinate grid[][];

    public Grid() {
        grid = new Coordinate[5][5]; // size * (size - i) - (size-1-j)
//        for (int i = 0; i < SIZE; i++) {
//            for (int j = 0; j < SIZE; j++) {
//                System.out.printf("%2d ",SIZE * (SIZE - i) - (SIZE - 1 - j));
//            }
//            System.out.println();
//        }
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                grid[i][j] = new Coordinate(i, j);
            }
        }
    }

    public int getHeuristicValue(Coordinate current, Coordinate goal) {
        /* If either of the 2 coordinates are out of range of the grid, return -1 */
        if(!(isWithinRange(current) && isWithinRange(goal)))
            return -1;

        int drow = Math.abs(goal.row - current.row);
        int dcol = Math.abs(goal.col - current.col);

        return SCALE * (drow + dcol);
    }

    public boolean isWithinRange(Coordinate pos) {
        return (pos.row < SIZE) && (pos.row >= 0) && (pos.col >= 0) && (pos.col < SIZE);
    }

    public boolean isWithinRange(int row, int col) {
        return (row < SIZE) && (row >= 0) && (col >= 0) && (col < SIZE);
    }

    public int getVertexNo(Coordinate node) {
        return SIZE * (SIZE - node.row) - (SIZE - 1 - node.col);
    }

    public Coordinate getCoordinate(int vertexNo) {
        int row, col;

        if(vertexNo % SIZE != 0){
            row = SIZE - 1 - vertexNo / SIZE ;
            col = vertexNo % SIZE - 1;
        }
        else {
            row = SIZE - vertexNo / SIZE;
            col = SIZE - 1;
        }

        return isWithinRange(row, col) ? grid[row][col] : null;
    }

    public Coordinate getCoordinate(int row, int col) {
        return isWithinRange(row, col) ? grid[row][col] : null;
    }
}


text:
"""Entry point for the tej utility.
"""

from __future__ import unicode_literals

import argparse
import codecs
import functools
import locale
import logging
import sys

from tej import __version__ as tej_version
from tej.errors import Error, JobNotFound
from tej.submission import DEFAULT_TEJ_DIR, RemoteQueue

logger = logging.getLogger('tej')

def setup_logging(verbosity):
    levels = [logging.CRITICAL, logging.WARNING, logging.INFO, logging.DEBUG]
    level = levels[min(verbosity, 3)]

    fmt = "%(asctime)s %(levelname)s: %(message)s"
    formatter = logging.Formatter(fmt)

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

    logging.getLogger().addHandler(handler)
    logger.setLevel(level)

    # Prints output from server to stderr
    server = logging.getLogger('tej.server')
    server.propagate = False
    raw_console = logging.StreamHandler(sys.stderr)
    raw_console.setFormatter(logging.Formatter('%(message)s'))
    server.addHandler(raw_console)

def needs_job_id(f):
    @functools.wraps(f)
    def wrapped(args):
        if args.id is None:
            logger.critical("Missing job identifier")
            sys.exit(1)
        return f(args)
    return wrapped

def _setup(args):
    queue = RemoteQueue(args.destination, args.queue,
                        setup_runtime=args.runtime)
    queue.setup(args.make_link, args.force, args.only_links)

def _submit(args):
    queue = RemoteQueue(args.destination, args.queue)
    job_id = queue.submit(args.id, args.directory, args.script)
    print(job_id)

@needs_job_id
def _status(args):
    try:
        queue = RemoteQueue(args.destination, args.queue)
        status, directory, arg = queue.status(args.id)
        if status == RemoteQueue.JOB_DONE:
            sys.stdout.write("finished")
        elif status == RemoteQueue.JOB_RUNNING:
            sys.stdout.write("running")
        else:  # pragma: no cover
            raise RuntimeError("Got unknown job status %r" % status)
        if arg is not None:
            sys.stdout.write(' %s' % arg)
        sys.stdout.write('\n')
    except JobNotFound:
        print("not found")

@needs_job_id
def _download(args):
    RemoteQueue(args.destination, args.queue).download(args.id, args.files,
                                                       directory='.')

@needs_job_id
def _kill(args):
    RemoteQueue(args.destination, args.queue).kill(args.id)

@needs_job_id
def _delete(args):
    RemoteQueue(args.destination, args.queue).delete(args.id)

def _list(args):
    for job_id, info in RemoteQueue(args.destination, args.queue).list():
        sys.stdout.write("%s %s\n" % (job_id, info['status']))

def main():
    """Entry point when called on the command-line.
    """
    # Locale
    locale.setlocale(locale.LC_ALL, '')

    # Encoding for output streams
    if str == bytes:  # PY2
        writer = codecs.getwriter(locale.getpreferredencoding())
        o_stdout, o_stderr = sys.stdout, sys.stderr
        sys.stdout = writer(sys.stdout)
        sys.stdout.buffer = o_stdout
        sys.stderr = writer(sys.stderr)
        sys.stderr.buffer = o_stderr
    else:  # PY3
        sys.stdin = sys.stdin.buffer

    # Parses command-line

    # Runtime to setup
    def add_runtime_option(opt):
        opt.add_argument(
            '-r', '--runtime', action='store',
            help="runtime to deploy on the server if the queue doesn't exist. "
                 "If unspecified, will auto-detect what is appropriate, and "
                 "fallback on 'default'.")

    # Destination selection
    def add_destination_option(opt):
        opt.add_argument('destination', action='store',
                         help="Machine to SSH into; [user@]host[:port]")
        opt.add_argument('--queue', action='store', default=DEFAULT_TEJ_DIR,
                         help="Directory for tej's files")

    # Root parser
    parser = argparse.ArgumentParser(
        description="Trivial Extensible Job-submission")
    parser.add_argument('--version', action='version',
                        version="tej version %s" % tej_version)
    parser.add_argument('-v', '--verbose', action='count', default=1,
                        dest='verbosity',
                        help="augments verbosity level")
    subparsers = parser.add_subparsers(title="commands", metavar='')

    # Setup action
    parser_setup = subparsers.add_parser(
        'setup',
        help="Sets up tej on a remote machine")
    add_destination_option(parser_setup)
    add_runtime_option(parser_setup)
    parser_setup.add_argument('--make-link', action='append',
                              dest='make_link')
    parser_setup.add_argument('--make-default-link', action='append_const',
                              dest='make_link', const=DEFAULT_TEJ_DIR)
    parser_setup.add_argument('--force', action='store_true')
    parser_setup.add_argument('--only-links', action='store_true')
    parser_setup.set_defaults(func=_setup)

    # Submit action
    parser_submit = subparsers.add_parser(
        'submit',
        help="Submits a job to a remote machine")
    add_destination_option(parser_submit)
    add_runtime_option(parser_submit)
    parser_submit.add_argument('--id', action='store',
                               help="Identifier for the new job")
    parser_submit.add_argument('--script', action='store',
                               help="Relative name of the script in the "
                                    "directory")
    parser_submit.add_argument('directory', action='store',
                               help="Job directory to upload")
    parser_submit.set_defaults(func=_submit)

    # Status action
    parser_status = subparsers.add_parser(
        'status',
        help="Gets the status of a job")
    add_destination_option(parser_status)
    parser_status.add_argument('--id', action='store',
                               help="Identifier of the running job")
    parser_status.set_defaults(func=_status)

    # Download action
    parser_download = subparsers.add_parser(
        'download',
        help="Downloads files from finished job")
    add_destination_option(parser_download)
    parser_download.add_argument('--id', action='store',
                                 help="Identifier of the job")
    parser_download.add_argument('files', action='store',
                                 nargs=argparse.ONE_OR_MORE,
                                 help="Files to download")
    parser_download.set_defaults(func=_download)

    # Kill action
    parser_kill = subparsers.add_parser(
        'kill',
        help="Kills a running job")
    add_destination_option(parser_kill)
    parser_kill.add_argument('--id', action='store',
                             help="Identifier of the running job")
    parser_kill.set_defaults(func=_kill)

    # Delete action
    parser_delete = subparsers.add_parser(
        'delete',
        help="Deletes a finished job")
    add_destination_option(parser_delete)
    parser_delete.add_argument('--id', action='store',
                               help="Identifier of the finished job")
    parser_delete.set_defaults(func=_delete)

    # List action
    parser_list = subparsers.add_parser(
        'list',
        help="Lists remote jobs")
    add_destination_option(parser_list)
    parser_list.set_defaults(func=_list)

    args = parser.parse_args()
    setup_logging(args.verbosity)

    try:
        args.func(args)
    except Error as e:
        # No need to show a traceback here, this is not an internal error
        logger.critical(e)
        sys.exit(1)
    sys.exit(0)

if __name__ == '__main__':  # pragma: no cover
    main()


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from abc import abstractmethod

from ansible.plugins import AnsiblePlugin

class HttpApiBase(AnsiblePlugin):
    def __init__(self, connection):
        super(HttpApiBase, self).__init__()

        self.connection = connection
        self._become = False
        self._become_pass = ''

    def set_become(self, become_context):
        self._become = become_context.become
        self._become_pass = getattr(become_context, 'become_pass') or ''

    def login(self, username, password):
        """Call a defined login endpoint to receive an authentication token.

        This should only be implemented if the API has a single endpoint which
        can turn HTTP basic auth into a token which can be reused for the rest
        of the calls for the session.
        """
        pass

    def logout(self):
        """ Call to implement session logout.

        Method to clear session gracefully e.g. tokens granted in login
        need to be revoked.
        """
        pass

    def update_auth(self, response, response_text):
        """Return per-request auth token.

        The response should be a dictionary that can be plugged into the
        headers of a request. The default implementation uses cookie data.
        If no authentication data is found, return None
        """
        cookie = response.info().get('Set-Cookie')
        if cookie:
            return {'Cookie': cookie}

        return None

    def handle_httperror(self, exc):
        """Overridable method for dealing with HTTP codes.

        This method will attempt to handle known cases of HTTP status codes.
        If your API uses status codes to convey information in a regular way,
        you can override this method to handle it appropriately.

        :returns:
            * True if the code has been handled in a way that the request
            may be resent without changes.
            * False if the error cannot be handled or recovered from by the
            plugin. This will result in the HTTPError being returned to the
            caller to deal with as appropriate.
            * Any other value returned is taken as a valid response from the
            server without making another request. In many cases, this can just
            be the original exception.
            """
        if exc.code == 401 and self.connection._auth:
            # Stored auth appears to be invalid, clear and retry
            self.connection._auth = None
            self.login(self.connection.get_option('remote_user'), self.connection.get_option('password'))
            return True

        return exc

    @abstractmethod
    def send_request(self, data, **message_kwargs):
        """Prepares and sends request(s) to device."""
        pass


text:
[![Build Status](https://travis-ci.org/MartinThoma/pysec.svg?branch=master)](https://travis-ci.org/MartinThoma/pysec)
[![Coverage Status](https://img.shields.io/coveralls/MartinThoma/pysec.svg)](https://coveralls.io/r/MartinThoma/pysec?branch=master)
[![Documentation Status](http://img.shields.io/badge/docs-latest-brightgreen.svg)](http://pythonhosted.org/pysec)
[![Code Health](https://landscape.io/github/MartinThoma/pysec/master/landscape.svg)](https://landscape.io/github/MartinThoma/pysec/master)

## pysec
A tool which gives you a chance to get a stolen notebook back.

### Version history

* 0.1 First uploads

### Documentation

The documentation is available at https://pythonhosted.org/pysec


text:
layout: page
title: 'Argyle House'
teaser: "Monitoring environment conditions and occupancy in meeting rooms"
image:
    title: libelium.jpg
    thumb: chair.png
show_meta: true
category: Project
tags: [building management, room occupancy, indoor sensors, environmental monitoring, UoE pilot, devices in the workplace]
---

As part of a broad plan for estates management by the University of Edinburgh, several hundreds of operations staff who had been scattered across multiple sites were recently rehoused in open-plan offices in a refurbished 60s office block (Argyle House).  The ground floor of the premises was remodelled to contain an assortment of large and small meeting rooms.  In order to give building managers more information about occupancy and environmental conditions, we carried out a pilot project with multiple networked devices.

In one of the small meeting rooms, sensors were attached to chairs and the door to measure temperature, light level and movement. Sensors for light level, temperature, atmospheric pressure and relative humidity were also placed near desks across one wing of an open-plan area.

We carried out a Privacy Impact Assessment in which we were careful to demonstrate that no personal data would be captured by the sensors.

The pilot allowed us to build and demonstrate our capability with IoT infrastructure, as well as giving us an understanding of how the environment in Argyle House performs.


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

#include "privacy/net/krypton/auth_and_sign_request.h"

#include <optional>
#include <string>

#include "google/protobuf/any.proto.h"
#include "privacy/net/attestation/proto/attestation.proto.h"
#include "testing/base/public/gmock.h"
#include "testing/base/public/gunit.h"
#include "third_party/absl/types/optional.h"
#include "third_party/jsoncpp/reader.h"
#include "third_party/jsoncpp/value.h"

namespace privacy {
namespace krypton {

using ::testing::EqualsProto;

// TODO: Write fuzz testing of the JSON body.
TEST(AuthAndSignRequest, TestAuthAndSignRequest) {
  AuthAndSignRequest request("abc", "123", "aaaa", std::nullopt, std::nullopt,
                             std::nullopt,
                             /*attach_oauth_as_header=*/false);

  auto proto = request.EncodeToProto();
  EXPECT_TRUE(proto);

  Json::Reader reader;

  Json::Value expected;
  reader.parse(R"string({
      "oauth_token" : "abc",
      "service_type" : "123",
   })string",
               expected);

  Json::Value actual;
  reader.parse(proto.value().json_body(), actual);

  EXPECT_EQ(actual, expected);
}

TEST(AuthAndSignRequest, TestAuthAndSignRequestWithOauthAsHeader) {
  AuthAndSignRequest request("abc", "123", "aaaa", std::nullopt, std::nullopt,
                             std::nullopt,
                             /*attach_oauth_as_header=*/true);

  auto proto = request.EncodeToProto();
  EXPECT_TRUE(proto);

  Json::Reader reader;

  Json::Value expected;
  reader.parse(R"string({
      "service_type" : "123",
   })string",
               expected);

  Json::Value actual;
  reader.parse(proto.value().json_body(), actual);

  EXPECT_EQ(actual, expected);
  EXPECT_EQ(proto->headers().find("Authorization")->second, "Bearer abc");
}

TEST(AuthAndSignRequest, TestAuthAndSignRequestWithBlindSigning) {
  AuthAndSignRequest request("abc", "123", "aaaa", "some_blind",
                             "hash of blind", std::nullopt,
                             /*attach_oauth_as_header=*/false);
  auto proto = request.EncodeToProto();
  EXPECT_TRUE(proto);

  Json::Reader reader;

  Json::Value expected;
  reader.parse(R"string({
      "oauth_token" : "abc",
      "service_type" : "123",
      "blinded_token": [ "some_blind"],
      "public_key_hash" : "hash of blind"
   })string",
               expected);

  Json::Value actual;
  reader.parse(proto.value().json_body(), actual);

  EXPECT_EQ(actual, expected);
}

TEST(AuthAndSignRequest, TestPublicKeyRequest) {
  PublicKeyRequest request(/*request_nonce=*/false, std::optional("apiKey"));
  auto proto = request.EncodeToProto();
  EXPECT_TRUE(proto);

  Json::Value expected;
  expected["get_public_key"] = true;

  Json::Reader reader;
  Json::Value actual;
  reader.parse(proto.value().json_body(), actual);
  EXPECT_EQ(proto->headers().find("X-Goog-Api-Key")->second, "apiKey");

  EXPECT_EQ(actual, expected);
}

TEST(AuthAndSignRequest, TestPublicKeyRequestWithNonceRequest) {
  PublicKeyRequest request(/*request_nonce=*/true, std::optional("apiKey"));
  auto proto = request.EncodeToProto();
  EXPECT_TRUE(proto);

  Json::Value expected;
  expected["get_public_key"] = true;
  expected["request_nonce"] = true;

  Json::Reader reader;
  Json::Value actual;
  reader.parse(proto.value().json_body(), actual);

  EXPECT_EQ(actual, expected);
}

TEST(AuthAndSignRequest, TestAuthAndSignRequestWithIntegrityToken) {
  privacy::ppn::AttestationData attestation_data;
  attestation_data.mutable_attestation_data()->set_type_url("foo");
  attestation_data.mutable_attestation_data()->set_value("bar");

  AuthAndSignRequest request("abc", "123", "aaaa", std::nullopt, std::nullopt,
                             attestation_data,
                             /*attach_oauth_as_header=*/false);
  auto proto = request.EncodeToProto();
  EXPECT_TRUE(proto);

  std::string request_bytes = proto->proto_body();
  ppn::AuthAndSignRequest actual;
  ASSERT_TRUE(actual.ParseFromString(request_bytes));

  ASSERT_THAT(
      actual, EqualsProto(R"pb(
        oauth_token: "abc"
        service_type: "123"
        attestation { attestation_data { type_url: "foo" value: "bar" } }
      )pb"));
}

}  // namespace krypton
}  // namespace privacy


text:
package org.jetbrains.plugins.scala.traceLogger.macros

import scala.language.experimental.macros

//noinspection ScalaUnusedSymbol
trait LoggingMacros {
  final def log(msg: String, args: Any*): Unit = macro LoggingMacros.logImpl
  final def block[T](msg: String, args: Any*)(body: => T): T = macro LoggingMacros.blockImpl[T]
  final def func[T](body: => T): T = macro LoggingMacros.funcImpl[T]
}

object LoggingMacros {
  type Context = scala.reflect.macros.blackbox.Context

  def logImpl(c: Context)(msg: c.Expr[String], args: c.Expr[Any]*): c.Expr[Unit] = {
    InContext[c.type](c).logImpl(msg, args)
  }

  def blockImpl[T](c: Context)(msg: c.Expr[String], args: c.Expr[Any]*)(body: c.Expr[T])(implicit wk: c.WeakTypeTag[T]): c.Expr[T] = {
    InContext[c.type](c).blockImpl(msg, args, body)
  }

  def funcImpl[T](c: Context)(body: c.Expr[T])(implicit wk: c.WeakTypeTag[T]): c.Expr[T] = {
    InContext[c.type](c).funcImpl(body)
  }

  //noinspection SameParameterValue
  private final case class InContext[Ctx <: Context](c: Ctx) {
    import c.universe._

    private val traceLogFqn: Tree =
      q"_root_.org.jetbrains.plugins.scala.traceLogger.TraceLog"

    private val toDataFqn: Tree =
      q"_root_.org.jetbrains.plugins.scala.traceLogger.ToData"

    private val stackTrace: Tree =
      q"_root_.java.lang.Thread.currentThread().getStackTrace"

    private def toData(expr: Tree, ty: Type): Tree = {
      // we have to typecheck here, so the correct ToData is selected
      q"$toDataFqn[$ty]($expr)"
    }

    private def textOfExpr(v: Tree): String = {
      val fileContent = new String(v.pos.source.content)
      val start = v.collect {
        case treeVal => treeVal.pos match {
          case NoPosition => Int.MaxValue
          case p => p.start
        }
      }.min
      if (start == Int.MaxValue) {
        throw new Error(s"Cannot determine source code for $v")
      } else {
        val g = c.asInstanceOf[reflect.macros.runtime.Context].global
        val parser = g.newUnitParser(fileContent.drop(start))
        parser.expr()
        val end = parser.in.lastOffset
        fileContent.slice(start, start + end)
      }
    }

    private def wrapReturns[R](tree: Tree, f: Tree => Tree): Tree = {
      val transformer = new Transformer {
        override def transform(tree: Tree): Tree = {
          tree match {
            case Return(expr) =>
              // We have to type check the returned tree
              // because we insert it into an already typed tree.
              // Otherwise we will get compiler errors,
              // because the compiler will not typecheck trees
              // that have typechecked parents.
              val transformedExpr = c.typecheck(f(expr))
              treeCopy.Return(tree, transformedExpr)

            //skip local functions and classes
            case dd: DefDef @unchecked => dd
            case cd: ClassDef @unchecked => cd
            case md: ModuleDef @unchecked => md
            case _ => super.transform(tree)
          }
        }
      }
      transformer.transform(tree)
    }

    private def wrapResulting[R: WeakTypeTag](tree: Tree, f: Tree => Tree): c.Expr[R] =
      c.Expr[R](f(wrapReturns(tree, f)))

    private def enclosingOwner: c.Symbol = c.internal.enclosingOwner

    private def withOwners(startSymbol: c.Symbol): Iterator[c.Symbol] = new Iterator[c.Symbol] {
      private var cur = startSymbol
      override def hasNext: Boolean = cur != NoSymbol
      override def next(): c.Symbol = {
        val result = cur
        cur = cur.owner
        result
      }
    }

    private def enclosingMethod(start: Symbol): Option[MethodSymbol] =
      withOwners(start).collectFirst {
        case method if method.isMethod => method.asMethod
        case cls if cls.isClass => cls.asClass.primaryConstructor.asMethod
      }

    private def enclosingClass(start: Symbol): Option[ClassSymbol] =
      withOwners(start).collectFirst {
        case cls if cls.isClass => cls.asClass
      }

    private def inActiveIf[T: WeakTypeTag](inner: c.Expr[T]): c.Expr[T] = {
      c.Expr[T](
        q"""
          if ($traceLogFqn.isActiveInAtLeastOneThread) {
            $inner
          }
        """)
    }

    private def convertExprToData(v: Tree, ty: Type): c.Expr[_] =
      convertExprToData(textOfExpr(v), v, ty)

    private def convertExprToData(name: String, v: Tree, ty: Type): c.Expr[_] =
      c.Expr(q"""($name, ${toData(v, ty)})""")

    private def convertExpressionsToData(v: Seq[c.Expr[Any]]): c.Expr[Seq[_]] = {
      assert(v.forall(_.actualType != null))
      c.Expr(q"Seq(..${v.map(e => convertExprToData(e.tree, e.actualType))})")
    }

    private def enclosingStart(msg: c.Expr[String], data: c.Expr[Seq[_]]): c.Expr[Unit] =
      c.Expr[Unit](q"$traceLogFqn.inst.startEnclosing($msg, $data, $stackTrace)")

    private def success(result: Tree, ty: Type): c.Expr[Unit] =
      c.Expr[Unit](q"$traceLogFqn.inst.enclosingSuccess(${toData(result, ty)}, $stackTrace)")

    private def fail(e: Tree): c.Expr[Unit] =
      c.Expr[Unit](q"$traceLogFqn.inst.enclosingFail($e, $stackTrace)")

    private def enclosing[T](body: c.Expr[T])(implicit ttag: WeakTypeTag[T]): c.Expr[T] = {
      val resultType = ttag.tpe
      val wrappedBody = wrapResulting(body.tree, result => {
        val resultVar = q"${TermName(c.freshName("result"))}"
        q"""
          val $resultVar: $resultType = $result
          ${inActiveIf(success(resultVar, resultType))}
          $resultVar
         """
      })

      c.Expr[T](
        q"""
        try {
          $wrappedBody
        } catch {
          case e: scala.runtime.NonLocalReturnControl[_] =>
            ${inActiveIf(success(q"e.value.asInstanceOf[$resultType]", resultType))}
            throw e
          case e: scala.Throwable =>
            ${inActiveIf(fail(q"e"))}
            throw e
        }
        """
      )
    }

    def logImpl(msg: c.Expr[String], args: Seq[c.Expr[Any]]): c.Expr[Unit] = {
      val logExpr = c.Expr[Unit](
        q"$traceLogFqn.inst.log($msg, ${convertExpressionsToData(args)}, $stackTrace)"
      )

      inActiveIf(logExpr)
    }

    def blockImpl[T: WeakTypeTag](msg: c.Expr[String], args: Seq[c.Expr[Any]], body: c.Expr[T]): c.Expr[T] = {
      c.Expr[T](q"""
        ${inActiveIf(enclosingStart(msg, convertExpressionsToData(args)))}
        ${enclosing(body)}
       """)
    }

    def funcImpl[T: WeakTypeTag](body: c.Expr[T]): c.Expr[T] = {
      val owner = enclosingOwner
      if (!owner.isClass && !owner.isMethod) {
        c.abort(c.enclosingPosition, "use TraceLogger.func only at the start of methods or in class constructors")
      }
      val method = enclosingMethod(owner).get

      def convertUntypedTree(name: String, tree: Tree): c.Expr[_] = {
        val typed = c.typecheck(tree)
        convertExprToData(name, typed, typed.tpe)
      }

      val thisDesc = enclosingClass(owner) match {
        case Some(c) if !c.isPackageClass && !c.isModuleClass && !c.isImplementationArtifact && !c.isSynthetic =>
          Seq(convertExprToData("this", q"this", c.toType))
        case _ =>
          Seq.empty
      }

      val params = thisDesc ++ method.paramLists.flatten.map(param => convertUntypedTree(param.name.toString, q"$param"))
      val paramsSeq = c.Expr[Seq[_]](q"Seq(..$params)")
      val emptyMessage = c.Expr[String](q"null")
      c.Expr[T](q"""
        ${inActiveIf(enclosingStart(emptyMessage, paramsSeq))}
        ${enclosing(body)}
       """)
    }
  }
}


text:
package cmd

import (
	"fmt"
	"log"
	"os"
	"runtime"

	clilog "github.com/b4b4r07/go-cli-log"
	"github.com/spf13/cobra"
)

var (
	// Version is the version number
	Version = "unset"

	// BuildTag set during build to git tag, if any
	BuildTag = "unset"

	// BuildSHA is the git sha set during build
	BuildSHA = "unset"
)

// newRootCmd returns the root command
func newRootCmd() *cobra.Command {
	rootCmd := &cobra.Command{
		Use:                "gist",
		Short:              "A simple gist editor for CLI",
		SilenceErrors:      true,
		DisableSuggestions: false,
		Version:            fmt.Sprintf("%s (%s/%s)", Version, BuildTag, BuildSHA),
	}

	rootCmd.AddCommand(newNewCmd())
	rootCmd.AddCommand(newEditCmd())
	rootCmd.AddCommand(newOpenCmd())
	rootCmd.AddCommand(newDeleteCmd())
	return rootCmd
}

// Execute is the entrypoint of this cmd package
func Execute() error {
	clilog.Env = "GIST_LOG"
	clilog.Path = "GIST_LOG_PATH"
	clilog.SetOutput()

	log.Printf("[INFO] pkg version: %s", Version)
	log.Printf("[INFO] Go runtime version: %s", runtime.Version())
	log.Printf("[INFO] Build tag/SHA: %s/%s", BuildTag, BuildSHA)
	log.Printf("[INFO] CLI args: %#v", os.Args)

	defer log.Printf("[DEBUG] root command execution finished")

	return newRootCmd().Execute()
}


text:
package org.docksidestage.hangar.dbflute.cbean.cq.bs;

import java.util.Map;

import org.dbflute.cbean.*;
import org.dbflute.cbean.chelper.*;
import org.dbflute.cbean.coption.*;
import org.dbflute.cbean.cvalue.ConditionValue;
import org.dbflute.cbean.sqlclause.SqlClause;
import org.dbflute.exception.IllegalConditionBeanOperationException;
import org.docksidestage.hangar.dbflute.cbean.cq.ciq.*;
import org.docksidestage.hangar.dbflute.cbean.*;
import org.docksidestage.hangar.dbflute.cbean.cq.*;

/**
 * The base condition-query of WHITE_BASE_ONE01_SEA_MAGICLAMP.
 * @author DBFlute(AutoGenerator)
 */
public class BsWhiteBaseOne01SeaMagiclampCQ extends AbstractBsWhiteBaseOne01SeaMagiclampCQ {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected WhiteBaseOne01SeaMagiclampCIQ _inlineQuery;

    // ===================================================================================
    //                                                                         Constructor
    //                                                                         ===========
    public BsWhiteBaseOne01SeaMagiclampCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
        super(referrerQuery, sqlClause, aliasName, nestLevel);
    }

    // ===================================================================================
    //                                                                 InlineView/OrClause
    //                                                                 ===================
    /**
     * Prepare InlineView query.

     * {select ... from ... left outer join (select * from WHITE_BASE_ONE01_SEA_MAGICLAMP) where FOO = [value] ...}
     *

     * cb.query().queryMemberStatus().inline().setFoo...;
     *

     * @return The condition-query for InlineView query. (NotNull)
     */
    public WhiteBaseOne01SeaMagiclampCIQ inline() {
        if (_inlineQuery == null) { _inlineQuery = xcreateCIQ(); }
        _inlineQuery.xsetOnClause(false); return _inlineQuery;
    }

    protected WhiteBaseOne01SeaMagiclampCIQ xcreateCIQ() {
        WhiteBaseOne01SeaMagiclampCIQ ciq = xnewCIQ();
        ciq.xsetBaseCB(_baseCB);
        return ciq;
    }

    protected WhiteBaseOne01SeaMagiclampCIQ xnewCIQ() {
        return new WhiteBaseOne01SeaMagiclampCIQ(xgetReferrerQuery(), xgetSqlClause(), xgetAliasName(), xgetNestLevel(), this);
    }

    /**
     * Prepare OnClause query.

     * {select ... from ... left outer join WHITE_BASE_ONE01_SEA_MAGICLAMP on ... and FOO = [value] ...}
     *

     * cb.query().queryMemberStatus().on().setFoo...;
     *

     * @return The condition-query for OnClause query. (NotNull)
     * @throws IllegalConditionBeanOperationException When this condition-query is base query.
     */
    public WhiteBaseOne01SeaMagiclampCIQ on() {
        if (isBaseQuery()) { throw new IllegalConditionBeanOperationException("OnClause for local table is unavailable!"); }
        WhiteBaseOne01SeaMagiclampCIQ inlineQuery = inline(); inlineQuery.xsetOnClause(true); return inlineQuery;
    }

    // ===================================================================================
    //                                                                               Query
    //                                                                               =====
    protected ConditionValue _magiclampId;
    public ConditionValue xdfgetMagiclampId()
    { if (_magiclampId == null) { _magiclampId = nCV(); }
      return _magiclampId; }
    protected ConditionValue xgetCValueMagiclampId() { return xdfgetMagiclampId(); }

    /**
     * Add order-by as ascend.

     * MAGICLAMP_ID: {PK, NotNull, INTEGER(10)}
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addOrderBy_MagiclampId_Asc() { regOBA("MAGICLAMP_ID"); return this; }

    /**
     * Add order-by as descend.

     * MAGICLAMP_ID: {PK, NotNull, INTEGER(10)}
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addOrderBy_MagiclampId_Desc() { regOBD("MAGICLAMP_ID"); return this; }

    protected ConditionValue _magiclampName;
    public ConditionValue xdfgetMagiclampName()
    { if (_magiclampName == null) { _magiclampName = nCV(); }
      return _magiclampName; }
    protected ConditionValue xgetCValueMagiclampName() { return xdfgetMagiclampName(); }

    /**
     * Add order-by as ascend.

     * MAGICLAMP_NAME: {NotNull, VARCHAR(200)}
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addOrderBy_MagiclampName_Asc() { regOBA("MAGICLAMP_NAME"); return this; }

    /**
     * Add order-by as descend.

     * MAGICLAMP_NAME: {NotNull, VARCHAR(200)}
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addOrderBy_MagiclampName_Desc() { regOBD("MAGICLAMP_NAME"); return this; }

    protected ConditionValue _seaId;
    public ConditionValue xdfgetSeaId()
    { if (_seaId == null) { _seaId = nCV(); }
      return _seaId; }
    protected ConditionValue xgetCValueSeaId() { return xdfgetSeaId(); }

    /**
     * Add order-by as ascend.

     * SEA_ID: {IX, INTEGER(10), FK to WHITE_BASE_ONE01_SEA}
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addOrderBy_SeaId_Asc() { regOBA("SEA_ID"); return this; }

    /**
     * Add order-by as descend.

     * SEA_ID: {IX, INTEGER(10), FK to WHITE_BASE_ONE01_SEA}
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addOrderBy_SeaId_Desc() { regOBD("SEA_ID"); return this; }

    // ===================================================================================
    //                                                             SpecifiedDerivedOrderBy
    //                                                             =======================
    /**
     * Add order-by for specified derived column as ascend.
     *

     * cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
     *     public void query(PurchaseCB subCB) {
     *         subCB.specify().columnPurchaseDatetime();
     *     }
     * }, aliasName);
     * // order by [alias-name] asc
     * cb.addSpecifiedDerivedOrderBy_Asc(aliasName);
     *

     * @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; }

    /**
     * Add order-by for specified derived column as descend.
     *

     * cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
     *     public void query(PurchaseCB subCB) {
     *         subCB.specify().columnPurchaseDatetime();
     *     }
     * }, aliasName);
     * // order by [alias-name] desc
     * cb.addSpecifiedDerivedOrderBy_Desc(aliasName);
     *

     * @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
     * @return this. (NotNull)
     */
    public BsWhiteBaseOne01SeaMagiclampCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; }

    // ===================================================================================
    //                                                                         Union Query
    //                                                                         ===========
    public void reflectRelationOnUnionQuery(ConditionQuery bqs, ConditionQuery uqs) {
        WhiteBaseOne01SeaMagiclampCQ bq = (WhiteBaseOne01SeaMagiclampCQ)bqs;
        WhiteBaseOne01SeaMagiclampCQ uq = (WhiteBaseOne01SeaMagiclampCQ)uqs;
        if (bq.hasConditionQueryWhiteBaseOne01Sea()) {
            uq.queryWhiteBaseOne01Sea().reflectRelationOnUnionQuery(bq.queryWhiteBaseOne01Sea(), uq.queryWhiteBaseOne01Sea());
        }
    }

    // ===================================================================================
    //                                                                       Foreign Query
    //                                                                       =============
    /**
     * Get the condition-query for relation table.

     * WHITE_BASE_ONE01_SEA by my SEA_ID, named 'whiteBaseOne01Sea'.
     * @return The instance of condition-query. (NotNull)
     */
    public WhiteBaseOne01SeaCQ queryWhiteBaseOne01Sea() {
        return xdfgetConditionQueryWhiteBaseOne01Sea();
    }
    public WhiteBaseOne01SeaCQ xdfgetConditionQueryWhiteBaseOne01Sea() {
        String prop = "whiteBaseOne01Sea";
        if (!xhasQueRlMap(prop)) { xregQueRl(prop, xcreateQueryWhiteBaseOne01Sea()); xsetupOuterJoinWhiteBaseOne01Sea(); }
        return xgetQueRlMap(prop);
    }
    protected WhiteBaseOne01SeaCQ xcreateQueryWhiteBaseOne01Sea() {
        String nrp = xresolveNRP("WHITE_BASE_ONE01_SEA_MAGICLAMP", "whiteBaseOne01Sea"); String jan = xresolveJAN(nrp, xgetNNLvl());
        return xinitRelCQ(new WhiteBaseOne01SeaCQ(this, xgetSqlClause(), jan, xgetNNLvl()), _baseCB, "whiteBaseOne01Sea", nrp);
    }
    protected void xsetupOuterJoinWhiteBaseOne01Sea() { xregOutJo("whiteBaseOne01Sea"); }
    public boolean hasConditionQueryWhiteBaseOne01Sea() { return xhasQueRlMap("whiteBaseOne01Sea"); }

    protected Map<String, Object> xfindFixedConditionDynamicParameterMap(String property) {
        return null;
    }

    // ===================================================================================
    //                                                                     ScalarCondition
    //                                                                     ===============
    public Map<String, WhiteBaseOne01SeaMagiclampCQ> xdfgetScalarCondition() { return xgetSQueMap("scalarCondition"); }
    public String keepScalarCondition(WhiteBaseOne01SeaMagiclampCQ sq) { return xkeepSQue("scalarCondition", sq); }

    // ===================================================================================
    //                                                                       MyselfDerived
    //                                                                       =============
    public Map<String, WhiteBaseOne01SeaMagiclampCQ> xdfgetSpecifyMyselfDerived() { return xgetSQueMap("specifyMyselfDerived"); }
    public String keepSpecifyMyselfDerived(WhiteBaseOne01SeaMagiclampCQ sq) { return xkeepSQue("specifyMyselfDerived", sq); }

    public Map<String, WhiteBaseOne01SeaMagiclampCQ> xdfgetQueryMyselfDerived() { return xgetSQueMap("queryMyselfDerived"); }
    public String keepQueryMyselfDerived(WhiteBaseOne01SeaMagiclampCQ sq) { return xkeepSQue("queryMyselfDerived", sq); }
    public Map<String, Object> xdfgetQueryMyselfDerivedParameter() { return xgetSQuePmMap("queryMyselfDerived"); }
    public String keepQueryMyselfDerivedParameter(Object pm) { return xkeepSQuePm("queryMyselfDerived", pm); }

    // ===================================================================================
    //                                                                        MyselfExists
    //                                                                        ============
    protected Map<String, WhiteBaseOne01SeaMagiclampCQ> _myselfExistsMap;
    public Map<String, WhiteBaseOne01SeaMagiclampCQ> xdfgetMyselfExists() { return xgetSQueMap("myselfExists"); }
    public String keepMyselfExists(WhiteBaseOne01SeaMagiclampCQ sq) { return xkeepSQue("myselfExists", sq); }

    // ===================================================================================
    //                                                                       MyselfInScope
    //                                                                       =============
    public Map<String, WhiteBaseOne01SeaMagiclampCQ> xdfgetMyselfInScope() { return xgetSQueMap("myselfInScope"); }
    public String keepMyselfInScope(WhiteBaseOne01SeaMagiclampCQ sq) { return xkeepSQue("myselfInScope", sq); }

    // ===================================================================================
    //                                                                       Very Internal
    //                                                                       =============
    // very internal (for suppressing warn about 'Not Use Import')
    protected String xCB() { return WhiteBaseOne01SeaMagiclampCB.class.getName(); }
    protected String xCQ() { return WhiteBaseOne01SeaMagiclampCQ.class.getName(); }
    protected String xCHp() { return HpQDRFunction.class.getName(); }
    protected String xCOp() { return ConditionOption.class.getName(); }
    protected String xMap() { return Map.class.getName(); }
}


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Starts a service</title>

win32_start_service_ctrl_dispatcher

win32_stop_service

win32service Functions

PHP Manual

win32_start_service

(PECL win32service SVN)

win32_start_service — Starts a service

Description

   int win32_start_service
    ( string $servicename
   [, string $machine
  ] )

   Attempts to start the named service.  Usually requires administrative
   privileges.

Parameters

servicename

       The short name of the service.

machine

       Optional machine name.  If omitted, the local machine is used.

Return Values

   Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

See Also

win32_stop_service() - Stops a service

Win32 Error Codes

win32_start_service_ctrl_dispatcher

win32_stop_service

win32service Functions

PHP Manual


text:
package io.vitess.hadoop;

import io.vitess.client.Context;
import io.vitess.client.RpcClient;
import io.vitess.client.RpcClientFactory;
import io.vitess.client.VTGateBlockingConn;
import io.vitess.client.cursor.Cursor;
import io.vitess.client.cursor.Row;
import io.vitess.proto.Query;
import io.vitess.proto.Query.BoundQuery;
import io.vitess.proto.Topodata.TabletType;
import io.vitess.proto.Vtgate.SplitQueryResponse;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import org.joda.time.Duration;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class VitessRecordReader extends RecordReader<NullWritable, RowWritable> {

  private VitessInputSplit split;
  private VTGateBlockingConn vtgate;
  private VitessConf conf;
  private long rowsProcessed = 0;
  private Cursor cursor;
  private RowWritable currentRow;
  private Query.ExecuteOptions.IncludedFields includedFields;

  /**
   * Fetch connection parameters from Configuraiton and open VtGate connection.
   */
  @Override
  public void initialize(InputSplit split, TaskAttemptContext context)
      throws IOException, InterruptedException {
    this.split = (VitessInputSplit) split;
    conf = new VitessConf(context.getConfiguration());
    try {
      @SuppressWarnings("unchecked")
      Class<? extends RpcClientFactory> rpcFactoryClass =
          (Class<? extends RpcClientFactory>) Class.forName(conf.getRpcFactoryClass());
      List<String> addressList = Arrays.asList(conf.getHosts().split(","));
      int index = new Random().nextInt(addressList.size());

      RpcClient rpcClient = rpcFactoryClass.newInstance().create(
          Context.getDefault().withDeadlineAfter(Duration.millis(conf.getTimeoutMs())),
          addressList.get(index));
      vtgate = new VTGateBlockingConn(rpcClient);
      includedFields = conf.getIncludedFields();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException exc) {
      throw new RuntimeException(exc);
    }
  }

  @Override
  public void close() throws IOException {
    if (vtgate != null) {
      try {
        vtgate.close();
        vtgate = null;
      } catch (IOException exc) {
        throw new RuntimeException(exc);
      }
    }
  }

  @Override
  public NullWritable getCurrentKey() throws IOException, InterruptedException {
    return NullWritable.get();
  }

  @Override
  public RowWritable getCurrentValue() throws IOException, InterruptedException {
    return currentRow;
  }

  @Override
  public float getProgress() throws IOException, InterruptedException {
    if (rowsProcessed > split.getLength()) {
      return 0.9f;
    }
    return rowsProcessed / split.getLength();
  }

  /**
   * Fetches the next row. If this is the first invocation for the split, execute the streaming
   * query. Subsequent calls just advance the iterator.
   */
  @Override
  public boolean nextKeyValue() throws IOException, InterruptedException {
    try {
      if (cursor == null) {
        SplitQueryResponse.Part splitInfo = split.getSplit();
        if (splitInfo.hasKeyRangePart()) {
          BoundQuery query = splitInfo.getQuery();
          SplitQueryResponse.KeyRangePart keyRangePart = splitInfo.getKeyRangePart();
          cursor = vtgate.streamExecuteKeyRanges(Context.getDefault(), query.getSql(),
              keyRangePart.getKeyspace(), keyRangePart.getKeyRangesList(), query.getBindVariables(),
              TabletType.RDONLY, includedFields);
        } else if (splitInfo.hasShardPart()) {
          BoundQuery query = splitInfo.getQuery();
          SplitQueryResponse.ShardPart shardPart = splitInfo.getShardPart();
          cursor = vtgate.streamExecuteShards(Context.getDefault(), query.getSql(),
              shardPart.getKeyspace(), shardPart.getShardsList(), query.getBindVariables(),
              TabletType.RDONLY, includedFields);
        } else {
          throw new IllegalArgumentException("unknown split info: " + splitInfo);
        }
      }
      Row row = cursor.next();
      if (row == null) {
        currentRow = null;
      } else {
        currentRow = new RowWritable(row);
      }
    } catch (SQLException exc) {
      throw new RuntimeException(exc);
    }

    if (currentRow == null) {
      return false;
    }
    rowsProcessed++;
    return true;
  }
}


text:
package org.kuali.kra.award.rule.event;

import org.kuali.kra.award.document.AwardDocument;
import org.kuali.kra.award.notesandattachments.attachments.AwardAttachment;
import org.kuali.kra.award.rule.AddAwardAttachmentRule;
import org.kuali.rice.krad.rules.rule.BusinessRule;

public class AddAwardAttachmentEvent extends AwardAttachmentEventBase {

    public AddAwardAttachmentEvent(String description, String errorPathPrefix, AwardDocument document, AwardAttachment attachment) {
        super(description, errorPathPrefix, document, attachment);
    }

   public AddAwardAttachmentEvent(String description, String errorPathPrefix, AwardDocument document) {
        super(description, errorPathPrefix, document);

    }

    @Override
    public Class getRuleInterfaceClass() {
        return AddAwardAttachmentRule.class;
    }

    @Override
    public boolean invokeRuleMethod(BusinessRule rule) {
        return ((AddAwardAttachmentRule) rule).processsAddAttachmentRule(this);
    }

}


text:
swig-base
=========

Base template for [swig](http://paularmstrong.github.io/swig/)


text:
from distutils.core import setup

import codecs
import os
import re

def find_version(*file_paths):
    # Open in Latin-1 so that we avoid encoding errors.
    # Use codecs.open for Python 2 compatibility
    here = os.path.abspath(os.path.dirname(__file__))

    with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f:
        version_file = f.read()

    # The version line must have the form
    # __version__ = 'ver'
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

setup(
    name='tide-wrangler',
    version=find_version('tide_wrangler', '__init__.py'),
    description='Wrangle data files containing predictions & observations',
    author='Sea Level Research Ltd',
    author_email='hello@sealevelresearch.com',
    url='https://github.com/sealevelresearch/tide-wrangler',
    install_requires=['docopt', 'pytz'],
    packages=['tide_wrangler'],
    entry_points={
        'console_scripts': [
            'wrangle=tide_wrangler:main',
        ],
    },
)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  IoModes
  Steinberg::Vst

  IStreamSeekMode
  Steinberg::IBStream

Searching...

No Matches


text:
package org.springframework.cloud.servicebroker.service.events.flows;

import reactor.core.publisher.Mono;

import org.springframework.cloud.servicebroker.model.instance.GetLastServiceOperationRequest;

/**
 * Error flow for asynchronous get last operation reguest
 *
 * @author Roy Clarkson
 */
public interface AsyncOperationServiceInstanceErrorFlow {

	/**
	 * Performs the operation on the error flow
	 *
	 * @param request the service broker request
	 * @param t the error
	 * @return an empty Mono
	 */
	default Mono<Void> error(GetLastServiceOperationRequest request, Throwable t) {
		return Mono.empty();
	}

}


text:
<?php
if(isset($script2) && isset($script)) {
 echo $script2; //script untuk atur class active
 echo $script; //script untuk atur class active
}
?>

	<?php $this->load->view('super/menu/sidebar') //load the sidebar ?>

Kompetisi

				+ Kompetisi Baru

<a href="<?php echo site_url('super/super/dashboard?act=posted') ?>" >Posted

<a href="<?php echo site_url('super/super/dashboard?act=draft') ?>">Draft

Total Posted Kompetisi :
								<?php if(isset($tot_aktif)){
									echo $tot_aktif;
								} else if(isset($tot_draft)){
									echo $tot_draft;
								}?>

											No
											Judul Kompetisi
											MK
											SK
											Ditandai
											Bergabung
											Dikunjungi
											Status

										<?php $n = 1 ?>
										<?php foreach ($view as $v) {
											$enc = base64_encode(base64_encode($v['id_kompetisi']));
											$id = $id_kompetisi = str_replace('=', '', $enc);
											$judul = str_replace(' ', '_', $v['judul_kompetisi']);
											?>

												<?php echo $n;?>
												<?php echo $v['judul_kompetisi'];?>
												<?php echo $v['id_main_kat'];?>
												<?php echo $v['id_sub_kat'];?>
												2300
												1234
												24000
												<?php echo $v['status']?>

														<a href="<?php echo site_url().'/super/super/edit'.'/?id='.$id; ?>" class="btn btn-default">
														<a href="<?php echo site_url().'/kompetisi/detail/'.$id.'/'.$judul; ?>" class="btn btn-default">
														<a onclick="return confirm('Anda Yakin!')" href="<?php echo site_url('super/super/delete_kompetisi?id='.$v['id_kompetisi'])?>" class="btn btn-default">

											<?php $n++;
										} ?>

<?php echo $page ?>

Total Draft Kompetisi : <?php echo $tot_draft ?>

									No
									Judul Kompetisi
									SubKategori
									Ditandai
									Bergabung
									Dikunjungi
									Status

								<?php $n = 1 ?>
								<?php foreach ($draft as $d) {
									$enc = base64_encode(base64_encode($d['id_kompetisi']));
									$id = $id_kompetisi = str_replace('=', '', $enc);
									$judul = str_replace(' ', '_', $d['judul_kompetisi']);
									?>

										<?php echo $n;?>
										<?php echo $d['judul_kompetisi'];?>
										<?php echo $d['id_sub_kat'];?>
										2300
										1234
										24000
										<?php echo $d['status']?>
										<a href="<?php echo site_url().'/super/super/edit'.'/?id='.$id; ?>" class="btn btn-default">
											<a href="<?php echo site_url().'/kompetisi/detail/'.$id.'/'.$judul; ?>" class="btn btn-default">

										<?php $n++;
									} ?>

<?php echo $page ?>

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

Tambah Kompetisi

				<form enctype="multipart/form-data" method="post" action="<?php echo site_url('super/super/add_kompetisi')?>" class="form-horizontal" role="form">

						*Judul Kompetis

pastikan ejaan yang anda tulis sudah benar

							<input name="judul" type="text" class="form-control" id="judulkompetisi" required>

						*Deskripsi Singkat

maks 500 karakter

							<input name="sort" type="text" class="form-control" id="deskripsisingkat" required>

						*Kategori

							<select name="mainkategori" class="form-control" id="mainkategori" onchange="loadsubkat()" required>
								<?php foreach ($main_kat as $sk) { ?>
								<option value="<?php echo $sk['id_main_kat']?>" ><?php echo $sk['main_kat']?></option>
								<?php } ?>
							</select>

							<img src="<?php echo base_url('dist/ajax-loader.gif')?>"/> loading subkategori

							*Deadline

								<input name="deadline" type="date" class="form-control" id="deadline" required>

							*Pengumuman

								<input name="pengumuman" type="date" class="form-control" id="pengumuman" required>

							*Penyelenggara

								<input name="penyelenggara" type="text" class="form-control" id="penyelenggara" required>

							*Nilai Total Hadiah

Penulisan tanpa tanda (.) titik atau (,) koma

Contoh : 5000000

									Rp.
									<input name="total" type="number" class="form-control" id="total" required>
									.00

							*Detail Hadiah:

Contoh : juara 1 : iPad 32GB | juara 2 : iPhone 5 32GB | Juara 3 : iPhone 5 8GB

atau hadiah akan diberikan kepada 5 juara favorit

								<textarea name="hadiah" class="form-control" id="hadiah" maxlength="500" required></textarea>

							* Deskripsi Lengkap

deskripsi meliputi syarat dan ketentuan kompetisi

dan atau contact person / informasi lebih lanjut

								<textarea name="deskripsi" style="height:200px" class="form-control deskripsilengkap" id="deskripsilengkap" ></textarea>

							Link

								<input name="link" type="url" class="form-control" id="pengumuman">

							Poster

file support : png, jpg, jpeg

maks : 1MB

								<input name="poster" type="file" class="form-control" id="poster">

						<input type="hidden" name="username" value="$this->session->userdata('username')">

								<button name="btn_pasang" type="submit" class="btn btn-default">+ Pasang</button>

						</form>


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports['default'] = init;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _models = require('../models');

var _models2 = _interopRequireDefault(_models);

var _users = require('../../data/user');

function init() {
  _models2['default'].user.find(function (err, users) {
    if (!users.length) {
      _users.forEach(function (item) {
        var userEntity = new _models2['default'].user(item);
        userEntity.save();
      });
      console.log('Insert data done!');
    }
  });
}

module.exports = exports['default'];


text:
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

/**
   @file gcm_done.c
   GCM implementation, Terminate the stream, by Tom St Denis
*/
#include "tomcrypt.h"

#ifdef LTC_GCM_MODE

/**
  Terminate a GCM stream
  @param gcm     The GCM state
  @param tag     [out] The destination for the MAC tag
  @param taglen  [in/out]  The length of the MAC tag
  @return CRYPT_OK on success
 */
int gcm_done(gcm_state *gcm,
                     unsigned char *tag,    unsigned long *taglen)
{
   unsigned long x;
   int err;

   LTC_ARGCHK(gcm     != NULL);
   LTC_ARGCHK(tag     != NULL);
   LTC_ARGCHK(taglen  != NULL);

   if (gcm->buflen > 16 || gcm->buflen < 0) {
      return CRYPT_INVALID_ARG;
   }

   if ((err = cipher_is_valid(gcm->cipher)) != CRYPT_OK) {
      return err;
   }

   if (gcm->mode != LTC_GCM_MODE_TEXT) {
      return CRYPT_INVALID_ARG;
   }

   /* handle remaining ciphertext */
   if (gcm->buflen) {
      gcm->pttotlen += gcm->buflen * CONST64(8);
      gcm_mult_h(gcm, gcm->X);
   }

   /* length */
   STORE64H(gcm->totlen, gcm->buf);
   STORE64H(gcm->pttotlen, gcm->buf+8);
   for (x = 0; x < 16; x++) {
       gcm->X[x] ^= gcm->buf[x];
   }
   gcm_mult_h(gcm, gcm->X);

   /* encrypt original counter */
   if ((err = cipher_descriptor[gcm->cipher].ecb_encrypt(gcm->Y_0, gcm->buf, &gcm->K)) != CRYPT_OK) {
      return err;
   }
   for (x = 0; x < 16 && x < *taglen; x++) {
       tag[x] = gcm->buf[x] ^ gcm->X[x];
   }
   *taglen = x;

   cipher_descriptor[gcm->cipher].done(&gcm->K);

   return CRYPT_OK;
}

#endif

/* $Source$ */
/* $Revision$ */
/* $Date$ */


text:
import {ServiceBase} from './ServiceBase';
import {
    GetLayersInfoService,
    SetLayerInfoService,
    SetLayersInfoService,
    SetLayerStatusService,
    CommonUtil
} from '@supermap/iclient-common';

/**
 * @class ol.supermap.LayerInfoService
 * @category  iServer Map Layer
 * @classdesc 图层信息服务类。
 * @extends {ol.supermap.ServiceBase}
 * @example
 *      new ol.supermap.LayerInfoService(url).getLayersInfo(function(result){
 *           //doSomething
 *      })
 * @param {string} url - 与客户端交互的地图服务地址。请求地图服务,URL 应为:
 *                       http://{服务器地址}:{服务端口号}/iserver/services/{地图服务名}/rest/maps/{地图名}/tempLayersSet/{tempLayerID}/Rivers@World@@World"。
 * @param {Object} options - 参数。
 * @param {string} [options.proxy] - 服务代理地址。
 * @param {boolean} [options.withCredentials=false] - 请求是否携带cookie。
 * @param {boolean} [options.crossOrigin] - 是否允许跨域请求。
 * @param {Object} [options.headers] - 请求头。
 */
export class LayerInfoService extends ServiceBase {

    constructor(url, options) {
        super(url, options);
    }

    /**
     * @function ol.supermap.LayerInfoService.prototype.getLayersInfo
     * @description 获取图层信息服务。
     * @param {RequestCallback} callback - 回调函数。
     */
    getLayersInfo(callback) {
        var me = this;
        var getLayersInfoService = new GetLayersInfoService(me.url, {
            proxy: me.options.proxy,
            withCredentials: me.options.withCredentials,
            crossOrigin: me.options.crossOrigin,
            headers: me.options.headers,
            eventListeners: {
                processCompleted: callback,
                processFailed: callback
            }
        });
        getLayersInfoService.processAsync();
    }

    /**
     * @function ol.supermap.LayerInfoService.prototype.setLayerInfo
     * @description 设置图层信息服务。可以实现临时图层中子图层的修改。
     * @param {SuperMap.SetLayerInfoParameters} params - 设置图层信息参数类。
     * @param {RequestCallback} callback - 回调函数。
     */
    setLayerInfo(params, callback) {
        if (!params) {
            return;
        }
        var me = this,
            resourceID = params.resourceID,
            tempLayerName = params.tempLayerName,
            layerInfoParams = params.layerInfo;
        if (!resourceID || !tempLayerName) {
            return;
        }
        var url = CommonUtil.urlPathAppend(me.url, "tempLayersSet/" + resourceID + "/" + tempLayerName);
        var setLayerInfoService = new SetLayerInfoService(url, {
            proxy: me.options.proxy,
            withCredentials: me.options.withCredentials,
            crossOrigin: me.options.crossOrigin,
            headers: me.options.headers,
            eventListeners: {
                processCompleted: callback,
                processFailed: callback
            }
        });
        setLayerInfoService.processAsync(layerInfoParams);
    }

    /**
     * @function ol.supermap.LayerInfoService.prototype.setLayersInfo
     * @description 设置图层信息服务。可以实现创建新的临时图层和对现有临时图层的修改。
     * @param {SuperMap.SetLayersInfoParameters} params - 设置图层信息参数类,包括临时图层。
     * @param {RequestCallback} callback - 回调函数。
     */
    setLayersInfo(params, callback) {
        if (!params) {
            return;
        }
        var me = this,
            resourceID = params.resourceID,
            isTempLayers = params.isTempLayers ? params.isTempLayers : false,
            layersInfo = params.layersInfo;
        if ((isTempLayers && !resourceID) || !layersInfo) {
            return;
        }
        var setLayersInfoService = new SetLayersInfoService(me.url, {
            proxy: me.options.proxy,
            withCredentials: me.options.withCredentials,
            crossOrigin: me.options.crossOrigin,
            headers: me.options.headers,
            eventListeners: {
                processCompleted: callback,
                processFailed: callback
            },
            resourceID: resourceID,
            isTempLayers: isTempLayers
        });
        setLayersInfoService.processAsync(layersInfo);
    }

    /**
     * @function ol.supermap.LayerInfoService.prototype.setLayerStatus
     * @description 子图层显示控制服务。负责将子图层显示控制参数传递到服务端,并获取服务端返回的图层显示状态。
     * @param {SuperMap.SetLayerStatusParameters} params - 子图层显示控制参数类。
     * @param {RequestCallback} callback - 回调函数。
     */
    setLayerStatus(params, callback) {
        if (!params) {
            return;
        }
        var me = this;
        var setLayerStatusService = new SetLayerStatusService(me.url, {
            proxy: me.options.proxy,
            withCredentials: me.options.withCredentials,
            crossOrigin: me.options.crossOrigin,
            headers: me.options.headers,
            eventListeners: {
                processCompleted: callback,
                processFailed: callback
            }
        });
        setLayerStatusService.processAsync(params);
    }
}


text:
package org.apache.flink.sql.parser.dql;

import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.SqlSpecialOperator;
import org.apache.calcite.sql.SqlWriter;
import org.apache.calcite.sql.parser.SqlParserPos;

import java.util.Collections;
import java.util.List;

/** EXPLAIN (PLAN FOR)* STATEMENT sql call. */
public class SqlRichExplain extends SqlCall {

    public static final SqlSpecialOperator OPERATOR =
            new SqlSpecialOperator("EXPLAIN", SqlKind.EXPLAIN);

    private SqlNode statement;

    public SqlRichExplain(SqlParserPos pos, SqlNode statement) {
        super(pos);
        this.statement = statement;
    }

    public SqlNode getStatement() {
        return statement;
    }

    @Override
    public SqlOperator getOperator() {
        return OPERATOR;
    }

    @Override
    public List<SqlNode> getOperandList() {
        return Collections.singletonList(statement);
    }

    @Override
    public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
        writer.keyword("EXPLAIN");
        statement.unparse(writer, leftPrec, rightPrec);
    }

    @Override
    public void setOperand(int i, SqlNode operand) {
        if (i == 0) {
            statement = operand;
        } else {
            throw new UnsupportedOperationException(
                    "SqlExplain SqlNode only support index equals 1");
        }
    }
}


text:
import sys, os
import subprocess
import signal
import urllib
import urllib2
import time
from subprocess import Popen, PIPE

# fix signal error caused by omxplayer
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)

moviePlaying = False
playProcess = "";
url = ""

def getUrl(youtubeUrl):

   try:
      proc = subprocess.Popen("youtube-dl -g " + youtubeUrl, shell=True, stdout=subprocess.PIPE)
      (out, err) = proc.communicate()
      url = out.replace('\n', '')
      return url

   except KeyboardInterrupt:
      print "Exit"
      exit()

def postStuffAndReturnUrl(values):
   postUrl = 'http://localhost/player/Main.php'

   data = urllib.urlencode(values)
   req = urllib2.Request(postUrl, data)
   response = urllib2.urlopen(req)
   return response.read()

def checkForImmediatePlay():
   values = {'m' : 'playnow'}
   return postStuffAndReturnUrl(values)

def playNextInQueue():
  values = {'m' : 'next'}
  return postStuffAndReturnUrl(values)

while True:

   url = checkForImmediatePlay()

   if(url != "e"):
      if (moviePlaying):
         print "quit"
         playProcess.stdin.write('q')
         moviePlaying = False

   if (moviePlaying == False):

      if (url == "e"):
         url = playNextInQueue()

      if (url == "e"):
         print "continue"
         time.sleep(2)
         continue

      print "play"

      url = getUrl(url)

      try:
         command1='omxplayer','-o', 'hdmi', url
         playProcess = subprocess.Popen(command1, stdin=PIPE, stderr=PIPE, preexec_fn=os.setsid)

      except KeyboardInterrupt:
         playProcess.stdin.write('q')

         print "Exit"
         exit()
         os.killpg(playProcess.pid, signal.SIGTERM)

      moviePlaying = True

   if(playProcess.poll() != None):
      print "movie stopped"
      moviePlaying = False

   time.sleep(2)


text:
A C++11 library to work with quaternions, as a single header file.

## Introduction
- In mathematics, the quaternions are a number system that extends the complex numbers.
  They were first described by Irish mathematician William Rowan Hamilton in 1843 and applied to mechanics
  in three-dimensional space. A feature of quaternions is that multiplication of two quaternions is noncommutative.
  Hamilton defined a quaternion as the quotient of two directed lines in a three-dimensional space or equivalently
  as the quotient of two vectors. Quaternions find uses in both theoretical and applied mathematics, in particular
  for calculations involving three-dimensional rotations such as in three-dimensional computer graphics, computer
  vision and crystallographic texture analysis. In practical applications, they can be used alongside other methods,
  such as Euler angles and rotation matrices, or as an alternative to them, depending on the application.

## Design objectives
- This library was designed to be simple, fast and convenient.
- For simplicity, there is a single(parametric) class, quaternion::Quaternion, that lives in a single header file.
- Computing the power of a quaternion in particular has been optimized to be significantly faster than boost.
- The methods provided have been designed to make it as natural as possible to use quaternion::Quaternion.

## Usage
- include \<quaternions/src/quaternion.h\>
- using namespace quaternion;
- To build the unit tests: cmake . ; make OR make -f Makefile.mk
- To make the doc: doxygen Doxyfile.
- The file unit_tests.cpp shows usage examples for all the function in the quaternion namespace.
- The file unit_tests.cpp contains various benchmarks.

## Notes
- Boost provides quaternions at: http://www.boost.org/doc/libs/1_59_0/libs/math/doc/html/quaternions.html
  This implementation is as fast as or faster than Boost. In particular pow is much faster than Boost. The speedups
  in this implementation were obtained by factorizing the a few low powers, and re-using those factorizations for
  higher powers.
- I have tried to use intrinsics(SSE), but didn't find it to be faster than "naive" code.
- Expression templates: unless the expression templates do some serious work, gcc can optimize the code to get very
  good performance, essentially equal to expression templates. So expression templates seem to be an older technique
  that's no longer required by modern compilers(although clang seems to lag compared to gcc in terms of optimization).
- The std::complex class is reputed to be slow, mostly because it does a lot of work to comply with IEEE-754/IEC-559
  apparently. Maybe the worst of this is that this compliance is not optional, and some developers have complained
  that absolutely correct handling of the sign of infinities should not be forced on them.

## IEEE-754/IEC-559 compliance
- If the compiler supports IEC-559, which can be verified by calling std::numeric_limits::is_iec559,
  then quaternion::Quaternion will leverage this.
- However the Quaternion algorithms do not currently take extra steps to comply with IEC-559's prescribed way of handling
  NaNs, underflows, overflows...

## Tested with:
- clang
- gcc 4.8

## Requirements
- Boost is required for the unit tests, but not for the Quaternion class itself.

## Others/References
- https://en.wikipedia.org/wiki/Quaternion
- http://www.boost.org/doc/libs/1_59_0/libs/math/doc/html/quaternions.html
- *vectorclass* from Agner Fog, can be found at: http://www.agner.org/optimize/, and provides quaternion classes.
- http://www.geometrictools.com/index.html

## Quaternion synopsis

### Quaternion\<T\> members
#### Constructors
    Quaternion(T a=0, T b=0, T c=0, T d=0)

    template<typename T1 = T, IS_NOT_ITERATOR(T1)>
    Quaternion(T1 a=0, T1 b=0, T1 c=0, T1 d=0)

    template<typename T1>
    Quaternion(const std::complex<T1> &x, const std::complex<T1> &y=std::complex<T1>(0, 0))

    template<typename T1 = T>
    Quaternion(T1 *it)

    template<typename It, IS_ITERATOR(It)>
    Quaternion(It it)

    template<typename T1>
    Quaternion(const Quaternion<T1> &y)

    template<typename T1>
    Quaternion & operator=(const Quaternion<T1> &other)

#### Accessors
    T a() const
    T b() const
    T c() const
    T d() const

    std::complex<T> c1() const
    std::complex<T> c2() const

    T to_real() const
    std::complex<T> to_complex() const
    std::array<T, 4> to_array() const

    T real() const
    Quaternion unreal() const

    T norm_squared() const
    T abs() const
    T unreal_norm_squared() const

#### Tests
    template<typename T1 = T>
    bool is_unit(T1 eps=0) const

    template<typename T1 = T>
    bool is_real(T1 eps=0) const

    template<typename T1 = T>
    bool is_complex(T1 eps=0) const

    template<typename T1 = T>
    bool is_unreal(T1 eps=0) const

#### Arithmetic
    Quaternion operator+() const
    Quaternion operator-() const
    Quaternion operator+=(T y)
    Quaternion operator-=(T y)
    Quaternion operator*=(T k)
    Quaternion operator/=(T k)

    template<typename T1>
    Quaternion operator+=(const std::complex<T1> &y)

    template<typename T1>
    Quaternion operator-=(const std::complex<T1> &y)

    template<typename T1>
    Quaternion operator*=(const std::complex<T1> &y)

    template<typename T1>
    Quaternion operator/=(const std::complex<T1> &y)

    template<typename T1>
    Quaternion operator+=(const Quaternion<T1> &y)

    template<typename T1>
    Quaternion operator-=(const Quaternion<T1> &y)

    template<typename T1>
    Quaternion operator*=(const Quaternion<T1> &y)

    template<typename T1>
    Quaternion operator/=(const Quaternion<T1> &y)

### Typedef
    typedef Quaternion<float> Qf
    typedef Quaternion<double> Qd
    typedef Quaternion<long double> Qld

    template<typename T>
    using polar_representation = std::array<T, 5>

    template<typename T>
    using matrix_representation = std::array<std::array<std::complex<T>, 2>, 2>

    template<typename T>
    using rotation_matrix = std::array<std::array<T, 3>, 3>

### Enumerations
    enum  DisplayStyle { q_nice, q_compact }

### Predefined constants
    const Qf Qf_1(1)
    const Qf Qf_i(0, 1)
    const Qf Qf_j(0, 0, 1)
    const Qf Qf_k(0, 0, 0, 1)

    const Qd Qd_1(1)
    const Qd Qd_i(0, 1)
    const Qd Qd_j(0, 0, 1)
    const Qd Qd_k(0, 0, 0, 1)

    const Qld Qld_1(1)
    const Qld Qld_i(0, 1)
    const Qld Qld_j(0, 0, 1)
    const Qld Qld_k(0, 0, 0, 1)

### Functions
#### Constructors
    template<typename T>
    Quaternion<T> spherical(T rho, T theta, T phi1, T phi2)

    template<typename T>
    Quaternion<T> semipolar(T rho, T alpha, T theta1, T theta2)

    template<typename T>
    Quaternion<T> multipolar(T rho1, T theta1, T rho2, T theta2)

    template<typename T>
    Quaternion<T> cylindrospherical(T t, T radius, T longitude, T latitude)

    template<typename T>
    Quaternion<T> cylindrical(T r, T angle, T h1, T h2)

    template<typename T>
    polar_representation<T> to_polar_representation(const Quaternion<T> &x)

    template<typename T>
    matrix_representation<T> to_matrix_representation(const Quaternion<T> &x)

    template<typename T>
    rotation_matrix<T> to_rotation_matrix(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> from_rotation_matrix(const rotation_matrix<T> &rm)

#### Various
    template<typename T>
    Quaternion<T> conj(const Quaternion<T> &x)

    template<typename T>
    T norm_squared(const Quaternion<T> &x)

    template<typename T>
    T abs(const Quaternion<T> &x)

    template<typename T>
    T unreal_norm_squared(const Quaternion<T> &x)

    template<typename T>
    T norm_l0(const Quaternion<T> &x)

    template<typename T>
    T norm_l1(const Quaternion<T> &x)

    template<typename T , typename T1>
    T norm_lk(const Quaternion<T> &x, T1 k)

    template<typename T>
    T norm_sup(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> normalize(const Quaternion<T> &x)

#### Tests
    template<typename T , typename T1 = T>
    bool is_unit(const Quaternion<T> &x, T1 eps=0)

    template<typename T , typename T1 = T>
    bool is_real(const Quaternion<T> &x, T1 eps=0)

    template<typename T , typename T1 = T>
    bool is_complex(const Quaternion<T> &x, T1 eps=0)

    template<typename T , typename T1 = T>
    bool is_unreal(const Quaternion<T> &x, T1 eps=0)

#### Equality
    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator==(const Quaternion<T> &x, T2 y)

    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator==(T2 y, const Quaternion<T> &x)

    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator!=(const Quaternion<T> &x, T2 y)

    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator!=(T2 y, const Quaternion<T> &x)

    template<typename T , typename T2 , typename T3 , IS_CONVERTIBLE(T2, T) , IS_CONVERTIBLE(T3, T)>
    bool nearly_equal(const Quaternion<T> &x, T2 y, T3 eps)

    template<typename T , typename T2 , typename T3 , IS_CONVERTIBLE(T2, T) , IS_CONVERTIBLE(T3, T)>
    bool nearly_equal(T2 y, const Quaternion<T> &x, T3 eps)

    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator==(const Quaternion<T> &x, const std::complex<T2> &y)

    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator!=(const Quaternion<T> &x, const std::complex<T2> &y)

    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator==(const std::complex<T2> &y, const Quaternion<T> &x)

    template<typename T , typename T2 , IS_CONVERTIBLE(T2, T)>
    bool operator!=(const std::complex<T2> &y, const Quaternion<T> &x)

    template<typename T , typename T2 , typename T3 , IS_CONVERTIBLE(T2, T) , IS_CONVERTIBLE(T3, T)>
    bool nearly_equal(const Quaternion<T> &x, const std::complex<T2> &y, T3 eps)

    template<typename T , typename T2 , typename T3 , IS_CONVERTIBLE(T2, T) , IS_CONVERTIBLE(T3, T)>
    bool nearly_equal(const std::complex<T2> &y, const Quaternion<T> &x, T3 eps)

    template<typename T>
    bool operator==(const Quaternion<T> &x, const Quaternion<T> &y)

    template<typename T>
    bool operator!=(const Quaternion<T> &x, const Quaternion<T> &y)

    template<typename T , typename T2 , typename T3 , IS_CONVERTIBLE(T2, T) , IS_CONVERTIBLE(T3, T)>
    bool nearly_equal(const Quaternion<T> &x, const Quaternion<T2> &y, T3 eps)

#### Arithmetic
    template<typename T , typename T1>
    Quaternion<T> operator+(const Quaternion<T> &x, T1 y)

    template<typename T , typename T1>
    Quaternion<T> operator+(T1 y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator+(const Quaternion<T> &x, std::complex<T> &y)

    template<typename T>
    Quaternion<T> operator+(std::complex<T> &y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator+(const Quaternion<T> &x, const Quaternion<T> &y)

    template<typename T , typename T1>
    Quaternion<T> operator-(const Quaternion<T> &x, T1 y)

    template<typename T , typename T1>
    Quaternion<T> operator-(T1 y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator-(const Quaternion<T> &x, std::complex<T> &y)

    template<typename T>
    Quaternion<T> operator-(std::complex<T> &y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator-(const Quaternion<T> &x, const Quaternion<T> &y)

    template<typename T , typename T1>
    Quaternion<T> operator*(const Quaternion<T> &x, T1 y)

    template<typename T , typename T1>
    Quaternion<T> operator*(T1 y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator*(const Quaternion<T> &x, std::complex<T> &y)

    template<typename T>
    Quaternion<T> operator*(std::complex<T> &y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator*(const Quaternion<T> &x, const Quaternion<T> &y)

    template<typename T>
    Quaternion<T> inverse(const Quaternion<T> &x)

    template<typename T , typename T1>
    Quaternion<T> operator/(const Quaternion<T> &x, T1 y)

    template<typename T , typename T1>
    Quaternion<T> operator/(T1 y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator/(const Quaternion<T> &x, std::complex<T> &y)

    template<typename T>
    Quaternion<T> operator/(std::complex<T> &y, const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> operator/(const Quaternion<T> &x, const Quaternion<T> &y)

#### Dot, cross product, commutator
    template<typename T>
    T dot(const Quaternion<T> &x, const Quaternion<T> &y)

    template<typename T>
    Quaternion<T> cross(const Quaternion<T> &x, const Quaternion<T> &y)

    template<typename T>
    Quaternion<T> commutator(const Quaternion<T> &x, const Quaternion<T> &y)

#### Transcendentals
    template<typename T>
    Quaternion<T> exp(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> log(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> pow2(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> pow3(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> pow4(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> pow(const Quaternion<T> &x, int expt)

    template<typename T>
    Quaternion<T> pow(const Quaternion<T> &x, T a)

    template<typename T>
    Quaternion<T> pow(const Quaternion<T> &x, const Quaternion<T> &a)

    template<typename T>
    Quaternion<T> cos(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> sin(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> tan(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> cosh(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> sinh(const Quaternion<T> &x)

    template<typename T>
    Quaternion<T> tanh(const Quaternion<T> &x)

#### Algorithms
    template<typename T , typename K>
    Quaternion<T> axby(K k1, const Quaternion<T> &x, K k2, const Quaternion<T> &y)


text:
namespace Microsoft.Azure.Devices.Client.Transport.Mqtt
{
    using System;
    using DotNetty.Transport.Channels;

    public class ChannelMessageProcessingException : Exception
    {
        public ChannelMessageProcessingException(Exception innerException, IChannelHandlerContext context)
            : base(string.Empty, innerException)
        {
            this.Context = context;
        }

        public IChannelHandlerContext Context { get; private set; }
    }
}