text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WebsitePanel.Portal.VPSForPC {

    public partial class VdcFastCreateServer {

        /// <summary>
        /// asyncTasks control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;

        /// <summary>
        /// breadcrumb control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::WebsitePanel.Portal.VPSForPC.UserControls.Breadcrumb breadcrumb;

        /// <summary>
        /// menu control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::WebsitePanel.Portal.VPSForPC.UserControls.Menu menu;

        /// <summary>
        /// imgIcon control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Image imgIcon;

        /// <summary>
        /// Localize1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize Localize1;

        /// <summary>
        /// messageBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;

        /// <summary>
        /// validatorsSummary control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ValidationSummary validatorsSummary;

        /// <summary>
        /// locSubTitle control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize locSubTitle;

        /// <summary>
        /// locDescription control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize locDescription;

        /// <summary>
        /// Localize2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize Localize2;

        /// <summary>
        /// ValidationSummary1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ValidationSummary ValidationSummary1;

        /// <summary>
        /// locOperatingSystem control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize locOperatingSystem;

        /// <summary>
        /// listOperatingSystems control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList listOperatingSystems;

        /// <summary>
        /// OperatingSystemValidator control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator OperatingSystemValidator;

        /// <summary>
        /// Localize3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize Localize3;

        /// <summary>
        /// txtVmName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtVmName;

        /// <summary>
        /// vmNameValidator control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator vmNameValidator;

        /// <summary>
        /// btnCreate control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnCreate;

        /// <summary>
        /// btnCancel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnCancel;

        /// <summary>
        /// FormComments control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize FormComments;
    }
}


text:
<LINK REL="stylesheet" HREF="../static/styles.css">

<TITLE>FMOD_DSP_PROCESS_OPERATION</TITLE>

Firelight Technologies FMOD Studio API

FMOD_DSP_PROCESS_OPERATION

Operation type for FMOD_DSP_PROCESS_CALLBACK.

Enumeration

typedef enum {
  FMOD_DSP_PROCESS_PERFORM,
  FMOD_DSP_PROCESS_QUERY
} FMOD_DSP_PROCESS_OPERATION;

Values

FMOD_DSP_PROCESS_PERFORM

Process the incoming audio in 'inbufferarray' and output to 'outbufferarray'.

FMOD_DSP_PROCESS_QUERY

The DSP is being queried for the expected output format and whether it needs to process audio or should be bypassed.  The function should return FMOD_OK, or FMOD_ERR_DSP_DONTPROCESS or FMOD_ERR_DSP_SILENCE if audio can pass through unprocessed. See remarks for more.  If audio is to be processed, 'outbufferarray' must be filled with the expected output format, channel count and mask.

Remarks

A process callback will be called twice per mix for a DSP unit.  Once with the FMOD_DSP_PROCESS_QUERY command, then conditionally, FMOD_DSP_PROCESS_PERFORM.

FMOD_DSP_PROCESS_QUERY is to be handled only by filling out the outputarray information, and returning a relevant return code.

It should not really do any logic besides checking and returning one of the following codes:

- FMOD_OK - Meaning yes, it should execute the dsp process function with FMOD_DSP_PROCESS_PERFORM

- FMOD_ERR_DSP_DONTPROCESS - Meaning no, it should skip the process function and not call it with FMOD_DSP_PROCESS_PERFORM.

- FMOD_ERR_DSP_SILENCE - Meaning no, it should skip the process function and not call it with FMOD_DSP_PROCESS_PERFORM, AND, tell the signal chain to follow that it is now idle, so that no more processing happens down the chain.

If audio is to be processed, 'outbufferarray' must be filled with the expected output format, channel count and mask.  Mask can be 0.

FMOD_DSP_PROCESS_PROCESS  is to be handled by reading the data from the input, processing it, and writing it to the output.  Always write to the output buffer and fill it fully to avoid unpredictable audio output.

Always return FMOD_OK, the return value is ignored from the process stage.

See Also

FMOD_DSP_DESCRIPTION

Version 1.08.02 Built on Apr 14, 2016

redpajama_set_name: RedPajamaGithub


text:
(function ($) {
  Drupal.behaviors.BiblioHighlight = {
    attach: function (context, settings) {
      $('input#biblio-highlight', context).click(function(e) {
        $("div.suspect").toggleClass('biblio-highlight');
      });
    }
  };
}(jQuery));


text:
var _                = require('lodash'),
    dataProvider     = require('../models'),
    settings         = require('./settings'),
    mail             = require('./mail'),
    globalUtils      = require('../utils'),
    utils            = require('./utils'),
    Promise          = require('bluebird'),
    errors           = require('../errors'),
    config           = require('../config'),
    authentication;

function setupTasks(object) {
    var setupUser,
        internal = {context: {internal: true}};

    return utils.checkObject(object, 'setup').then(function (checkedSetupData) {
        setupUser = {
            name: checkedSetupData.setup[0].name,
            email: checkedSetupData.setup[0].email,
            password: checkedSetupData.setup[0].password,
            blogTitle: checkedSetupData.setup[0].blogTitle,
            status: 'active'
        };

        return dataProvider.User.findOne({role: 'Owner', status: 'all'});
    }).then(function (ownerUser) {
        if (ownerUser) {
            return dataProvider.User.setup(setupUser, _.extend({id: ownerUser.id}, internal));
        } else {
            return dataProvider.Role.findOne({name: 'Owner'}).then(function (ownerRole) {
                setupUser.roles = [ownerRole.id];
                return dataProvider.User.add(setupUser, internal);
            });
        }
    }).then(function (user) {
        var userSettings = [];

        // Handles the additional values set by the setup screen.
        if (!_.isEmpty(setupUser.blogTitle)) {
            userSettings.push({key: 'title', value: setupUser.blogTitle});
            userSettings.push({key: 'description', value: 'Thoughts, stories and ideas.'});
        }

        setupUser = user.toJSON(internal);
        return settings.edit({settings: userSettings}, {context: {user: setupUser.id}});
    }).then(function () {
        return Promise.resolve(setupUser);
    });
}

/**
 * ## Authentication API Methods
 *
 * **See:** [API Methods](index.js.html#api%20methods)
 */
authentication = {

    /**
     * ## Generate Reset Token
     * generate a reset token for a given email address
     * @param {Object} object
     * @returns {Promise(passwordreset)} message
     */
    generateResetToken: function generateResetToken(object) {
        var expires = Date.now() + globalUtils.ONE_DAY_MS,
            email;

        return authentication.isSetup().then(function (result) {
            var setup = result.setup[0].status;

            if (!setup) {
                return Promise.reject(new errors.NoPermissionError('Setup must be completed before making this request.'));
            }

            return utils.checkObject(object, 'passwordreset');
        }).then(function (checkedPasswordReset) {
            if (checkedPasswordReset.passwordreset[0].email) {
                email = checkedPasswordReset.passwordreset[0].email;
            } else {
                return Promise.reject(new errors.BadRequestError('No email provided.'));
            }

            return settings.read({context: {internal: true}, key: 'dbHash'})
            .then(function (response) {
                var dbHash = response.settings[0].value;
                return dataProvider.User.generateResetToken(email, expires, dbHash);
            }).then(function (resetToken) {
                var baseUrl = config.forceAdminSSL ? (config.urlSSL || config.url) : config.url,
                    resetUrl = baseUrl.replace(/\/$/, '') + '/ghost/reset/' + globalUtils.encodeBase64URLsafe(resetToken) + '/';

                return mail.generateContent({data: {resetUrl: resetUrl}, template: 'reset-password'});
            }).then(function (emailContent) {
                var payload = {
                    mail: [{
                        message: {
                            to: email,
                            subject: 'Reset Password',
                            html: emailContent.html,
                            text: emailContent.text
                        },
                        options: {}
                    }]
                };
                return mail.send(payload, {context: {internal: true}});
            }).then(function () {
                return Promise.resolve({passwordreset: [{message: 'Check your email for further instructions.'}]});
            }).catch(function (error) {
                return Promise.reject(error);
            });
        });
    },

    /**
     * ## Reset Password
     * reset password if a valid token and password (2x) is passed
     * @param {Object} object
     * @returns {Promise(passwordreset)} message
     */
    resetPassword: function resetPassword(object) {
        var resetToken,
            newPassword,
            ne2Password;

        return authentication.isSetup().then(function (result) {
            var setup = result.setup[0].status;

            if (!setup) {
                return Promise.reject(new errors.NoPermissionError('Setup must be completed before making this request.'));
            }

            return utils.checkObject(object, 'passwordreset');
        }).then(function (checkedPasswordReset) {
            resetToken = checkedPasswordReset.passwordreset[0].token;
            newPassword = checkedPasswordReset.passwordreset[0].newPassword;
            ne2Password = checkedPasswordReset.passwordreset[0].ne2Password;

            return settings.read({context: {internal: true}, key: 'dbHash'}).then(function (response) {
                var dbHash = response.settings[0].value;
                return dataProvider.User.resetPassword({
                    token: resetToken,
                    newPassword: newPassword,
                    ne2Password: ne2Password,
                    dbHash: dbHash
                });
            }).then(function () {
                return Promise.resolve({passwordreset: [{message: 'Password changed successfully.'}]});
            }).catch(function (error) {
                return Promise.reject(new errors.UnauthorizedError(error.message));
            });
        });
    },

    /**
     * ### Accept Invitation
     * @param {User} object the user to create
     * @returns {Promise(User}} Newly created user
     */
    acceptInvitation: function acceptInvitation(object) {
        var resetToken,
            newPassword,
            ne2Password,
            name,
            email;

        return authentication.isSetup().then(function (result) {
            var setup = result.setup[0].status;

            if (!setup) {
                return Promise.reject(new errors.NoPermissionError('Setup must be completed before making this request.'));
            }

            return utils.checkObject(object, 'invitation');
        }).then(function (checkedInvitation) {
            resetToken = checkedInvitation.invitation[0].token;
            newPassword = checkedInvitation.invitation[0].password;
            ne2Password = checkedInvitation.invitation[0].password;
            email = checkedInvitation.invitation[0].email;
            name = checkedInvitation.invitation[0].name;

            return settings.read({context: {internal: true}, key: 'dbHash'}).then(function (response) {
                var dbHash = response.settings[0].value;
                return dataProvider.User.resetPassword({
                    token: resetToken,
                    newPassword: newPassword,
                    ne2Password: ne2Password,
                    dbHash: dbHash
                });
            }).then(function (user) {
                // Setting the slug to '' has the model regenerate the slug from the user's name
                return dataProvider.User.edit({name: name, email: email, slug: ''}, {id: user.id});
            }).then(function () {
                return Promise.resolve({invitation: [{message: 'Invitation accepted.'}]});
            }).catch(function (error) {
                return Promise.reject(new errors.UnauthorizedError(error.message));
            });
        });
    },

    /**
     * ### Check for invitation
     * @param {Object} options
     * @param {string} options.email The email to check for an invitation on
     * @returns {Promise(Invitation}} An invitation status
     */
    isInvitation: function isInvitation(options) {
        return authentication.isSetup().then(function (result) {
            var setup = result.setup[0].status;

            if (!setup) {
                return Promise.reject(new errors.NoPermissionError('Setup must be completed before making this request.'));
            }

            if (options.email) {
                return dataProvider.User.findOne({email: options.email, status: 'invited'}).then(function (response) {
                    if (response) {
                        return {invitation: [{valid: true}]};
                    } else {
                        return {invitation: [{valid: false}]};
                    }
                });
            } else {
                return Promise.reject(new errors.BadRequestError('The server did not receive a valid email'));
            }
        });
    },

    isSetup: function isSetup() {
        return dataProvider.User.query(function (qb) {
            qb.whereIn('status', ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked']);
        }).fetch().then(function (users) {
            if (users) {
                return Promise.resolve({setup: [{status: true}]});
            } else {
                return Promise.resolve({setup: [{status: false}]});
            }
        });
    },

    setup: function setup(object) {
        var setupUser;

        return authentication.isSetup().then(function (result) {
            var setup = result.setup[0].status;

            if (setup) {
                return Promise.reject(new errors.NoPermissionError('Setup has already been completed.'));
            }

            return setupTasks(object);
        }).then(function (result) {
            setupUser = result;

            var data = {
                ownerEmail: setupUser.email
            };

            return mail.generateContent({data: data, template: 'welcome'});
        }).then(function (emailContent) {
            var message = {
                    to: setupUser.email,
                    subject: 'Your New Ghost Blog',
                    html: emailContent.html,
                    text: emailContent.text
                },
                payload = {
                    mail: [{
                        message: message,
                        options: {}
                    }]
                };

            mail.send(payload, {context: {internal: true}}).catch(function (error) {
                errors.logError(
                    error.message,
                    'Unable to send welcome email, your blog will continue to function.',
                    'Please see http://support.ghost.org/mail/ for instructions on configuring email.'
                );
            });
        }).then(function () {
            return Promise.resolve({users: [setupUser]});
        });
    },

    updateSetup: function updateSetup(object, options) {
        if (!options.context || !options.context.user) {
            return Promise.reject(new errors.NoPermissionError('You are not logged in.'));
        }

        return dataProvider.User.findOne({role: 'Owner', status: 'all'}).then(function (result) {
            var user = result.toJSON();

            if (user.id !== options.context.user) {
                return Promise.reject(new errors.NoPermissionError('You are not the blog owner.'));
            }

            return setupTasks(object);
        }).then(function (result) {
            return Promise.resolve({users: [result]});
        });
    },

    revoke: function (object) {
        var token;

        if (object.token_type_hint && object.token_type_hint === 'access_token') {
            token = dataProvider.Accesstoken;
        } else if (object.token_type_hint && object.token_type_hint === 'refresh_token') {
            token = dataProvider.Refreshtoken;
        } else {
            return errors.BadRequestError('Invalid token_type_hint given.');
        }

        return token.destroyByToken({token: object.token}).then(function () {
            return Promise.resolve({token: object.token});
        }, function () {
            // On error we still want a 200. See https://tools.ietf.org/html/rfc7009#page-5
            return Promise.resolve({token: object.token, error: 'Invalid token provided'});
        });
    }
};

module.exports = authentication;


text:
import React from 'react'
import { render } from 'react-dom'
import { hello, goodbye } from './lib'

render(
	<div>
		{hello}
		{goodbye}
	</div>,
	document.getElementById('react-container')
)


text:
import { Class } from 'orbit/lib/objects';

export default Class.extend({
	init: function(firebaseClient){
		this._firebaseClient = firebaseClient;
	},

	handles: function(operation){
		return ["replace", "add"].indexOf(operation.op) !== -1 && operation.path.length === 3 && !operation.path[2].match(/^__/);
	},

	transform: function(operation){
		return this._firebaseClient.set(operation.path, operation.value);
	}
});


text:
(function($) {

    $.djangoAjaxPost = function(element, options) {

        var defaults = {
            postUrl: '',                                        // Post URL
            postData: '',                                       // Post data {}

            overlayMessage: 'Requesting...',                    // Overlay message during post
            overlaySuccess: 'Success',                          // Success message on overlay
            overlayGif: 'img/loading.gif',                   // Loading gif location
            successMessage: 'Thank you.',                       // Replace form text with success message

            prependOverlayTo: 'body',                           // Prepend element to

            initalDelay: 800,                                   // This delay shows the overlay message for this duration
            successDelay: 300,                                  // This delay shows the success message for this duration
        }

        var plugin = this;

        plugin.settings = {}

        var $element = $(element),
             element = element;

        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);

            // Create overlay HTML if does not already exist
            if ($('#overlay').length == 0){
                var overlayHTML = '

' + plugin.settings.overlayMessage + '

';
                var overlay = $(overlayHTML);
                overlay.prependTo($(plugin.settings.prependOverlayTo));
            }

            // As per Django documentation
            // https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/
            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    function getCookie(name) {
                        var cookieValue = null;
                        if (document.cookie && document.cookie != '') {
                            var cookies = document.cookie.split(';');
                            for (var i = 0; i < cookies.length; i++) {
                                var cookie = jQuery.trim(cookies[i]);
                                // Does this cookie string begin with the name we want?
                            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                break;
                            }
                        }
                    }
                    return cookieValue;
                    }
                    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                    }
                }
            });

            // Make the AJAX request
            $.ajax({
                url : plugin.settings.postUrl,
                data : plugin.settings.postData,
                type : "POST",

                success : function(json) {
                    // set time out to delay the overlay text, so user can see it
                    setTimeout(function () {
                        // update the overlay text to show the success message
                        $('.ajaxOverlayText').text(plugin.settings.overlaySuccess);

                        // set time out to show success message
                        setTimeout(function () {
                            // hide the overlay
                            overlay.hide();
                            // set the success message in the form
                            $element.after(plugin.settings.successMessage)
                            // hide the rest of the form
                            $element.hide();

                        }, plugin.settings.successDelay);

                    }, plugin.settings.initalDelay);
                },

                error : function(xhr,errmsg,err) {
                    console.log(xhr.status + ": " + xhr.responseText);
                }
            });

        }

        plugin.init();

    }

    $.fn.djangoAjaxPost = function(options) {

        return this.each(function() {
            if (undefined == $(this).data('djangoAjaxPost')) {
                var plugin = new $.djangoAjaxPost(this, options);
                $(this).data('djangoAjaxPost', plugin);
            }
        });

    }

})(jQuery);


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var classNames = require("classnames");
var PureRender = require("pure-render-decorator");
var React = require("react");
var Classes = require("../../common/classes");
// this component is simple enough that tests would be purely tautological.
/* istanbul ignore next */
var ControlGroup = (function (_super) {
    tslib_1.__extends(ControlGroup, _super);
    function ControlGroup() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ControlGroup.prototype.render = function () {
        var _a = this.props, children = _a.children, className = _a.className, fill = _a.fill, vertical = _a.vertical, htmlProps = tslib_1.__rest(_a, ["children", "className", "fill", "vertical"]);
        var rootClasses = classNames(Classes.CONTROL_GROUP, (_b = {},
            _b[Classes.FILL] = fill,
            _b[Classes.VERTICAL] = vertical,
            _b), className);
        return (React.createElement("div", tslib_1.__assign({}, htmlProps, { className: rootClasses }), children));
        var _b;
    };
    ControlGroup.displayName = "Blueprint.ControlGroup";
    ControlGroup = tslib_1.__decorate([
        PureRender
    ], ControlGroup);
    return ControlGroup;
}(React.Component));
exports.ControlGroup = ControlGroup;
exports.ControlGroupFactory = React.createFactory(ControlGroup);


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

<title>org.apache.cassandra.io.sstable.format.big Class Hierarchy (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.cassandra.io.sstable.format.big

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.cassandra.io.sstable.format.big.BigFormat (implements org.apache.cassandra.io.sstable.format.SSTableFormat)

org.apache.cassandra.io.sstable.format.big.BigTableScanner (implements org.apache.cassandra.io.sstable.ISSTableScanner)

org.apache.cassandra.io.sstable.format.big.BigTableScanner.EmptySSTableScanner (implements org.apache.cassandra.io.sstable.ISSTableScanner)

org.apache.cassandra.io.sstable.SSTable

org.apache.cassandra.io.sstable.format.SSTableReader (implements org.apache.cassandra.utils.concurrent.SelfRefCounted<T>)

org.apache.cassandra.io.sstable.format.big.BigTableReader

org.apache.cassandra.io.sstable.format.SSTableWriter (implements org.apache.cassandra.utils.concurrent.Transactional)

org.apache.cassandra.io.sstable.format.big.BigTableWriter

com.google.common.collect.UnmodifiableIterator<E> (implements java.util.Iterator<E>)

com.google.common.collect.AbstractIterator<T>

org.apache.cassandra.io.sstable.format.big.BigTableScanner.KeyScanningIterator

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5"
            android:clickable="true"
            android:onClick="chessTopPress"
            android:background="#4c000000">

            <LinearLayout
                android:id="@+id/chess_top_init_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:orientation="horizontal">

                <EditText
                    android:id="@+id/chess_top_init_min"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:width="100dp"
                    android:ems="10"
                    android:hint="@string/min_hint"
                    android:inputType="number"
                    android:textSize="50dp" />

                <TextView
                    android:id="@+id/chess_top_init_colon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/colon"
                    android:textSize="50dp" />

                <EditText
                    android:id="@+id/chess_top_init_sec"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:width="100dp"
                    android:ems="10"
                    android:hint="@string/sec_hint"
                    android:inputType="number"
                    android:textSize="50dp" />
            </LinearLayout>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:id="@+id/chess_top_time_layout">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/time_zero"
                    android:id="@+id/chess_top_time"
                    android:textSize="80dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/time_zero"
                    android:id="@+id/chess_top_time_inv"
                    android:rotation="180"
                    android:textSize="80dp" />
            </LinearLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5"
            android:clickable="true"
            android:onClick="chessBottomPress"
            android:background="#ffffff">

            <LinearLayout
                android:id="@+id/chess_bottom_init_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:orientation="horizontal">

                <EditText
                    android:id="@+id/chess_bottom_init_min"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:width="100dp"
                    android:ems="10"
                    android:hint="@string/min_hint"
                    android:inputType="number"
                    android:textSize="50dp" />

                <TextView
                    android:id="@+id/chess_bottom_init_colon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/colon"
                    android:textSize="50dp"
                    android:textIsSelectable="false" />

                <EditText
                    android:id="@+id/chess_bottom_init_sec"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:width="100dp"
                    android:ems="10"
                    android:hint="@string/sec_hint"
                    android:inputType="number"
                    android:textSize="50dp" />
            </LinearLayout>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:id="@+id/chess_bottom_time_layout">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/time_zero"
                    android:id="@+id/chess_bottom_time"
                    android:textSize="80dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/time_zero"
                    android:id="@+id/chess_bottom_time_inv"
                    android:rotation="180"
                    android:textSize="80dp" />
            </LinearLayout>
        </RelativeLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_centerInParent="true">

        <Button
            android:id="@+id/chess_start"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="chessStart"
            android:text="@string/start_string" />

        <Button
            android:id="@+id/chess_reset"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="chessReset"
            android:text="@string/reset_string" />
</LinearLayout>
</RelativeLayout>


text:
@implementation SSTextView

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self setup];
    [self updateView];
}

-(void)prepareForInterfaceBuilder
{
    [super prepareForInterfaceBuilder];
    [self setup];
    [self updateView];
}

-(void)setup
{
    self.fontDictionary = [[SSTheme currentTheme] fontDictionary];
    self.colorDictionary = [[SSTheme currentTheme] colorDictionary];
}

-(void)updateView
{
    if(_fontKey)
    {
        NSAssert(self.fontDictionary[_fontKey], @"Invalid Font Key %@",_fontKey);
        [self setFont:self.fontDictionary[_fontKey]];
    }

    if(_colorKey)
    {
        NSAssert(self.colorDictionary[_colorKey], @"Invalid Color Key %@",_colorKey);
        [self setTextColor:self.colorDictionary[_colorKey]];
    }

    if(_removeTopPadding)
    {
        self.textContainerInset = UIEdgeInsetsZero;
        self.textContainer.lineFragmentPadding = 0;
    }

    if(_applyPadding)
    {
        self.textContainerInset = UIEdgeInsetsMake(_contentInsetY, _contentInsetX, _contentInsetY, _contentInsetX);
    }

    [self.layer setCornerRadius:_cornerRadius];
    [self addBorder:_borderWidth color:_borderColorKey colorDict:self.colorDictionary];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">

    <scr:component name="A"
        configuration-policy="ignore">
        <implementation class="org.apache.felix.scr.integration.components.felix5276.A" />
        <service>
            <provide interface="org.apache.felix.scr.integration.components.felix5276.A" />
        </service>
    </scr:component>

    <scr:component name="B"
        xmlns:scr="http://felix.apache.org/xmlns/scr/v1.2.0-felix"
        configuration-policy="ignore">
        <implementation class="org.apache.felix.scr.integration.components.felix5276.B" />
        <service>
            <provide interface="org.apache.felix.scr.integration.components.felix5276.B" />
        </service>
        <reference
            name="a"
            interface="org.apache.felix.scr.integration.components.felix5276.A"
            cardinality="0..1"
            policy="dynamic"
            bind="setA"
            unbind="unsetA"
        />
    </scr:component>

   <scr:component name="C"
        modified="modify"
        configuration-policy="require">
        <implementation class="org.apache.felix.scr.integration.components.felix5276.C" />
        <reference
            name="b"
            interface="org.apache.felix.scr.integration.components.felix5276.B"
            cardinality="0..1"
            policy="dynamic"
            bind="setB"
            unbind="unsetB"
        />
    </scr:component>

</components>


text:
package uk.gov.hmrc.play.filters.frontend

import org.scalactic.Equivalence
import play.api.mvc.RequestHeader

object RequestHeaderEquivalence extends Equivalence[RequestHeader] {

  def areEquivalent(h1: RequestHeader, h2: RequestHeader): Boolean = {
    h1.id == h2.id &&
    h1.tags == h2.tags &&
    h1.uri == h2.uri &&
    h1.path == h2.path &&
    h1.method == h2.method &&
    h1.version == h2.version &&
    h1.queryString == h2.queryString &&
    h1.headers.toMap == h2.headers.toMap &&
    h1.remoteAddress == h2.remoteAddress
  }
}


text:
SOURCE_DIR=$(pwd)
ORIG_DIR=$(mktemp -d)
BUILD_DIR=$(mktemp -d)
TMP_SOURCE=$(mktemp)
TMP_DEST=$(mktemp)

pushd ${ORIG_DIR}
	make -C ${SOURCE_DIR} distclean || echo "No distclean"
	${SOURCE_DIR}/configure && make dist && make distclean || (echo "Cannot create tarball" && exit 2)
	VERSION=$(grep PACKAGE_VERSION ${SOURCE_DIR}/configure | grep '=' | cut -d'=' -f2 | sed -e "s/'//g")
popd

TAR_DIR="accords-${VERSION}"
TAR_NAME="${TAR_DIR}.tar.gz"

pushd ${BUILD_DIR}
	tar xf ${ORIG_DIR}/${TAR_NAME} -C . || (echo "Cannot extract tarball" && exit 3)
	${TAR_DIR}/configure || (echo "Cannot configure target" && exit 4)
popd

SOURCE_FILES=$(find ${SOURCE_DIR} -type f -prune -not -path "${SOURCE_DIR}/.git/*" -and -prune -not -name ".gitignore" | sed -e "s|${SOURCE_DIR}/||g" | sort > ${TMP_SOURCE})
DEST_FILES=$(find ${BUILD_DIR}/${TAR_DIR}/ -type f | sed -e "s|${BUILD_DIR}/${TAR_DIR}/||g" | sort > ${TMP_DEST})

echo "The following files might be missing from Makefile's DIST variable"
diff -uw ${TMP_SOURCE} ${TMP_DEST} | grep "^-"

rm ${TMP_SOURCE} || echo "Error while removing ${TMP_SOURCE}"
rm ${TMP_DEST} || echo "Error while removing ${TMP_DEST}"
rm -rf ${ORIG_DIR}
rm -rf ${BUILD_DIR}


text:
using FluentAssertions;
using VkNet.Tests.Infrastructure;
using Xunit;

namespace VkNet.Tests.Categories.Audio;

public class GetPlaylistByIdTest : CategoryBaseTest
{
	protected override string Folder => "Audio";

	[Fact]
	public void GetPlaylistByIdTestTest()
	{
		Url = "https://api.vk.com/method/audio.getPlaylistById";

		ReadCategoryJsonPath(nameof(Api.Audio.GetPlaylistById));

		var result = Api.Audio.GetPlaylistById(-77288583, 84820009);

		result.Should()
			.NotBeNull();
	}
}


text:
<?php

/**
 * @namespace
 */
namespace Bluz\Validator\Rule;

/**
 * Class Integer
 * @package Bluz\Validator\Rule
 */
class Integer extends AbstractRule
{
    /**
     * @var string Error template
     */
    protected $template = '{{name}} must be an integer number';

    /**
     * Check input data
     * @param mixed $input
     * @return bool
     */
    public function validate($input)
    {
        return is_numeric($input) && (int) $input == $input;
    }
}


text:
Pass a loader object to the directive.

```
  <div ja-angular-loader="loader"></div>
```

# The Loader Object
The loader object should at least include a condition boolean value to toggle `ng-show` on the loader container. You can optionally pass a message and/or history array.

```
  $scope.loader = {
    condition: required boolean
    message: optional string
    history: optional array of strings
  }
```

# Example Loader Object Manipulation:
Initially set the loader object to minimum blank required values

```
  $scope.loader = {
    condition: false
    message: null
    history: []
  }
```

I like to feed the loader object via a method that takes the loader object, a message (a noun like 'Results'), present tense prefix (like 'Getting'), and past tense prefix (like 'Got'). From these parameters, I can pass the message as present tense and push the past tense to the history.

```
  feedLoader = (loader, message, present, past) ->
    unless $scope.loader.condition then $scope.loader.condition = true # only sets condition to true if it needs to
    $scope.loader.message = [present, message].join(' ') # set the message
    $scope.loader.history.push [past, message].join(' ') # add message to history
```

We then need a method to clear the loader object.

```
  clearLoader = (loader) ->
    $scope.loader = {
      condition: false
      message: null
      history: []
    }
```

Then we can use these functions at whatever points in a process we need to.

```
    # dummy process function
    processData = () ->
        # add first message (will initiate display of loader)
        feedLoader($scope.loader, 'Request', 'Making', 'Made')

        # dummy request function
        makeRequest().then (res) ->
            # update loader to second message (same method as initial)
            feedLoader($scope.loader, 'Response', 'Processing', 'Processed')

            # dummy response function
            processResponse(res).then () ->
                # clear the loader now that everything has been processed
                clearLoader($scope.loader)
```

# Loader Template:

You can style/organize the loader template in the directive as you see fit. It has a main wrapper with `ng-show` on the condition, displays the message in a `span` and history in a `ul`.

```
    <div class="loader" ng-show="loader.condition" ng-cloak>
        <div class="loader-image"></div>
        <div class="loader-message">
            <span ng-if="loader.message" ng-bind="loader.message"></span>
            <ul ng-if="loader.history">
                <li ng-if="$index < loader.history.length - 1"
                    ng-repeat="message in loader.history track by $index"
                    ng-bind="message">
                </li>
            </ul>
        </div>
    </div>
```


text:
<script type="application/ld+json">
  {
    "@context":"http:\/\/schema.org",
    "@type":"WebSite",
    "name":"{{ theme.title }}",
    "url":"{{ site.url }}"
  }
</script>
<script>
  document.documentElement.className = document.documentElement.className.replace("no-js", "js");
</script>


text:
module Refinery
  module <%= class_name.pluralize %>
    class <%= class_name %> < Refinery::Core::BaseModel
<% if table_name == namespacing.underscore.pluralize -%>
      self.table_name = 'refinery_<%= plural_name %>'
<% end -%>
<% if (text_or_string_fields = attributes.map{ |a| a.name if a.type.to_s =~ /string|text/ }.compact.uniq).any? %>
      acts_as_indexed :fields => [:<%= text_or_string_fields.join(", :") %>]
<% end -%>
<% if (text_fields = attributes.map {|a| a.name if a.type.to_s == 'text'}.compact.uniq).any? && text_fields.detect{|a| a.to_s == 'message'}.nil? %>
      alias_attribute :message, :<%= text_fields.first %>
<% elsif text_fields.empty? %>
      # def message was created automatically because you didn't specify a text field
      # when you ran the refinery:form generator. <3 <3 Refinery CMS.
      def message
        "Override def message in vendor/extensions/<%= namespacing.underscore %>/app/models/refinery/<%= namespacing.underscore %>/<%= singular_name %>.rb"
      end
<% end %>
<% unless (string_fields = attributes.map{ |a| a.name if a.type.to_s == 'string' }.compact.uniq).empty? || string_fields.detect{|f| f.to_s == 'name'} %>
      alias_attribute :name, :<%= string_fields.first %>
<% end %>
      # Add some validation here if you want to validate the user's input
<% if string_fields.any? -%>
      # We have validated the first string field for you.
      validates :<%= string_fields.first %>, :presence => true
<% else %>
      # def name was created automatically because you didn't specify a string field
      # when you ran the refinery:form generator. <3 <3 Refinery CMS.
      def name
        "Override def name in vendor/extensions/<%= namespacing.underscore %>/app/models/refinery/<%= namespacing.underscore %>/<%= singular_name %>.rb"
      end
<% end -%>
<% attributes.select{|a| a.type.to_s == 'image'}.uniq.each do |a| -%>

      belongs_to :<%= a.name.gsub("_id", "") -%>, :class_name => '::Refinery::Image'
<% end -%>
<% attributes.select{|a| a.type.to_s == 'resource'}.uniq.each do |a| -%>

      belongs_to :<%= a.name.gsub("_id", "") %>, :class_name => '::Refinery::Resource'
<% end -%>
<% attributes.select{|a| a.type.to_s =~ /radio|select/}.uniq.each do |a| -%>
      <%= a.name.pluralize.upcase %> = []
<% end -%>
    end
  end
end


text:
<title>Google OAuth2 API v1 Client Library for Java</title>

Google OAuth2 API v1 Client Library for Java

Overview

High-level details about this library can be found at
https://developers.google.com/api-client-library/java/

Release Notes

JavaDoc

Developer's Guide

Support

License

The license can be found here.

Generated service-specific Library

The generated service-specific library can be found in the top level directory
of the zip file:
google-api-services-oauth2-v1-rev125-1.21.0.jar

Eclipse

A .classpath file snippet that can be included in your project's .classpath has been provided here.
Please only use the classpathentry's you actually need (see below for details).

ProGuard

A ProGuard configuration file proguard-google-api-client.txt
is included for common settings for using the library. On Android projects, you may want to add a reference to
proguard-google-api-client.txt in the project.properties file under the
proguard.config property.

Dependencies

Dependent jars for
google-api-services-oauth2-v1-rev125-1.21.0.jar
can be found in the libs folder and the corresponding source
jars can be found in the libs-sources folder.

The dependency structure and licenses can be found in the
dependencies directory.

Dependencies for all Platforms

The following are the jars from the libs folder required for
applications on all platforms:

google-api-client-1.21.0.jar

google-oauth-client-1.21.0.jar

google-http-client-1.21.0.jar

jsr305-1.3.9.jar

google-http-client-gson-1.21.0.jar (when using GSON)

gson-2.1.jar

google-http-client-jackson2-1.21.0.jar (when using Jackson 2)

jackson-core-$2.1.3.jar

google-http-client-jdo-1.21.0.jar (when using JDO)

jdo2-api-2.3-eb.jar

Android Dependencies

The following are the jars from the libs folder required for
android applications or a newer compatible version of each dependency:

google-api-client-android-1.21.0.jar (for SDK >= 2.1)

google-http-client-android-1.21.0.jar

The libs folder also contains properties files that specify the location of source
jars for Android projects in Eclipse.

Please see the
Android
for the Android Developer's Guide.

Google App Engine Dependencies

The following are the jars from the libs folder required for
Google App Engine applications or a newer compatible version of each dependency:

google-api-client-appengine-1.21.0.jar

google-api-client-servlet-1.21.0.jar

google-oauth-client-appengine-1.21.0.jar

google-oauth-client-servlet-1.21.0.jar

google-http-client-appengine-1.21.0.jar

transaction-api-1.1.jar

Please see the
GoogleAppEngine
for the Google App Engine Developer's Guide.

Servlet Dependencies

The following are the jars from the libs folder required for
Servlet applications or a newer compatible version of each dependency:

google-api-client-servlet-1.21.0.jar

google-oauth-client-1.21.0.jar

google-oauth-client-servlet-1.21.0.jar

commons-logging-1.1.1.jar

httpclient-4.0.1.jar

httpcore-4.0.1.jar

transaction-api-1.1.jar

General Purpose Java 5 Environment Dependencies

The following are the jars from the libs folder required for
general purpose Java 5 applications (or a newer compatible version of each dependency):

google-api-client-java6-1.21.0.jar

google-oauth-client-java6-1.21.0.jar

google-oauth-client-jetty-1.21.0.jar (for Jetty 6)

jetty-6.1.26

jetty-util-6.1.26

google-oauth-client-java7-1.21.0.jar

commons-logging-1.1.1.jar

httpclient-4.0.1.jar

httpcore-4.0.1.jar


text:
package com.loop81.fxcomparer.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Simple provider which reads information about the current version for the application. The version is loaded
 * from the "version.properties" which is filled with information using a pre-package step in the Maven build.
 *
 * @author Allitico
 */
public class VersionProvider {
	private final static String PROPERTIES_SOURCE = "/version.properties";
	private final static String PROPERTY_BUILD_NAME = "build.name";
	private final static String PROPERTY_BUILD_VERSION = "build.version";
	private final static String PROPERTY_BUILD_DATE = "build.date";

	private String name = "N/A";

	private String version = "N/A";

	private String buildDate = "N/A";

	public VersionProvider() {
		Properties properties = new Properties();
		try(InputStream in = getClass().getResourceAsStream(PROPERTIES_SOURCE)) {
			properties.load(in);
			name = properties.getProperty(PROPERTY_BUILD_NAME);
			version = properties.getProperty(PROPERTY_BUILD_VERSION);
			buildDate = properties.getProperty(PROPERTY_BUILD_DATE);
		} catch (IOException e) {
			// The version file should always be there.
		}
	}

	public String getName() {
		return name;
	}

	public String getVersion() {
		return version;
	}

	public String getBuildDate() {
		return buildDate;
	}
}


text:
package model.daos

import javax.inject.Inject

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO
import com.mohiva.play.silhouette.impl.providers.OAuth2Info
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json.collection.JSONCollection

import scala.concurrent.Future

class OAuth2InfoDAO @Inject()(reactiveMongoApi: ReactiveMongoApi)
  extends DelegableAuthInfoDAO[OAuth2Info] {

  case class Container(oAuth2: OAuth2Info, loginInfo: LoginInfo)

  import play.modules.reactivemongo.json.ImplicitBSONHandlers._
  import LoginInfo.jsonFormat

  implicit val oAuth2InfoFmt = Json.format[OAuth2Info]
  implicit val oAuth2InfoLoginInfoFmt = Json.format[Container]

  val oAuth2Infos = reactiveMongoApi.db.collection[JSONCollection]("oAuth2Info")

  def find(loginInfo: LoginInfo): Future[Option[OAuth2Info]] = {
    oAuth2Infos
      .find(Json.obj("loginInfo" -> loginInfo))
      .one[Container]
      .map(_.map { con => con.oAuth2 })

  }

  def add(loginInfo: LoginInfo, authInfo: OAuth2Info): Future[OAuth2Info] =
    oAuth2Infos.save(Container(authInfo, loginInfo)).flatMap {
      result => if (result.ok) {
        Future.successful(authInfo)
      } else {
        Future.failed[OAuth2Info](new Exception("error while adding new oaut2info"))
      }
    }

  def update(loginInfo: LoginInfo, authInfo: OAuth2Info): Future[OAuth2Info] =
    oAuth2Infos.update(
      Json.obj("loginInfo" -> loginInfo),
      Json.obj("$set" -> Json.obj("oAuth2" -> authInfo))).flatMap {
      result => if (result.ok) {
        Future.successful(authInfo)
      } else {
        Future.failed[OAuth2Info](new Exception("error while adding new oaut2info"))
      }
    }

  def save(loginInfo: LoginInfo, authInfo: OAuth2Info): Future[OAuth2Info] =
    find(loginInfo).flatMap {
      case Some(_) => update(loginInfo, authInfo)
      case None => add(loginInfo, authInfo)
    }

  def remove(loginInfo: LoginInfo) =
    oAuth2Infos.remove(Json.obj("loginInfo" -> loginInfo)).map(x => Unit)

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_header_search"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dp80"
    android:orientation="vertical"
    android:paddingTop="@dimen/dp20">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@color/color_transparent"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/dp10"
            android:orientation="vertical">

            <ImageView
                android:layout_width="@dimen/dp22"
                android:layout_height="@dimen/dp22"
                android:layout_gravity="center_horizontal"
                android:background="@drawable/iv_sao" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ll_search"
            android:layout_width="0dp"
            android:layout_height="@dimen/dp30"
            android:layout_centerVertical="true"
            android:layout_marginLeft="@dimen/dp10"
            android:layout_marginRight="@dimen/dp10"
            android:layout_weight="1"
            android:background="@drawable/bg_white_radius"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_search"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:drawableLeft="@drawable/iv_search_bar"
                android:drawablePadding="4dp"
                android:gravity="center"
                android:imeOptions="actionSearch"
                android:singleLine="true"
                android:text="搜索商品名称/关键字"
                android:textColor="@color/gray_nullup"
                android:textSize="15sp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ll_scan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/dp10"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/iv_scan"
                android:layout_width="@dimen/dp22"
                android:layout_height="@dimen/dp22"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/iv_home_message" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
"""
Usage:
  calicoctl node [--ip=<IP>] [--ip6=<IP6>] [--node-image=<DOCKER_IMAGE_NAME>] [--as=<AS_NUM>] [--log-dir=<LOG_DIR>]
  calicoctl node stop [--force]
  calicoctl node bgp peer add <PEER_IP> as <AS_NUM>
  calicoctl node bgp peer remove <PEER_IP>
  calicoctl node bgp peer show [--ipv4 | --ipv6]

Description:
  Configure the main calico/node container as well as default BGP information
  for this node.

Options:
  --force                  Stop the node process even if it has active endpoints.
  --node-image=<DOCKER_IMAGE_NAME>    Docker image to use for Calico's per-node
                                      container [default: calico/node:latest]
  --log-dir=<LOG_DIR>      The directory for logs [default: /var/log/calico]
  --ip=<IP>                The local management address to use.
  --ip6=<IP6>              The local IPv6 management address to use.
  --as=<AS_NUM>            The default AS number for this node.
  --ipv4                   Show IPv4 information only.
  --ipv6                   Show IPv6 information only.
"""
import sys
import os
import sh
import docker
import netaddr
import socket

from pycalico.datastore_datatypes import IPPool
from utils import ORCHESTRATOR_ID
from utils import hostname
from utils import client
from utils import docker_client
from pycalico.datastore_datatypes import BGPPeer
from pycalico.datastore import (ETCD_AUTHORITY_ENV,
                                ETCD_AUTHORITY_DEFAULT)
from checksystem import check_system
from utils import check_ip_version
from netaddr import IPAddress
from prettytable import PrettyTable
from utils import get_container_ipv_from_arguments

DEFAULT_IPV4_POOL = IPPool("192.168.0.0/16")
DEFAULT_IPV6_POOL = IPPool("fd80:24e2:f998:72d6::/64")

def node(arguments):
    """
    Main dispatcher for node commands. Calls the corresponding helper function.

    :param arguments: A dictionary of arguments already processed through
    this file's docstring with docopt
    :return: None
    """
    if arguments.get("bgp"):
        if arguments.get("peer"):
            ip_version = get_container_ipv_from_arguments(arguments)
            if arguments.get("add"):
                node_bgppeer_add(arguments.get("<PEER_IP>"), ip_version,
                                 arguments.get("<AS_NUM>"))
            elif arguments.get("remove"):
                node_bgppeer_remove(arguments.get("<PEER_IP>"), ip_version)
            elif arguments.get("show"):
                if not ip_version:
                    node_bgppeer_show("v4")
                    node_bgppeer_show("v6")
                else:
                    node_bgppeer_show(ip_version)
    elif arguments.get("stop"):
        node_stop(arguments.get("--force"))
    else:
        node_start(ip=arguments.get("--ip"),
                   node_image=arguments['--node-image'],
                   log_dir=arguments.get("--log-dir"),
                   ip6=arguments.get("--ip6"),
                   as_num=arguments.get("--as"))

def node_start(node_image, log_dir, ip="", ip6="", as_num=None):
    """
    Create the calico-node container and establish Calico networking on this
    host.

    :param ip:  The IPv4 address of the host.
    :param node_image:  The calico-node image to use.
    :param ip6:  The IPv6 address of the host (or None if not configured)
    :param as_num:  The BGP AS Number to use for this node.  If not specified
    the global default value will be used.
    :return:  None.
    """
    # Ensure log directory exists
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # Print warnings for any known system issues before continuing
    check_system(fix=False, quit_if_error=False)

    # Get IP address of host, if none was specified
    if not ip:
        ips = get_host_ips(4)
        try:
            ip = ips.pop()
        except IndexError:
            print "Couldn't autodetect a management IP address. Please provide" \
                  " an IP by rerunning the command with the --ip=<IP_ADDRESS> flag."
            sys.exit(1)
        else:
            print "No IP provided. Using detected IP: %s" % ip

    # Verify that the chosen IP exists on the current host
    warn_if_unknown_ip(ip, ip6)

    # Warn if this hostname conflicts with an existing host
    warn_if_hostname_conflict(ip)

    # Set up etcd
    ipv4_pools = client.get_ip_pools("v4")
    ipv6_pools = client.get_ip_pools("v6")

    # Create default pools if required
    if not ipv4_pools:
        client.add_ip_pool("v4", DEFAULT_IPV4_POOL)
    if not ipv6_pools:
        client.add_ip_pool("v6", DEFAULT_IPV6_POOL)

    client.ensure_global_config()
    client.create_host(hostname, ip, ip6, as_num)

    try:
        docker_client.remove_container("calico-node", force=True)
    except docker.errors.APIError as err:
        if err.response.status_code != 404:
            raise

    etcd_authority = os.getenv(ETCD_AUTHORITY_ENV, ETCD_AUTHORITY_DEFAULT)
    etcd_authority_split = etcd_authority.split(':')
    if len(etcd_authority_split) != 2:
        print_paragraph("Invalid %s. Must take the form <address>:<port>. Value " \
              "provided is '%s'" % (ETCD_AUTHORITY_ENV, etcd_authority))
        sys.exit(1)

    etcd_authority_address = etcd_authority_split[0]
    etcd_authority_port = etcd_authority_split[1]

    # Always try to convert the address(hostname) to an IP. This is a noop if
    # the address is already an IP address.
    etcd_authority = '%s:%s' % (socket.gethostbyname(etcd_authority_address),
                                etcd_authority_port)

    environment = [
        "HOSTNAME=%s" % hostname,
        "IP=%s" % ip,
        "IP6=%s" % (ip6 or ""),
        "ETCD_AUTHORITY=%s" % etcd_authority,  # etcd host:port
        "FELIX_ETCDADDR=%s" % etcd_authority,  # etcd host:port
    ]

    binds = {
        "/proc":
            {
                "bind": "/proc_host",
                "ro": False
            },
        log_dir:
            {
                "bind": "/var/log/calico",
                "ro": False
            },
        "/usr/share/docker/plugins/": #TODO make this an optional node
        # parameter like log_dir
        #"/run/docker/plugins/":
            {
                "bind": "/usr/share/docker/plugins",
                "ro": False
            }
    }

    host_config = docker.utils.create_host_config(
        privileged=True,
        restart_policy={"Name": "Always"},
        network_mode="host",
        binds=binds)

    _find_or_pull_node_image(node_image, docker_client)
    container = docker_client.create_container(
        node_image,
        name="calico-node",
        detach=True,
        environment=environment,
        host_config=host_config,
        volumes=["/proc_host",
                 "/var/log/calico",
                 "/usr/share/docker/plugins"])
    cid = container["Id"]

    docker_client.start(container)

    print "Calico node is running with id: %s" % cid

def node_stop(force):
    if force or len(client.get_endpoints(hostname=hostname, orchestrator_id=ORCHESTRATOR_ID)) == 0:
        client.remove_host(hostname)
        try:
            docker_client.stop("calico-node")
        except docker.errors.APIError as err:
            if err.response.status_code != 404:
                raise

        print "Node stopped and all configuration removed"
    else:
        print "Current host has active endpoints so can't be stopped." + \
              " Force with --force"

def node_bgppeer_add(ip, version, as_num):
    """
    Add a new BGP peer with the supplied IP address and AS Number to this node.

    :param ip: The address to add
    :param version: v4 or v6
    :param as_num: The peer AS Number.
    :return: None
    """
    address = check_ip_version(ip, version, IPAddress)
    peer = BGPPeer(address, as_num)
    client.add_bgp_peer(version, peer, hostname=hostname)

def node_bgppeer_remove(ip, version):
    """
    Remove a global BGP peer from this node.

    :param ip: The address to use.
    :param version: v4 or v6
    :return: None
    """
    address = check_ip_version(ip, version, IPAddress)
    try:
        client.remove_bgp_peer(version, address, hostname=hostname)
    except KeyError:
        print "%s is not a configured peer for this node." % address
        sys.exit(1)
    else:
        print "BGP peer removed from node configuration"

def node_bgppeer_show(version):
    """
    Print a list of the BGP Peers for this node.
    """
    assert version in ("v4", "v6")
    peers = client.get_bgp_peers(version, hostname=hostname)
    if peers:
        heading = "Node specific IP%s BGP Peer" % version
        x = PrettyTable([heading, "AS Num"], sortby=heading)
        for peer in peers:
            x.add_row([peer.ip, peer.as_num])
        x.align = "l"
        print x.get_string(sortby=heading)
    else:
        print "No IP%s BGP Peers defined for this node.\n" % version

def get_host_ips(version):
    """
    Gets all IP addresses assigned to this host.

    :param version: Desired version of IP addresses. Can be 4 or 6
    :return: List of string representations of IP Addresses.
    """
    ip = sh.Command._create("ip")
    ip_addrs = []
    addrs_raw = ip("-o", "-%d" % version, "addr").stdout.strip().split("\n")
    for address_output in addrs_raw:
        # Each 'address_output' represents a line showing the interface ip
        values = address_output.split()
        # Ignore the loopback interface
        if 'lo' not in values:
            # Extract the IP, ensure its valid
            ip_addrs.append(str(netaddr.IPNetwork(values[3]).ip))
    return ip_addrs

def warn_if_unknown_ip(ip, ip6):
    """
    Prints a warning message if the IP addresses are not assigned to interfaces
    on the current host.

    :param ip: IPv4 address which should be present on the host.
    :param ip6: IPv6 address which should be present on the host.
    :return: None
    """
    if ip not in get_host_ips(4):
        print "WARNING: Could not confirm that the provided IPv4 address is assigned" \
              " to this host."

    if ip6 and ip6 not in get_host_ips(6):
        print "WARNING: Could not confirm that the provided IPv6 address is assigned" \
              " to this host."

def warn_if_hostname_conflict(ip):
    """
    Prints a warning message if it seems like an existing host is already running
    calico using this hostname.

    :param ip: User-provided IP address to start this node with.
    :return: Nothing
    """
    # If there's already a calico-node container on this host, they're probably
    # just re-running node to update one of the ip addresses, so skip..
    if len(docker_client.containers(filters={'name': 'calico-node'})) == 0:
        # Otherwise, check if another host with the same hostname
        # is already configured
        try:
            current_ipv4, _ = client.get_host_ips(hostname)
        except KeyError:
            # No other machine has registered configuration under this hostname.
            # This must be a new host with a unique hostname, which is the
            # expected behavior.
            pass
        else:
            if current_ipv4 != "" and current_ipv4 != ip:
                print "WARNING: Hostname '%s' is already in use with IP address " \
                      "%s. Calico requires each compute host to have a " \
                      "unique hostname. If this is your first time running " \
                      "'calicoctl node' on this host, ensure that " \
                      "another host is not already using the " \
                      "same hostname."  % (hostname, ip)

def _find_or_pull_node_image(image_name, client):
    """
    Check if Docker has a cached copy of an image, and if not, attempt to pull
    it.

    :param image_name: The full name of the image.
    :return: None.
    """
    try:
        _ = client.inspect_image(image_name)
    except docker.errors.APIError as err:
        if err.response.status_code == 404:
            # TODO: Display proper status bar
            print "Pulling Docker image %s" % image_name
            client.pull(image_name)


text:
{-# LANGUAGE EmptyDataDecls     #-}
{-# LANGUAGE FlexibleInstances  #-}
{-# LANGUAGE GADTs              #-}
{-# LANGUAGE OverloadedStrings  #-}
{-# LANGUAGE RankNTypes         #-}
{-# LANGUAGE RecordWildCards    #-}
{-# LANGUAGE StandaloneDeriving #-}

{-|
Module:      Web.JWT
License:     MIT
Maintainer:  Stefan Saasen <stefan@saasen.me>
Stability:   experimental

This implementation of JWT is based on <https://tools.ietf.org/html/rfc7519>
but currently only implements the minimum required to work with the Atlassian Connect framework.

Known limitations:

   * Only HMAC SHA-256 algorithm is currently a supported signature algorithm

   * There is currently no verification of time related information
   ('exp', 'nbf', 'iat').

   * Registered claims are not validated
-}
module Web.JWT
    (
    -- * Encoding & Decoding JWTs
    -- ** Decoding
    -- $docDecoding
      decode
    , verify
    , decodeAndVerifySignature
    -- ** Encoding
    , encodeSigned
    , encodeUnsigned

    -- * Utility functions
    -- ** Common
    , tokenIssuer
    , secret
    , binarySecret
    -- ** JWT structure
    , claims
    , header
    , signature
    -- ** JWT claims set
    , auds
    , intDate
    , numericDate
    , stringOrURI
    , stringOrURIToText
    , secondsSinceEpoch
    -- ** JWT header
    , typ
    , cty
    , alg

    -- * Types
    , UnverifiedJWT
    , VerifiedJWT
    , Signature
    , Secret
    , JWT
    , JSON
    , Algorithm(..)
    , JWTClaimsSet(..)
    , ClaimsMap
    , IntDate
    , NumericDate
    , StringOrURI
    , JWTHeader
    , JOSEHeader

    , module Data.Default
    ) where

import qualified Data.ByteString.Lazy.Char8 as BL (fromStrict, toStrict)
import qualified Data.ByteString.Extended as BS
import qualified Data.Text.Extended         as T
import qualified Data.Text.Encoding         as TE

import           Control.Applicative
import           Control.Monad
import           Crypto.Hash.Algorithms
import           Crypto.MAC.HMAC
import           Data.ByteArray.Encoding
import           Data.Aeson                 hiding (decode, encode)
import qualified Data.Aeson                 as JSON
import           Data.Default
import qualified Data.HashMap.Strict        as StrictMap
import qualified Data.Map                   as Map
import           Data.Maybe
import           Data.Scientific
import           Data.Time.Clock            (NominalDiffTime)
import qualified Network.URI                as URI
import           Prelude                    hiding (exp)

-- $setup
-- The code examples in this module require GHC's `OverloadedStrings`
-- extension:
--
-- >>> :set -XOverloadedStrings

type JSON = T.Text

{-# DEPRECATED JWTHeader "Use JOSEHeader instead. JWTHeader will be removed in 1.0" #-}
type JWTHeader = JOSEHeader

-- | The secret used for calculating the message signature
newtype Secret = Secret BS.ByteString

instance Eq Secret where
    (Secret s1) == (Secret s2) = s1 `BS.constTimeCompare` s2

instance Show Secret where
    show _ = "<secret>"

newtype Signature = Signature T.Text deriving (Show)

instance Eq Signature where
    (Signature s1) == (Signature s2) = s1 `T.constTimeCompare` s2

-- | JSON Web Token without signature verification
data UnverifiedJWT

-- | JSON Web Token that has been successfully verified
data VerifiedJWT

-- | The JSON Web Token
data JWT r where
   Unverified :: JWTHeader -> JWTClaimsSet -> Signature -> T.Text -> JWT UnverifiedJWT
   Verified   :: JWTHeader -> JWTClaimsSet -> Signature -> JWT VerifiedJWT

deriving instance Show (JWT r)

-- | Extract the claims set from a JSON Web Token
claims :: JWT r -> JWTClaimsSet
claims (Unverified _ c _ _) = c
claims (Verified _ c _) = c

-- | Extract the header from a JSON Web Token
header :: JWT r -> JOSEHeader
header (Unverified h _ _ _) = h
header (Verified h _ _) = h

-- | Extract the signature from a verified JSON Web Token
signature :: JWT r -> Maybe Signature
signature Unverified{}     = Nothing
signature (Verified _ _ s) = Just s

-- | A JSON numeric value representing the number of seconds from
-- 1970-01-01T0:0:0Z UTC until the specified UTC date/time.
{-# DEPRECATED IntDate "Use NumericDate instead. IntDate will be removed in 1.0" #-}
type IntDate = NumericDate

-- | A JSON numeric value representing the number of seconds from
-- 1970-01-01T0:0:0Z UTC until the specified UTC date/time.
newtype NumericDate = NumericDate Integer deriving (Show, Eq, Ord)

-- | Return the seconds since 1970-01-01T0:0:0Z UTC for the given 'IntDate'
secondsSinceEpoch :: NumericDate -> NominalDiffTime
secondsSinceEpoch (NumericDate s) = fromInteger s

-- | A JSON string value, with the additional requirement that while
-- arbitrary string values MAY be used, any value containing a ":"
-- character MUST be a URI [RFC3986].  StringOrURI values are
-- compared as case-sensitive strings with no transformations or
-- canonicalizations applied.
data StringOrURI = S T.Text | U URI.URI deriving (Eq)

instance Show StringOrURI where
    show (S s) = T.unpack s
    show (U u) = show u

data Algorithm = HS256 -- ^ HMAC using SHA-256 hash algorithm
                 deriving (Eq, Show)

-- | JOSE Header, describes the cryptographic operations applied to the JWT
data JOSEHeader = JOSEHeader {
    -- | The typ (type) Header Parameter defined by [JWS] and [JWE] is used to
    -- declare the MIME Media Type [IANA.MediaTypes] of this complete JWT in
    -- contexts where this is useful to the application.
    -- This parameter has no effect upon the JWT processing.
    typ :: Maybe T.Text
    -- | The cty (content type) Header Parameter defined by [JWS] and [JWE] is
    -- used by this specification to convey structural information about the JWT.
  , cty :: Maybe T.Text
    -- | The alg (algorithm) used for signing the JWT. The HS256 (HMAC using SHA-256)
    -- is the only required algorithm and the only one supported in this implementation
    -- in addition to "none" which means that no signature will be used.
    --
    -- See <http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-23#page-6>
  , alg :: Maybe Algorithm
} deriving (Eq, Show)

instance Default JOSEHeader where
    def = JOSEHeader Nothing Nothing Nothing

-- | The JWT Claims Set represents a JSON object whose members are the claims conveyed by the JWT.
data JWTClaimsSet = JWTClaimsSet {
    -- Registered Claim Names
    -- http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#ClaimsContents

    -- | The iss (issuer) claim identifies the principal that issued the JWT.
    iss                :: Maybe StringOrURI

    -- | The sub (subject) claim identifies the principal that is the subject of the JWT.
  , sub                :: Maybe StringOrURI

    -- | The aud (audience) claim identifies the audiences that the JWT is intended for according to draft 18 of the JWT spec, the aud claim is option and may be present in singular or as a list.
  , aud                :: Maybe (Either StringOrURI [StringOrURI])

    -- | The exp (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. Its value MUST be a number containing an IntDate value.
  , exp                :: Maybe IntDate

    -- | The nbf (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing.
  , nbf                :: Maybe IntDate

    -- | The iat (issued at) claim identifies the time at which the JWT was issued.
  , iat                :: Maybe IntDate

    -- | The jti (JWT ID) claim provides a unique identifier for the JWT.
  , jti                :: Maybe StringOrURI

  , unregisteredClaims :: ClaimsMap

} deriving (Show, Eq)

instance Default JWTClaimsSet where
    def = JWTClaimsSet Nothing Nothing Nothing Nothing Nothing Nothing Nothing Map.empty

-- | Encode a claims set using the given secret
--
--  @
--  let
--      cs = def { -- def returns a default JWTClaimsSet
--         iss = stringOrURI "Foo"
--       , unregisteredClaims = Map.fromList [("http://example.com/is_root", (Bool True))]
--      }
--      key = secret "secret-key"
--  in encodeSigned HS256 key cs
-- @
-- > "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiRm9vIn0.vHQHuG3ujbnBUmEp-fSUtYxk27rLiP2hrNhxpyWhb2E"
encodeSigned :: Algorithm -> Secret -> JWTClaimsSet -> JSON
encodeSigned algo secret claims = dotted [header, claim, signature]
    where claim     = encodeJWT claims
          header    = encodeJWT def {
                        typ = Just "JWT"
                      , alg = Just algo
                      }
          signature = calculateDigest algo secret (dotted [header, claim])

-- | Encode a claims set without signing it
--
--  @
--  let
--      cs = def { -- def returns a default JWTClaimsSet
--      iss = stringOrURI "Foo"
--    , iat = numericDate 1394700934
--    , unregisteredClaims = Map.fromList [("http://example.com/is_root", (Bool True))]
--  }
--  in encodeUnsigned cs
--  @
-- > "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjEzOTQ3MDA5MzQsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlLCJpc3MiOiJGb28ifQ."
encodeUnsigned :: JWTClaimsSet -> JSON
encodeUnsigned claims = dotted [header, claim, ""]
    where claim     = encodeJWT claims
          header    = encodeJWT def {
                        typ = Just "JWT"
                      , alg = Just HS256
                      }

-- | Decode a claims set without verifying the signature. This is useful if
-- information from the claim set is required in order to verify the claim
-- (e.g. the secret needs to be retrieved based on unverified information
-- from the claims set).
--
-- >>> :{
--  let
--      input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U" :: T.Text
--      mJwt = decode input
--  in fmap header mJwt
-- :}
-- Just (JOSEHeader {typ = Just "JWT", cty = Nothing, alg = Just HS256})
--
-- and
--
-- >>> :{
--  let
--      input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U" :: T.Text
--      mJwt = decode input
--  in fmap claims mJwt
-- :}
-- Just (JWTClaimsSet {iss = Nothing, sub = Nothing, aud = Nothing, exp = Nothing, nbf = Nothing, iat = Nothing, jti = Nothing, unregisteredClaims = fromList [("some",String "payload")]})
decode :: JSON -> Maybe (JWT UnverifiedJWT)
decode input = do
    (h,c,s) <- extractElems $ T.splitOn "." input
    let header' = parseJWT h
        claims' = parseJWT c
    Unverified <$> header' <*> claims' <*> (pure . Signature $ s) <*> (pure . dotted $ [h,c])
    where
        extractElems (h:c:s:_) = Just (h,c,s)
        extractElems _         = Nothing

-- | Using a known secret and a decoded claims set verify that the signature is correct
-- and return a verified JWT token as a result.
--
-- This will return a VerifiedJWT if and only if the signature can be verified using the
-- given secret.
--
-- The separation between decode and verify is very useful if you are communicating with
-- multiple different services with different secrets and it allows you to lookup the
-- correct secret for the unverified JWT before trying to verify it. If this is not an
-- isuse for you (there will only ever be one secret) then you should just use
-- 'decodeAndVerifySignature'.
--
-- >>> :{
--  let
--      input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U" :: T.Text
--      mUnverifiedJwt = decode input
--      mVerifiedJwt = verify (secret "secret") =<< mUnverifiedJwt
--  in signature =<< mVerifiedJwt
-- :}
-- Just (Signature "Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U")
verify :: Secret -> JWT UnverifiedJWT -> Maybe (JWT VerifiedJWT)
verify secret' (Unverified header' claims' unverifiedSignature originalClaim) = do
   algo <- alg header'
   let calculatedSignature = Signature $ calculateDigest algo secret' originalClaim
   guard (unverifiedSignature == calculatedSignature)
   pure $ Verified header' claims' calculatedSignature

-- | Decode a claims set and verify that the signature matches by using the supplied secret.
-- The algorithm is based on the supplied header value.
--
-- This will return a VerifiedJWT if and only if the signature can be verified
-- using the given secret.
--
-- >>> :{
--  let
--      input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U" :: T.Text
--      mJwt = decodeAndVerifySignature (secret "secret") input
--  in signature =<< mJwt
-- :}
-- Just (Signature "Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U")
decodeAndVerifySignature :: Secret -> JSON -> Maybe (JWT VerifiedJWT)
decodeAndVerifySignature secret' input = verify secret' =<< decode input

-- | Try to extract the value for the issue claim field 'iss' from the web token in JSON form
tokenIssuer :: JSON -> Maybe StringOrURI
tokenIssuer = decode >=> fmap pure claims >=> iss

-- | Create a Secret using the given key.
-- Consider using `binarySecret` instead if your key is not already a "Data.Text".
secret :: T.Text -> Secret
secret = Secret . TE.encodeUtf8

-- | Create a Secret using the given key.
binarySecret :: BS.ByteString -> Secret
binarySecret = Secret

-- | Convert the `NominalDiffTime` into an IntDate. Returns a Nothing if the
-- argument is invalid (e.g. the NominalDiffTime must be convertible into a
-- positive Integer representing the seconds since epoch).
{-# DEPRECATED intDate "Use numericDate instead. intDate will be removed in 1.0" #-}
intDate :: NominalDiffTime -> Maybe IntDate
intDate = numericDate

-- | Convert the `NominalDiffTime` into an NumericDate. Returns a Nothing if the
-- argument is invalid (e.g. the NominalDiffTime must be convertible into a
-- positive Integer representing the seconds since epoch).
numericDate :: NominalDiffTime -> Maybe NumericDate
numericDate i | i < 0 = Nothing
numericDate i         = Just $ NumericDate $ round i

-- | Convert a `T.Text` into a 'StringOrURI`. Returns a Nothing if the
-- String cannot be converted (e.g. if the String contains a ':' but is
-- *not* a valid URI).
stringOrURI :: T.Text -> Maybe StringOrURI
stringOrURI t | URI.isURI $ T.unpack t = U <$> URI.parseURI (T.unpack t)
stringOrURI t                          = Just (S t)

-- | Convert a `StringOrURI` into a `T.Text`. Returns the T.Text
-- representing the String as-is or a Text representation of the URI
-- otherwise.
stringOrURIToText :: StringOrURI -> T.Text
stringOrURIToText (S t)   = t
stringOrURIToText (U uri) = T.pack $ URI.uriToString id uri (""::String)

-- | Convert the `aud` claim in a `JWTClaimsSet` into a `[StringOrURI]`
auds :: JWTClaimsSet -> [StringOrURI]
auds jwt = case aud jwt of
    Nothing         -> []
    Just (Left a)   -> [a]
    Just (Right as) -> as

-- =================================================================================

encodeJWT :: ToJSON a => a -> T.Text
encodeJWT = TE.decodeUtf8 . convertToBase Base64URLUnpadded . BL.toStrict . JSON.encode

parseJWT :: FromJSON a => T.Text -> Maybe a
parseJWT x = case convertFromBase Base64URLUnpadded $ TE.encodeUtf8 x of
               Left _  -> Nothing
               Right s -> JSON.decode $ BL.fromStrict s

dotted :: [T.Text] -> T.Text
dotted = T.intercalate "."

-- =================================================================================

calculateDigest :: Algorithm -> Secret -> T.Text -> T.Text
calculateDigest HS256 (Secret key) msg = TE.decodeUtf8 $ convertToBase Base64URLUnpadded (hmac key (bs msg) :: HMAC SHA256)
    where
        bs = TE.encodeUtf8

-- =================================================================================

type ClaimsMap = Map.Map T.Text Value

fromHashMap :: Object -> ClaimsMap
fromHashMap = Map.fromList . StrictMap.toList

removeRegisteredClaims :: ClaimsMap -> ClaimsMap
removeRegisteredClaims input = Map.differenceWithKey (\_ _ _ -> Nothing) input registeredClaims
    where
        registeredClaims = Map.fromList $ map (\e -> (e, Null)) ["iss", "sub", "aud", "exp", "nbf", "iat", "jti"]

instance ToJSON JWTClaimsSet where
    toJSON JWTClaimsSet{..} = object $ catMaybes [
                  fmap ("iss" .=) iss
                , fmap ("sub" .=) sub
                , either ("aud" .=) ("aud" .=) <$> aud
                , fmap ("exp" .=) exp
                , fmap ("nbf" .=) nbf
                , fmap ("iat" .=) iat
                , fmap ("jti" .=) jti
            ] ++ Map.toList (removeRegisteredClaims unregisteredClaims)

instance FromJSON JWTClaimsSet where
        parseJSON = withObject "JWTClaimsSet"
                     (\o -> JWTClaimsSet
                     <$> o .:? "iss"
                     <*> o .:? "sub"
                     <*> case StrictMap.lookup "aud" o of
                         (Just as@(JSON.Array _)) -> Just <$> Right <$> parseJSON as
                         (Just (JSON.String t))   -> pure $ Left <$> stringOrURI t
                         _                        -> pure Nothing
                     <*> o .:? "exp"
                     <*> o .:? "nbf"
                     <*> o .:? "iat"
                     <*> o .:? "jti"
                     <*> pure (removeRegisteredClaims $ fromHashMap o))

instance FromJSON JOSEHeader where
    parseJSON = withObject "JOSEHeader"
                    (\o -> JOSEHeader
                    <$> o .:? "typ"
                    <*> o .:? "cty"
                    <*> o .:? "alg")

instance ToJSON JOSEHeader where
    toJSON JOSEHeader{..} = object $ catMaybes [
                  fmap ("typ" .=) typ
                , fmap ("cty" .=) cty
                , fmap ("alg" .=) alg
            ]

instance ToJSON NumericDate where
    toJSON (NumericDate i) = Number $ scientific (fromIntegral i) 0

instance FromJSON NumericDate where
    parseJSON (Number x) = return $ NumericDate $ coefficient x
    parseJSON _          = mzero

instance ToJSON Algorithm where
    toJSON HS256 = String ("HS256"::T.Text)

instance FromJSON Algorithm where
    parseJSON (String "HS256") = return HS256
    parseJSON _                = mzero

instance ToJSON StringOrURI where
    toJSON (S s)   = String s
    toJSON (U uri) = String $ T.pack $ URI.uriToString id uri ""

instance FromJSON StringOrURI where
    parseJSON (String s) | URI.isURI $ T.unpack s = return $ U $ fromMaybe URI.nullURI $ URI.parseURI $ T.unpack s
    parseJSON (String s)                          = return $ S s
    parseJSON _                                   = mzero

-- $docDecoding
-- There are three use cases supported by the set of decoding/verification
-- functions:
--
-- (1) Unsecured JWTs (<http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30#section-6>).
--      This is supported by the decode function 'decode'.
--      As a client you don't care about signing or encrypting so you only get back a 'JWT' 'UnverifiedJWT'.
--      I.e. the type makes it clear that no signature verification was attempted.
--
-- (2) Signed JWTs you want to verify using a known secret.
--      This is what 'decodeAndVerifySignature' supports, given a secret
--      and JSON it will return a 'JWT' 'VerifiedJWT' if the signature can be
--      verified.
--
-- (3) Signed JWTs that need to be verified using a secret that depends on
--      information contained in the JWT. E.g. the secret depends on
--      some claim, therefore the JWT needs to be decoded first and after
--      retrieving the appropriate secret value, verified in a subsequent step.
--      This is supported by using the `verify` function which given
--      a 'JWT' 'UnverifiedJWT' and a secret will return a 'JWT' 'VerifiedJWT' iff the
--      signature can be verified.


text:
using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Data;
using PnPTestResultsNotificationJob.Models;
using PnPTestResultsNotificationJob.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PnPTestResultsNotificationJob
{
    public class FailedTestRuns
    {
        public static List<TestSummary> GetFailedTestResults(int[] TestRunIDs, DateTime? toDate, DateTime? fromDate, int outcome, bool isAdmin)
        {
            List<TestSummary> testResults = null;

            using (PnPTestAutomationEntities dc = new PnPTestAutomationEntities())
            {
                var configDetails = from configset in dc.TestConfigurationSets
                                    select new
                                    {
                                        configset.Id,
                                        configset.AnonymousAccess,
                                        configset.Branch,
                                        configset.Name
                                    };

                if (!isAdmin)
                {
                    configDetails = configDetails.Where(c => c.AnonymousAccess == true);
                }

                var filteredTestRunSets = dc.TestRunSets.Where(c => TestRunIDs.Contains(c.Id));
                var data = (from testrunset in filteredTestRunSets
                            join testresultset in dc.TestResultSets on testrunset.Id equals testresultset.TestRunId
                            join configset in configDetails on testrunset.TestConfigurationId equals configset.Id
                            where testresultset.Outcome == outcome
                            select new
                            {
                                Outcome = testresultset.Outcome,
                                Error = testresultset.ErrorMessage,
                                StackTrace = testresultset.ErrorStackTrace,
                                TestDuration = testresultset.Duration,
                                TestCasename = testresultset.TestCaseName,
                                Id = testresultset.Id,
                                Branch = configset.Branch,
                                Configuration = configset.Name,
                                Testdate = testrunset.TestDate,
                                TestRunId = testrunset.Id
                            }).ToList();

                if (data != null && data.Any())
                {
                    testResults = (from testresult in data
                                   select new TestSummary
                                   {
                                       Outcome = testresult.Outcome,
                                       Error = testresult.Error,
                                       StackTrace = testresult.StackTrace,
                                       TestDuration = Convert.ToString(testresult.TestDuration),
                                       TestCasename = testresult.TestCasename,
                                       Id = testresult.Id,
                                       Branch = testresult.Branch,
                                       Configuration = testresult.Configuration,
                                       Testdate = testresult.Testdate,
                                       TestRunId = testresult.TestRunId
                                   }).OrderByDescending(t => t.Id).ToList();
                }

            }

            return testResults;
        }

    }
}


text:
<?php

/**
 * Subclass for representing a row from the 'report_payout_bonus' table.
 *
 *
 *
 * @package lib.model
 */
class ReportPayoutBonus extends BaseReportPayoutBonus
{
}


text:
(function() {
  module.exports = {
    Disconnected: 1,
    Preceding: 2,
    Following: 4,
    Contains: 8,
    ContainedBy: 16,
    ImplementationSpecific: 32
  };

}).call(this);


text:
from IPython.utils.syspathcontext import appended_to_syspath
import pytest

def test_append_deprecated():
    with pytest.warns(DeprecationWarning):
        appended_to_syspath(".")