text:
var allowUnsafeNewFunction = require('loophole').allowUnsafeNewFunction
var findRoot = require('find-root')
var getNearestPackageJson = require('./get-nearest-package-json')
var logger = require('./logger')
var packageName = require('./get-nearest-package-json').from(__filename).name
var path = require('path')

//
// Imports the style library (assumed to be js-standard, at the time of writing)
// and returns the correct version based on the current configuration of the
// plugin.
//
// Usage:
//
//     var style = require('./style-loader').load()
//
//     // Except for grieveous problems, you should receive a linter object for use,
//     // no error checking required by the caller.
//     style.lintText(someCode, options, otherstuff)
//
module.exports = {
  // Call to import the appropriate style engine.
  // @param filePath {String} the path to the file in the editor.
  load: function (filePath) {
    var config = atom.config.get(packageName)
    if (filePath && config.preferProjectStandard) {
      // TODO: Attempt to load the project specific standard library.
      var projectPackageJson = getNearestPackageJson.from(filePath)
      if (projectPackageJson &&
        ((projectPackageJson.dependencies && projectPackageJson.dependencies.standard) ||
        (projectPackageJson.devDependencies && projectPackageJson.devDependencies.standard))) {
        // If we have a packageJson object, findRoot should pass.
        var projectPath = findRoot(filePath)
        var standardPath = path.join(projectPath, 'node_modules', 'standard')
        try {
          logger.log('Using project specific standard library from: \'%s\'', standardPath)
          // Attempt to return the project specific standard.
          return allowUnsafeNewFunction(function () {
            return require(path.join(standardPath))
          })
        } catch (err) {
          logger.warn('\'%s\' has standard as dependency but it could not be imported from: \'%s\'', projectPath, standardPath)
          // fall through...
        }
      }
    }

    // ...else

    // NOTE: I moved this use of allowUnsafeNewFunction out of another file while
    // refactoring and simplifying the code to focus on standard style, but I'll
    // admit I don't know why we even need `allowUnsafeNewFunction`. It works,
    // good enough for now.
    return allowUnsafeNewFunction(function () {
      return require('standard')
    })
  }
}


text:
ag.ns("ag.common");

(function(){

var pathRegex = new RegExp("^(/[a-z]+)+"),

    State = function()
    {
        this.currentState = {};
        this.broker = ag.s.broker;

        window.addEventListener("hashchange", listen.bind(this, false));
        listen.call(this, true);
    },

    removeTrailingSlash = function(path)
    {
        if (path.charAt(path.length - 1) === "/")
            path = path.substr(0, path.length - 1);

        return path;
    },

    parseState = function(reqPath)
    {
        var
            path = pathRegex.test(reqPath) ? reqPath.match(pathRegex)[0] : "",
            requestString = decodeURIComponent(reqPath.substr(path.length + 1)), // length + 1 because of question mark
            request;

        try {
            request = JSON.parse(requestString);
        }
        catch(err) {
            request = requestString;
        }

        return {
            path : path,
            request : request
        };
    },

    listen = function(isInit)
    {
        var
            state = parseState(location.hash.substr(2)),
            eventName = "ag.state." + (isInit ? "init" : "change");

        this.currentState = state;

        this.broker.pub(eventName, state, this.createHash(state.path, state.request));
    };

State.prototype.createHash = function(path, request)
{
    path = removeTrailingSlash(typeof path === "string" ? path : this.currentState.path);

    var
        locPath = "#!" + path,
        requestString,
        hash = "";

    if (path || request)
    {
        if (request instanceof Array || request instanceof Object)
        {
            requestString = JSON.stringify(request);
        }
        else if (request !== undefined)
        {
            requestString = String(request);
        }

        if (path.length || requestString !== undefined)
        {
            hash = locPath + (requestString !== undefined ? "?" + requestString : "");
        }
    }

    return hash;
};

State.prototype.getCurrentState = function()
{
    return this.currentState;
};

State.prototype.getCurrentHash = function()
{
    return this.createHash(this.currentState.path, this.currentState.request);
};

State.prototype.switchTo = function(path, request)
{
    location.hash = this.createHash(path, request);
};

State.prototype.update = function(path, request)
{
    path = typeof path === "string" ? removeTrailingSlash(path) : this.currentState.path;

    var
        hash = this.createHash(path, request),
        newState = hash || location.pathname;

    history.replaceState(null, "", newState);
    this.broker.pub("ag.state.update", { path : path, request : request }, hash);
};

ag.s.state = new State();

})();

redpajama_set_name: RedPajamaGithub


text:
<?php

// $Id$

// Initialize global environment
define('INDEX_FILE_LOCATION', __FILE__);
require('lib/pkp/includes/bootstrap.inc.php');

// Serve the request
$application =& PKPApplication::getApplication();
$application->execute();


text:
//
//  PushConstants.h
//  JB4A-SDK-iOS
//
//  JB4A iOS SDK GitHub Repository
//  https://salesforce-marketingcloud.github.io/JB4A-SDK-iOS/
//

/**
 Notification that is sent when a push fails for some reason.
 */
/** @constant ETPush Notifications Sent when the data request process has started */
#define ETRequestStarted                @"ETRequestStarted"
#define ETRequestNoData                 @"ETRequestNoData"
#define ETRequestFailed                 @"ETRequestFailed"
#define ETRequestComplete               @"ETRequestComplete"
#define ETRequestFailedOnLoadingResult  @"ETRequestFailedOnLoadingResult"
#define ETRequestServiceReturnedError   @"ETRequestServiceReturnedError"
#define ETRequestServiceResponseSuccess @"ETRequestServiceResponseSuccess"
#define ETRequestFinishedWithFailure    @"ETRequestFinishedWithFailure"

/**
  Constants for dealing with other stuff
  */
#define AppLifecycleForeground          @"AppLifecycleForeground"
#define AppLifecycleBackground          @"AppLifecycleBackground"

/**
 Geofence Constants
 */
#define ETLargeGeofence                 433 // Get it? 433 North Capitol. It's been a long journey getting here.
#define ETLargeGeofenceIdentifier       @"ExactTargetMagicGlobalFence"

/**
 Caches
 */
#define ET_TAG_CACHE                    @"ET_TAG_CACHE"
#define ET_SUBKEY_CACHE                 @"ET_SUBKEY_CACHE"
#define ET_ATTR_CACHE                   @"ET_ATTR_CACHE"

/**
 Deprecation warning declaration
 */
#define __DEPRECATED_WARNING(message) __attribute((deprecated(message)))

// Tracks the BOOL for each in NSUserDefaults
static NSString * const ETProximityServicesActive = @"ETProximityServicesActive";
static NSString * const ETLocationServicesActive  = @"ETLocationServicesActive";
static NSString * const ETCloudPagesActive        = @"ETCloudPagesActive";
static NSString * const ETAnalyticsActive         = @"ETAnalyticsActive";
static NSString * const ETPIAnalyticsActive       = @"ETPIAnalyticsActive";

/**
 Push Origination State
 */
typedef NS_ENUM (NSUInteger, pushOriginationState){
    /** Initial enum value  */
    firstPushOriginationStateIndex = 0,
    /** PushOriginationStateBackground  */
    PushOriginationStateBackground = firstPushOriginationStateIndex,
    /** PushOriginationStateForeground  */
    PushOriginationStateForeground,
    /** Unknown state  */
    PushOriginationStateUnknown = 999,
    /** lastPushOriginationStateIndex */
    lastPushOriginationStateIndex = PushOriginationStateUnknown
};

/**
 configureSDKWithAppID errors
 */
typedef NS_ENUM(NSUInteger, configureSDKWithAppIDError) {
    /** Initial enum value  */
    firstconfigureSDKWithAppIDIndex = 0,
    /** configureSDKWithAppIDNoError  */
    configureSDKWithAppIDNoError = firstconfigureSDKWithAppIDIndex,
    /** configureSDKWithAppIDInvalidAppIDError  */
    configureSDKWithAppIDInvalidAppIDError,
    /** configureSDKWithAppIDInvalidAccessTokenError  */
    configureSDKWithAppIDInvalidAccessTokenError,
    /** configureSDKWithAppIDUnableToReadRandomError  */
    configureSDKWithAppIDUnableToReadRandomError,
    /** configureSDKWithAppIDDatabaseAccessError  */
    configureSDKWithAppIDDatabaseAccessError,
    /** configureSDKWithAppIDUnableToKeyDatabaseError  */
    configureSDKWithAppIDUnableToKeyDatabaseError,
    /** configureSDKWithAppIDCCKeyDerivationPBKDFError  */
    configureSDKWithAppIDCCKeyDerivationPBKDFError,
    /** configureSDKWithAppIDCCSymmetricKeyWrapError  */
    configureSDKWithAppIDCCSymmetricKeyWrapError,
    /** configureSDKWithAppIDCCSymmetricKeyUnwrapError  */
    configureSDKWithAppIDCCSymmetricKeyUnwrapError,
    /** configureSDKWithAppIDKeyChainError  */
    configureSDKWithAppIDKeyChainError,
    /** configureSDKWithAppIDUnableToReadCertificateError  */
    configureSDKWithAppIDUnableToReadCertificateError,
    /** configureSDKWithAppIDRunOnceSimultaneouslyError  */
    configureSDKWithAppIDRunOnceSimultaneouslyError,
    /** configureSDKWithAppIDRunOnceError  */
    configureSDKWithAppIDRunOnceError,
    /** configureSDKWithAppIDInvalidLocationAndProximityError  */
    configureSDKWithAppIDInvalidLocationAndProximityError,
    /** configureSDKWithAppIDSimulatorBlobError  */
    configureSDKWithAppIDSimulatorBlobError,
    /** configureSDKWithAppIDKeyChainInvalidError  */
    configureSDKWithAppIDKeyChainInvalidError,
    /** lastconfigureSDKWithAppIDIndex */
    lastconfigureSDKWithAppIDIndex = configureSDKWithAppIDKeyChainInvalidError
};

/**
 requestPIRecommendations errors
 */
typedef NS_ENUM(NSUInteger, requestPIRecommendationsError) {
    /** Initial enum value  */
    firstrequestPIRecommendationsInvalidIndex = 0,
    /** requestPIRecommendationsNoError  */
    requestPIRecommendationsNoError = firstrequestPIRecommendationsInvalidIndex,
    /** requestPIRecommendationsInvalidMidParameterError  */
    requestPIRecommendationsInvalidMidParameterError = 1024,
    /** requestPIRecommendationsInvalidRetailerParameterError  */
    requestPIRecommendationsInvalidRetailerParameterError,
    /** requestPIRecommendationsInvalidPageParameterError  */
    requestPIRecommendationsInvalidPageParameterError,
    /** requestPIRecommendationsInvalidCompletionHandlerError  */
    requestPIRecommendationsInvalidCompletionHandlerError,
    /** lastrequestPIRecommendationsInvalidIndex */
    lastrequestPIRecommendationsInvalidIndex = requestPIRecommendationsInvalidCompletionHandlerError
};

/**
 ETEventBus constants
 */

static NSString * const kDidDisplayLocationMessageNotification = @"ETEventBusDidDisplayLocationMessageNotification";
static NSString * const kDidReceiveGeofenceResponseNotification = @"ETEventBusDidReceiveGeofenceResponseNotification";
static NSString * const kDidReceiveBeaconResponseNotification = @"ETEventBusDidReceiveBeaconResponseNotification";
static NSString * const kDidEnterGeofenceNotification = @"ETEventBusDidEnterGeofenceNotification";
static NSString * const kDidExitGeofenceNotification = @"ETEventBusDidExitGeofenceNotification";
static NSString * const kDidRangeBeaconNotification = @"ETEventBusDidRangeBeaconNotification";
static NSString * const kDidReceiveRichMessagesNotification = @"ETEventBusDidReceiveRichMessagesNotification";
static NSString * const kDidReceiveCloudPagesNotification = @"ETEventBusDidReceiveRichMessagesNotification";
static NSString * const kDidReceiveLocationUpdateNotification = @"ETEventBusDidReceiveLocationUpdateNotification";

/**
 Enumeration of the type of ETMessage this is.
 */
typedef NS_ENUM(NSUInteger, MobilePushMessageType)
{
    /** Initial enum value  */
    firstMobilePushMessageTypeIndex = 0,
    /** Unknown */
    MobilePushMessageTypeUnknown = firstMobilePushMessageTypeIndex,
    /** Basic - A standard push message */
    MobilePushMessageTypeBasic,
    /** Geofence Entry */
    MobilePushMessageTypeFenceEntry = 3,
    /** Geofence Exit */
    MobilePushMessageTypeFenceExit,
    /** Proximity */
    MobilePushMessageTypeProximity,
    /** Silent Push */
    MobilePushMessageTypeSilentPush,
    /** Inbox */
    MobilePushMessageTypeInbox = 8,
    /** lastMobilePushMessageTypeIndex */
    lastMobilePushMessageTypeIndex = MobilePushMessageTypeInbox
};

/**
 Enumeration of the type of ETRegion that this is - Circle (Geofence) or Proximity (ibeacon). Polygon is not currently used.
 */
typedef NS_ENUM(NSUInteger, MobilePushGeofenceType) {
    /** Initial enum value  */
    firstMobilePushGeofenceTypeIndex = 0,
    /** MobilePushGeofenceTypeNone */
    MobilePushGeofenceTypeNone = firstMobilePushGeofenceTypeIndex,
    /** MobilePushGeofenceTypeCircle */
    MobilePushGeofenceTypeCircle,
    /** MobilePushGeofenceTypeProximity */
    MobilePushGeofenceTypeProximity = 3,
    /** lastMobilePushGeofenceTypeIndex */
    lastMobilePushGeofenceTypeIndex = MobilePushGeofenceTypeProximity
};

/**
 Enumeration to keep track of if the request is for Geofences or Proximity messages.
 */
typedef NS_ENUM(NSUInteger, ETRegionRequestType) {
    /** Initial enum value  */
    firstETRegionRequestTypeProximityIndex = 0,
    /** ETRegionRequestTypeUnknown */
    ETRegionRequestTypeUnknown = firstETRegionRequestTypeProximityIndex,
    /** ETRegionRequestTypeGeofence */
    ETRegionRequestTypeGeofence,
    /** ETRegionRequestTypeProximity */
    ETRegionRequestTypeProximity,
    /** lastETRegionRequestTypeProximityIndex */
    lastETRegionRequestTypeProximityIndex = ETRegionRequestTypeProximity
};

/**
 Bitmask of features that a message has. This is the representation of Push (AlertMessage), Push+Page (AlertMessage + Page), Page Only (Page) in the MobilePush UI.
 */
typedef NS_OPTIONS(NSUInteger, MobilePushContentType) {
    /** Unknown */
    MobilePushContentTypeNone = 0,
    /** Push Message */
    MobilePushContentTypeAlertMessage = 1 << 0,
    /** CloudPage */
    MobilePushContentTypePage = 1 << 1,
    /** Enhanced Cloud Page – Pushed Cloud Pages */
    MobilePushContentTypeEcp = 1 << 31
};

/**
 Time Unit enumeration for Message limiting.
 */
typedef NS_ENUM(NSUInteger, MobilePushMessageFrequencyUnit) {
    /** Initial enum value  */
    firstMobilePushMessageFrequencyIndex = 0,
    /** Unknown */
    MobilePushMessageFrequencyUnitNone = firstMobilePushMessageFrequencyIndex,
    /** Year */
    MobilePushMessageFrequencyUnitYear,
    /** Month */
    MobilePushMessageFrequencyUnitMonth,
    /** Week */
    MobilePushMessageFrequencyUnitWeek,
    /** Day */
    MobilePushMessageFrequencyUnitDay,
    /** Hour */
    MobilePushMessageFrequencyUnitHour,
    /** lastMobilePushMessageFrequencyIndex */
    lastMobilePushMessageFrequencyIndex = MobilePushMessageFrequencyUnitHour
};


text:
package org.terracotta.dynamic_config.cli.api.nomad;

import org.terracotta.diagnostic.model.LogicalServerState;
import org.terracotta.dynamic_config.api.model.Cluster;
import org.terracotta.dynamic_config.api.model.Node.Endpoint;
import org.terracotta.dynamic_config.api.model.nomad.DynamicConfigNomadChange;
import org.terracotta.nomad.client.change.ChangeResultReceiver;
import org.terracotta.nomad.client.recovery.RecoveryResultReceiver;
import org.terracotta.nomad.client.results.DiscoverResultsReceiver;
import org.terracotta.nomad.server.ChangeRequestState;

import java.util.Collection;
import java.util.Map;

public interface NomadManager<T> {
  void runConfigurationDiscovery(Map<Endpoint, LogicalServerState> nodes, DiscoverResultsReceiver<T> results);

  void runClusterActivation(Collection<Endpoint> nodes, Cluster cluster, ChangeResultReceiver<T> results);

  void runConfigurationChange(Cluster destinationCluster, Map<Endpoint, LogicalServerState> onlineNodes, DynamicConfigNomadChange changes, ChangeResultReceiver<T> results);

  void runConfigurationRepair(Map<Endpoint, LogicalServerState> onlineActivatedNodes, int totalNodeCount, RecoveryResultReceiver<T> results, ChangeRequestState forcedState);
}


text:
require "jekyll"
require "tempfile"
require "open3"

require_relative "./lib"

# This plugin enables jekyll to render helm charts.
# Traditionally, Jekyll will render files which make use of the Liquid templating language.
# This plugin adds a new 'tag' that when specified will pass the input to the Helm binary.
# example use:
#
# {% helm %}
# datastore: kubernetes
# networking: calico
# {% endhelm %}
module Jekyll
  class RenderHelmTagBlock < Liquid::Block
    def initialize(tag_name, extra_args, liquid_options)
      super

      @chart = "calico"
      if extra_args.start_with?("tigera-operator")
        @chart = "tigera-operator"
        extra_args.slice! "tigera-operator"
      end

      # helm doesn't natively have an --execute-dir flag but it sure would be useful if it did.
      # here we replace instances of "--execute-dir $dir" with individual calls to "--execute $file" by
      # iterating over files in that directory.
      extra_args.gsub!(/--execute-dir (\S*)/) do |_|
        e = []
        Dir.foreach "_includes/charts/#{@chart}/#{$1}" do |file|
            fpath = File.join($1, file)
            next if File.directory?("_includes/charts/#{@chart}/#{fpath}")

            # for helm v3, when templating crd files, you must specify them relative
            # to the crd directory. so trim the 'crds' from the name.
            # we don't need to worry about the helm v2 case because crds are stored in templates/
            # and can't be --executed from the crds/ directory.
            if fpath.start_with? "crds" then
              fpath = Pathname.new(fpath).relative_path_from(Pathname.new("crds"))
            end

            e << "--execute #{fpath}"
        end
        e.join(" ")
      end

      # substitute --execute with --show-only for helm v3 compatibility.
      if @chart == "tigera-operator" then
        extra_args.gsub!(/--execute (\S*)/) do |f|
          # operator CRDs have moved to root
          if $1.start_with? "templates/crds/" then f.sub('--execute templates/crds/', '--show-only ')
          # all other requests need to use --show-only instead of --execute for helm v3
          else f.sub('--execute', '--show-only')
          end
        end
      end

      @extra_args = extra_args
    end
    def render(context)
      text = super

      # Because helm hasn't merged stdin support, write the passed-in values.yaml
      # to a tempfile on disk.
      t = Tempfile.new("jhelm")
      t.write(text)
      t.close

      imageRegistry = context.registers[:page]["registry"]
      imageNames = context.registers[:site].config["imageNames"]
      versions = context.registers[:site].data["versions"]

      vs = parse_versions(versions)

      versionsYml = gen_values(vs, imageNames, imageRegistry, @chart)

      tv = Tempfile.new("temp_versions.yml")
      tv.write(versionsYml)
      tv.close

      # Execute helm.
      # Set the default etcd endpoint placeholder for rendering in the docs.
      if @chart == "tigera-operator" then
        cmd = """bin/helm3 template --include-crds _includes/charts/#{@chart} \
          -f #{tv.path} \
          -f #{t.path}"""
      else
        cmd = """bin/helm template _includes/charts/#{@chart} \
        -f #{tv.path} \
        -f #{t.path} \
        --set etcd.endpoints='http://<ETCD_IP>:<ETCD_PORT>'"""
      end

      cmd += " " + @extra_args.to_s

      out, stderr, status = Open3.capture3(cmd)
      if status != 0
        raise "failed to execute helm for '#{context.registers[:page]["path"]}': #{stderr}"
      end

      t.unlink
      tv.unlink
      return out
    end
  end
end

Liquid::Template.register_tag('helm', Jekyll::RenderHelmTagBlock)


text:
layout: post
title:  "USC Graduate Program Info Session"
date:   2014-10-13
author: Eric Tendian
categories:
- announcement
- event
img: /assets/img/blog/nopicture.jpg
thumb: nopicture.jpg
---

The **University of Southern California** is a top-ranked U.S. News & World Report graduate engineering program with over 70 PhD and Master's programs in 13 engineering disciplines. We invite you to attend an information session at Illinois Institute of Technology being held on **Tuesday, October 14, 12:40-1:50 PM at the MTCC Auditorium.** Refreshments will be served. There will be presentation covering:

- Overview of USC and the Viterbi School
- MS & PhD Programs
- Summer Undergraduate Research Experience
- Application Process
- Tuition & Fees

The presentation will be followed by a Q&A session. All students earning degrees in engineering, computer science, mathematics and the hard sciences are welcome.

Email me (Ray Fujioka at <fujioka@usc.edu>) to let me know that you plan to attend the session and receive a gift and be entered into a raffle to be held at the end of the presentation.

Sincerely,

Raymond Fujioka

Assistant Direct of Graduate Recruitment

University of Southern California

Viterbi School of Engineering


text:
<?php
//
// WARNING: Do not edit by hand, this file was generated by Crank:
// https://github.com/gocardless/crank
//

namespace GoCardlessPro\Integration;

class BillingRequestTemplatesIntegrationTest extends IntegrationTestBase
{
    public function testResourceModelExists()
    {
        $obj = new \GoCardlessPro\Resources\BillingRequestTemplate(array());
        $this->assertNotNull($obj);
    }

    public function testBillingRequestTemplatesList()
    {
        $fixture = $this->loadJsonFixture('billing_request_templates')->list;
        $this->stub_request($fixture);

        $service = $this->client->billingRequestTemplates();
        $response = call_user_func_array(array($service, 'list'), (array)$fixture->url_params);

        $body = $fixture->body->billing_request_templates;

        $records = $response->records;
        $this->assertInstanceOf('\GoCardlessPro\Core\ListResponse', $response);
        $this->assertInstanceOf('\GoCardlessPro\Resources\BillingRequestTemplate', $records[0]);

        $this->assertEquals($fixture->body->meta->cursors->before, $response->before);
        $this->assertEquals($fixture->body->meta->cursors->after, $response->after);

        foreach (range(0, count($body) - 1) as $num) {
            $record = $records[$num];
            $this->assertEquals($body[$num]->authorisation_url, $record->authorisation_url);
            $this->assertEquals($body[$num]->created_at, $record->created_at);
            $this->assertEquals($body[$num]->id, $record->id);
            $this->assertEquals($body[$num]->mandate_request_currency, $record->mandate_request_currency);
            $this->assertEquals($body[$num]->mandate_request_metadata, $record->mandate_request_metadata);
            $this->assertEquals($body[$num]->mandate_request_scheme, $record->mandate_request_scheme);
            $this->assertEquals($body[$num]->mandate_request_verify, $record->mandate_request_verify);
            $this->assertEquals($body[$num]->metadata, $record->metadata);
            $this->assertEquals($body[$num]->name, $record->name);
            $this->assertEquals($body[$num]->payment_request_amount, $record->payment_request_amount);
            $this->assertEquals($body[$num]->payment_request_currency, $record->payment_request_currency);
            $this->assertEquals($body[$num]->payment_request_description, $record->payment_request_description);
            $this->assertEquals($body[$num]->payment_request_metadata, $record->payment_request_metadata);
            $this->assertEquals($body[$num]->payment_request_scheme, $record->payment_request_scheme);
            $this->assertEquals($body[$num]->redirect_uri, $record->redirect_uri);
            $this->assertEquals($body[$num]->updated_at, $record->updated_at);

        }

        $expectedPathRegex = $this->extract_resource_fixture_path_regex($fixture);
        $dispatchedRequest = $this->history[0]['request'];
        $this->assertRegExp($expectedPathRegex, $dispatchedRequest->getUri()->getPath());
    }

    public function testBillingRequestTemplatesGet()
    {
        $fixture = $this->loadJsonFixture('billing_request_templates')->get;
        $this->stub_request($fixture);

        $service = $this->client->billingRequestTemplates();
        $response = call_user_func_array(array($service, 'get'), (array)$fixture->url_params);

        $body = $fixture->body->billing_request_templates;

        $this->assertInstanceOf('\GoCardlessPro\Resources\BillingRequestTemplate', $response);

        $this->assertEquals($body->authorisation_url, $response->authorisation_url);
        $this->assertEquals($body->created_at, $response->created_at);
        $this->assertEquals($body->id, $response->id);
        $this->assertEquals($body->mandate_request_currency, $response->mandate_request_currency);
        $this->assertEquals($body->mandate_request_metadata, $response->mandate_request_metadata);
        $this->assertEquals($body->mandate_request_scheme, $response->mandate_request_scheme);
        $this->assertEquals($body->mandate_request_verify, $response->mandate_request_verify);
        $this->assertEquals($body->metadata, $response->metadata);
        $this->assertEquals($body->name, $response->name);
        $this->assertEquals($body->payment_request_amount, $response->payment_request_amount);
        $this->assertEquals($body->payment_request_currency, $response->payment_request_currency);
        $this->assertEquals($body->payment_request_description, $response->payment_request_description);
        $this->assertEquals($body->payment_request_metadata, $response->payment_request_metadata);
        $this->assertEquals($body->payment_request_scheme, $response->payment_request_scheme);
        $this->assertEquals($body->redirect_uri, $response->redirect_uri);
        $this->assertEquals($body->updated_at, $response->updated_at);

        $expectedPathRegex = $this->extract_resource_fixture_path_regex($fixture);
        $dispatchedRequest = $this->history[0]['request'];
        $this->assertRegExp($expectedPathRegex, $dispatchedRequest->getUri()->getPath());
    }

    public function testBillingRequestTemplatesCreate()
    {
        $fixture = $this->loadJsonFixture('billing_request_templates')->create;
        $this->stub_request($fixture);

        $service = $this->client->billingRequestTemplates();
        $response = call_user_func_array(array($service, 'create'), (array)$fixture->url_params);

        $body = $fixture->body->billing_request_templates;

        $this->assertInstanceOf('\GoCardlessPro\Resources\BillingRequestTemplate', $response);

        $this->assertEquals($body->authorisation_url, $response->authorisation_url);
        $this->assertEquals($body->created_at, $response->created_at);
        $this->assertEquals($body->id, $response->id);
        $this->assertEquals($body->mandate_request_currency, $response->mandate_request_currency);
        $this->assertEquals($body->mandate_request_metadata, $response->mandate_request_metadata);
        $this->assertEquals($body->mandate_request_scheme, $response->mandate_request_scheme);
        $this->assertEquals($body->mandate_request_verify, $response->mandate_request_verify);
        $this->assertEquals($body->metadata, $response->metadata);
        $this->assertEquals($body->name, $response->name);
        $this->assertEquals($body->payment_request_amount, $response->payment_request_amount);
        $this->assertEquals($body->payment_request_currency, $response->payment_request_currency);
        $this->assertEquals($body->payment_request_description, $response->payment_request_description);
        $this->assertEquals($body->payment_request_metadata, $response->payment_request_metadata);
        $this->assertEquals($body->payment_request_scheme, $response->payment_request_scheme);
        $this->assertEquals($body->redirect_uri, $response->redirect_uri);
        $this->assertEquals($body->updated_at, $response->updated_at);

        $expectedPathRegex = $this->extract_resource_fixture_path_regex($fixture);
        $dispatchedRequest = $this->history[0]['request'];
        $this->assertRegExp($expectedPathRegex, $dispatchedRequest->getUri()->getPath());
    }

    public function testBillingRequestTemplatesCreateWithIdempotencyConflict()
    {
        $fixture = $this->loadJsonFixture('billing_request_templates')->create;

        $idempotencyConflictResponseFixture = $this->loadFixture('idempotent_creation_conflict_invalid_state_error');

        // The POST request responds with a 409 to our original POST, due to an idempotency conflict
        $this->mock->append(new \GuzzleHttp\Psr7\Response(409, [], $idempotencyConflictResponseFixture));

        // The client makes a second request to fetch the resource that was already
        // created using our idempotency key. It responds with the created resource,
        // which looks just like the response for a successful POST request.
        $this->mock->append(new \GuzzleHttp\Psr7\Response(200, [], json_encode($fixture->body)));

        $service = $this->client->billingRequestTemplates();
        $response = call_user_func_array(array($service, 'create'), (array)$fixture->url_params);
        $body = $fixture->body->billing_request_templates;

        $this->assertInstanceOf('\GoCardlessPro\Resources\BillingRequestTemplate', $response);

        $this->assertEquals($body->authorisation_url, $response->authorisation_url);
        $this->assertEquals($body->created_at, $response->created_at);
        $this->assertEquals($body->id, $response->id);
        $this->assertEquals($body->mandate_request_currency, $response->mandate_request_currency);
        $this->assertEquals($body->mandate_request_metadata, $response->mandate_request_metadata);
        $this->assertEquals($body->mandate_request_scheme, $response->mandate_request_scheme);
        $this->assertEquals($body->mandate_request_verify, $response->mandate_request_verify);
        $this->assertEquals($body->metadata, $response->metadata);
        $this->assertEquals($body->name, $response->name);
        $this->assertEquals($body->payment_request_amount, $response->payment_request_amount);
        $this->assertEquals($body->payment_request_currency, $response->payment_request_currency);
        $this->assertEquals($body->payment_request_description, $response->payment_request_description);
        $this->assertEquals($body->payment_request_metadata, $response->payment_request_metadata);
        $this->assertEquals($body->payment_request_scheme, $response->payment_request_scheme);
        $this->assertEquals($body->redirect_uri, $response->redirect_uri);
        $this->assertEquals($body->updated_at, $response->updated_at);

        $expectedPathRegex = $this->extract_resource_fixture_path_regex($fixture);
        $conflictRequest = $this->history[0]['request'];
        $this->assertRegExp($expectedPathRegex, $conflictRequest->getUri()->getPath());
        $getRequest = $this->history[1]['request'];
        $this->assertEquals($getRequest->getUri()->getPath(), '/billing_request_templates/ID123');
    }

    public function testBillingRequestTemplatesUpdate()
    {
        $fixture = $this->loadJsonFixture('billing_request_templates')->update;
        $this->stub_request($fixture);

        $service = $this->client->billingRequestTemplates();
        $response = call_user_func_array(array($service, 'update'), (array)$fixture->url_params);

        $body = $fixture->body->billing_request_templates;

        $this->assertInstanceOf('\GoCardlessPro\Resources\BillingRequestTemplate', $response);

        $this->assertEquals($body->authorisation_url, $response->authorisation_url);
        $this->assertEquals($body->created_at, $response->created_at);
        $this->assertEquals($body->id, $response->id);
        $this->assertEquals($body->mandate_request_currency, $response->mandate_request_currency);
        $this->assertEquals($body->mandate_request_metadata, $response->mandate_request_metadata);
        $this->assertEquals($body->mandate_request_scheme, $response->mandate_request_scheme);
        $this->assertEquals($body->mandate_request_verify, $response->mandate_request_verify);
        $this->assertEquals($body->metadata, $response->metadata);
        $this->assertEquals($body->name, $response->name);
        $this->assertEquals($body->payment_request_amount, $response->payment_request_amount);
        $this->assertEquals($body->payment_request_currency, $response->payment_request_currency);
        $this->assertEquals($body->payment_request_description, $response->payment_request_description);
        $this->assertEquals($body->payment_request_metadata, $response->payment_request_metadata);
        $this->assertEquals($body->payment_request_scheme, $response->payment_request_scheme);
        $this->assertEquals($body->redirect_uri, $response->redirect_uri);
        $this->assertEquals($body->updated_at, $response->updated_at);

        $expectedPathRegex = $this->extract_resource_fixture_path_regex($fixture);
        $dispatchedRequest = $this->history[0]['request'];
        $this->assertRegExp($expectedPathRegex, $dispatchedRequest->getUri()->getPath());
    }

}


text:
import pytest
from flask import json

from willbuyer.util.response_schema import ProductDetailsSchema

def test_product_default(flask_app_client):
    response = flask_app_client.post(
        "/product/AVzymLw4_QGzslKAF0HI",
        headers={"Accept": "application/json"}
    )
    data = json.loads(response.data)
    ProductDetailsSchema(strict=True).load(data)

    assert response.status_code == 200

def test_product_nocontent(flask_app_client):
    response = flask_app_client.post(
        "/product/dontexist",
        headers={"Accept": "application/json"}
    )

    assert response.status_code == 204


text:
var shovel = require('../shovel'),
    util = require('../util'),
    temp = require('temp');

module.exports.run = function run(opts, cb) {
    temp.track();
    var racketCodeDir = temp.mkdirSync('racket'),
        args = ['-l', 'racket/base'];
    shovel.start(opts, cb, {
        solutionOnly: function () {
            if (opts.setup) {
                var setupFile = util.codeWriteSync('racket', opts.setup, racketCodeDir, 'setup.rkt');
                args.push('-t', setupFile);
            }
            args.push('-e', opts.solution);
            return {
                name: 'racket',
                args: args
            };
        },
        fullProject: function () {
            throw 'Test framework is not supported';
        }
    });
};


text:
<title>GrADS Command: set grid</title>

set grid

set grid status <linestyle> <color#>

Specifies the characteristics of the displayed grid lines. Default is to draw
horizontal and vertical grid lines with color number 15 (grey) and linestyle 5 (dotted).

Options for status are:

on
- both latitude and longitude lines are drawn

off
- no grid lines lines are drawn

horizontal
- only latitude grid lines are drawn

vertical
- only longigude grid lines are drawn

Options for linestyle are:

1 - solid

2 - long dash

3 - short dash

4 - long dash, short dash

5 - dotted

6 - dot dash

7 - dot dot dash

color# may be one of the 16 GrADS default colors
or a new color defined with set rgb.

Usage Notes

Changes to the grid display characteristics 'stick' until reset by a new
execution of set grid.

You cannot specify a color# without also specifying
a linestyle.

Grid lines are aligned with the labeled tick marks on the X and Y
axes. GrADS chooses appropriate defaults for spacing of the labeled
tick marks, but these defaults may be overridden by the commands set xaxis, set yaxis, set xlint, set ylint, set xlevs, and set ylevs.  Please consult these
reference pages for more information.

Examples


text:
package structs

import (
	"fmt"
	"reflect"
	"strconv"
)

const (
	tagName = "cfg"
)

// Unmarshal unmarshals properties p into v.
// v must be a pointer to a struct.
func Unmarshal(p map[string]string, v interface{}) error {
	rv := reflect.ValueOf(v)
	if rv.Kind() != reflect.Ptr {
		return fmt.Errorf("value must be pointer to a struct: %+v", reflect.TypeOf(v))
	}
	val := rv.Elem()

	for i := 0; i < val.NumField(); i++ {
		tag := val.Type().Field(i).Tag.Get(tagName)
		if tag == "" {
			continue
		}
		strVal := p[tag]
		if strVal == "" {
			continue
		}
		field := val.Field(i)
		switch field.Kind() {
		case reflect.String:
			field.SetString(strVal)
		case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
			x, err := strconv.ParseInt(strVal, 10, 0)
			if err != nil {
				return err
			}
			field.SetInt(x)
		case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
			x, err := strconv.ParseUint(strVal, 10, 0)
			if err != nil {
				return err
			}
			field.SetUint(x)
		case reflect.Bool:
			x, err := strconv.ParseBool(strVal)
			if err != nil {
				return err
			}
			field.SetBool(x)
		case reflect.Float64, reflect.Float32:
			x, err := strconv.ParseFloat(strVal, 0)
			if err != nil {
				return err
			}
			field.SetFloat(x)
		}

	}
	return nil
}


text:
package nak.nakloidGUI.actions.displays;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;

import nak.nakloidGUI.NakloidGUI;
import nak.nakloidGUI.actions.AbstractAction;
import nak.nakloidGUI.coredata.CoreData;
import nak.nakloidGUI.gui.MainWindow;

public class DisplayNotesWindowAction extends AbstractAction {
	public DisplayNotesWindowAction(MainWindow mainWindow, CoreData coreData) {
		super("CHECKBOX_ACTION", Action.AS_CHECK_BOX, mainWindow, coreData);
		setText("音符一覧を表示(&L)@F4");
		setAccelerator(SWT.F4);
		setChecked(mainWindow.displayingNotesWindow());
	}
	@Override
	public void run() {
		NakloidGUI.preferenceStore.setValue("gui.mainWindow.displayNotesWindow", isChecked());
		mainWindow.displayNotesWindow(isChecked());
	}
}


text:
package org.apache.camel.itest.doc;

import org.apache.camel.CamelContext;
import org.apache.camel.ComponentConfiguration;
import org.apache.camel.EndpointConfiguration;
import org.apache.camel.component.browse.BrowseComponent;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class BrowseComponentConfigurationAndDocumentationTest extends CamelTestSupport {

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Test
    public void testComponentConfiguration() throws Exception {
        BrowseComponent comp = context.getComponent("browse", BrowseComponent.class);
        EndpointConfiguration conf = comp.createConfiguration("browse:seda:foo?synchronous=true");

        assertEquals("true", conf.getParameter("synchronous"));

        ComponentConfiguration compConf = comp.createComponentConfiguration();
        String json = compConf.createParameterJsonSchema();
        assertNotNull(json);

        assertTrue(json.contains("\"name\": { \"kind\": \"path\", \"group\": \"common\", \"required\": \"true\", \"type\": \"string\""));
        assertTrue(json.contains("\"synchronous\": { \"kind\": \"parameter\", \"group\": \"advanced\", \"label\": \"advanced\", \"type\": \"boolean\""));
    }

    @Test
    public void testComponentDocumentation() throws Exception {
        CamelContext context = new DefaultCamelContext();
        String html = context.getComponentDocumentation("browse");
        assertNotNull("Should have found some auto-generated HTML", html);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using MediaLibrary.Caching;

namespace MediaLibraryTests {
    [TestFixture]
    public class TestCache {

        [Test]
        public void TestSizeIsLimited() {
            var cache = new LruCache<string, int>(10);

            for (int i = 0; i < 20; i++) {
                cache[i.ToString()] = i;
            }

            Assert.AreEqual(10, cache.Count);
            for (int i = 10; i < 20; i++) {
                Assert.IsTrue(cache.ContainsKey(i.ToString()));
            }
        }

        [Test]
        public void CacheAccessShouldBumpItToTheFront() {
            var cache = new LruCache<int, int>(3);

            cache[1] = 1;
            cache[2] = 2;
            cache[3] = 3;

            var a = cache[1];
            cache[4] = 4;

            Assert.AreEqual(cache[1], 1);
            Assert.AreEqual(cache[3], 3);
            Assert.AreEqual(cache[4], 4);
            Assert.IsFalse(cache.ContainsKey(2));
        }
    }
}


text:
package com.google.bitcoin.testing;

import com.google.bitcoin.core.*;
import com.google.bitcoin.net.BlockingClientManager;
import com.google.bitcoin.net.NioClientManager;
import com.google.bitcoin.params.UnitTestParams;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.MemoryBlockStore;
import com.google.common.base.Preconditions;

import java.net.InetSocketAddress;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;

/**
 * Utility class that makes it easy to work with mock NetworkConnections in PeerGroups.
 */
public class TestWithPeerGroup extends TestWithNetworkConnections {
    protected static final NetworkParameters params = UnitTestParams.get();
    protected PeerGroup peerGroup;

    protected VersionMessage remoteVersionMessage;
    private final ClientType clientType;

    public TestWithPeerGroup(ClientType clientType) {
        super(clientType);
        if (clientType != ClientType.NIO_CLIENT_MANAGER && clientType != ClientType.BLOCKING_CLIENT_MANAGER)
            throw new RuntimeException();
        this.clientType = clientType;
    }

    @Override
    public void setUp() throws Exception {
        setUp(new MemoryBlockStore(params));
    }

    @Override
    public void setUp(BlockStore blockStore) throws Exception {
        super.setUp(blockStore);

        remoteVersionMessage = new VersionMessage(unitTestParams, 1);
        remoteVersionMessage.localServices = VersionMessage.NODE_NETWORK;
        remoteVersionMessage.clientVersion = NotFoundMessage.MIN_PROTOCOL_VERSION;
        initPeerGroup();
    }

    @Override
    public void tearDown() {
        try {
            super.tearDown();
            Utils.finishMockSleep();
            peerGroup.stopAsync();
            peerGroup.awaitTerminated();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected void initPeerGroup() {
        if (clientType == ClientType.NIO_CLIENT_MANAGER)
            peerGroup = new PeerGroup(unitTestParams, blockChain, new NioClientManager());
        else
            peerGroup = new PeerGroup(unitTestParams, blockChain, new BlockingClientManager());
        peerGroup.setPingIntervalMsec(0);  // Disable the pings as they just get in the way of most tests.
        peerGroup.addWallet(wallet);
    }

    protected InboundMessageQueuer connectPeerWithoutVersionExchange(int id) throws Exception {
        Preconditions.checkArgument(id < PEER_SERVERS);
        InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 2000 + id);
        Peer peer = peerGroup.connectTo(remoteAddress).getConnectionOpenFuture().get();
        InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take();
        writeTarget.peer = peer;
        return writeTarget;
    }

    protected InboundMessageQueuer connectPeer(int id) throws Exception {
        return connectPeer(id, remoteVersionMessage);
    }

    protected InboundMessageQueuer connectPeer(int id, VersionMessage versionMessage) throws Exception {
        checkArgument(versionMessage.hasBlockChain());
        InboundMessageQueuer writeTarget = connectPeerWithoutVersionExchange(id);
        // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter
        writeTarget.sendMessage(versionMessage);
        writeTarget.sendMessage(new VersionAck());
        stepThroughInit(versionMessage, writeTarget);
        return writeTarget;
    }

    // handle peer discovered by PeerGroup
    protected InboundMessageQueuer handleConnectToPeer(int id) throws Exception {
        return handleConnectToPeer(id, remoteVersionMessage);
    }

    // handle peer discovered by PeerGroup
    protected InboundMessageQueuer handleConnectToPeer(int id, VersionMessage versionMessage) throws Exception {
        InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take();
        checkArgument(versionMessage.hasBlockChain());
        // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter
        writeTarget.sendMessage(versionMessage);
        writeTarget.sendMessage(new VersionAck());
        stepThroughInit(versionMessage, writeTarget);
        return writeTarget;
    }

    private void stepThroughInit(VersionMessage versionMessage, InboundMessageQueuer writeTarget) throws InterruptedException {
        checkState(writeTarget.nextMessageBlocking() instanceof VersionMessage);
        checkState(writeTarget.nextMessageBlocking() instanceof VersionAck);
        if (versionMessage.isBloomFilteringSupported()) {
            checkState(writeTarget.nextMessageBlocking() instanceof BloomFilter);
            checkState(writeTarget.nextMessageBlocking() instanceof MemoryPoolMessage);
        }
    }
}


text:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <thread_db.h>
#include "libproc_impl.h"

static const char* alt_root = NULL;
static int alt_root_len = -1;

#define SA_ALTROOT "SA_ALTROOT"

static void init_alt_root() {
   if (alt_root_len == -1) {
      alt_root = getenv(SA_ALTROOT);
      if (alt_root) {
         alt_root_len = strlen(alt_root);
      } else {
         alt_root_len = 0;
      }
   }
}

int pathmap_open(const char* name) {
   int fd;
   char alt_path[PATH_MAX + 1];

   init_alt_root();
   fd = open(name, O_RDONLY);
   if (fd >= 0) {
      return fd;
   }

   if (alt_root_len > 0) {
      strcpy(alt_path, alt_root);
      strcat(alt_path, name);
      fd = open(alt_path, O_RDONLY);
      if (fd >= 0) {
         print_debug("path %s substituted for %s\n", alt_path, name);
         return fd;
      }

      if (strrchr(name, '/')) {
         strcpy(alt_path, alt_root);
         strcat(alt_path, strrchr(name, '/'));
         fd = open(alt_path, O_RDONLY);
         if (fd >= 0) {
            print_debug("path %s substituted for %s\n", alt_path, name);
            return fd;
         }
      }
   }

   return -1;
}

static bool _libsaproc_debug;

void print_debug(const char* format,...) {
   if (_libsaproc_debug) {
     va_list alist;

     va_start(alist, format);
     fputs("libsaproc DEBUG: ", stderr);
     vfprintf(stderr, format, alist);
     va_end(alist);
   }
}

bool is_debug() {
   return _libsaproc_debug;
}

// initialize libproc
bool init_libproc(bool debug) {
   // init debug mode
   _libsaproc_debug = debug;

   // initialize the thread_db library
   if (td_init() != TD_OK) {
     print_debug("libthread_db's td_init failed\n");
     return false;
   }

   return true;
}

static void destroy_lib_info(struct ps_prochandle* ph) {
   lib_info* lib = ph->libs;
   while (lib) {
     lib_info *next = lib->next;
     if (lib->symtab) {
        destroy_symtab(lib->symtab);
     }
     free(lib);
     lib = next;
   }
}

static void destroy_thread_info(struct ps_prochandle* ph) {
   thread_info* thr = ph->threads;
   while (thr) {
     thread_info *next = thr->next;
     free(thr);
     thr = next;
   }
}

// ps_prochandle cleanup

// ps_prochandle cleanup
void Prelease(struct ps_prochandle* ph) {
   // do the "derived class" clean-up first
   ph->ops->release(ph);
   destroy_lib_info(ph);
   destroy_thread_info(ph);
   free(ph);
}

lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base) {
   return add_lib_info_fd(ph, libname, -1, base);
}

lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd, uintptr_t base) {
   lib_info* newlib;

   if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
      print_debug("can't allocate memory for lib_info\n");
      return NULL;
   }

   strncpy(newlib->name, libname, sizeof(newlib->name));
   newlib->base = base;

   if (fd == -1) {
      if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
         print_debug("can't open shared object %s\n", newlib->name);
         free(newlib);
         return NULL;
      }
   } else {
      newlib->fd = fd;
   }

   // check whether we have got an ELF file. /proc/<pid>/map
   // gives out all file mappings and not just shared objects
   if (is_elf_file(newlib->fd) == false) {
      close(newlib->fd);
      free(newlib);
      return NULL;
   }

   newlib->symtab = build_symtab(newlib->fd, libname);
   if (newlib->symtab == NULL) {
      print_debug("symbol table build failed for %s\n", newlib->name);
   }

   // even if symbol table building fails, we add the lib_info.
   // This is because we may need to read from the ELF file for core file
   // address read functionality. lookup_symbol checks for NULL symtab.
   if (ph->libs) {
      ph->lib_tail->next = newlib;
      ph->lib_tail = newlib;
   }  else {
      ph->libs = ph->lib_tail = newlib;
   }
   ph->num_libs++;

   return newlib;
}

// lookup for a specific symbol
uintptr_t lookup_symbol(struct ps_prochandle* ph,  const char* object_name,
                       const char* sym_name) {
   // ignore object_name. search in all libraries
   // FIXME: what should we do with object_name?? The library names are obtained
   // by parsing /proc/<pid>/maps, which may not be the same as object_name.
   // What we need is a utility to map object_name to real file name, something
   // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
   // now, we just ignore object_name and do a global search for the symbol.

   lib_info* lib = ph->libs;
   while (lib) {
      if (lib->symtab) {
         uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
         if (res) return res;
      }
      lib = lib->next;
   }

   print_debug("lookup failed for symbol '%s' in obj '%s'\n",
                          sym_name, object_name);
   return (uintptr_t) NULL;
}

const char* symbol_for_pc(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* poffset) {
   const char* res = NULL;
   lib_info* lib = ph->libs;
   while (lib) {
      if (lib->symtab && addr >= lib->base) {
         res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
         if (res) return res;
      }
      lib = lib->next;
   }
   return NULL;
}

// add a thread to ps_prochandle
thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
   thread_info* newthr;
   if ( (newthr = (thread_info*) calloc(1, sizeof(thread_info))) == NULL) {
      print_debug("can't allocate memory for thread_info\n");
      return NULL;
   }

   // initialize thread info
   newthr->pthread_id = pthread_id;
   newthr->lwp_id = lwp_id;

   // add new thread to the list
   newthr->next = ph->threads;
   ph->threads = newthr;
   ph->num_threads++;
   return newthr;
}

// struct used for client data from thread_db callback
struct thread_db_client_data {
   struct ps_prochandle* ph;
   thread_info_callback callback;
};

// callback function for libthread_db
static int thread_db_callback(const td_thrhandle_t *th_p, void *data) {
  struct thread_db_client_data* ptr = (struct thread_db_client_data*) data;
  td_thrinfo_t ti;
  td_err_e err;

  memset(&ti, 0, sizeof(ti));
  err = td_thr_get_info(th_p, &ti);
  if (err != TD_OK) {
    print_debug("libthread_db : td_thr_get_info failed, can't get thread info\n");
    return err;
  }

  print_debug("thread_db : pthread %d (lwp %d)\n", ti.ti_tid, ti.ti_lid);

  if (ptr->callback(ptr->ph, ti.ti_tid, ti.ti_lid) != true)
    return TD_ERR;

  return TD_OK;
}

// read thread_info using libthread_db
bool read_thread_info(struct ps_prochandle* ph, thread_info_callback cb) {
  struct thread_db_client_data mydata;
  td_thragent_t* thread_agent = NULL;
  if (td_ta_new(ph, &thread_agent) != TD_OK) {
     print_debug("can't create libthread_db agent\n");
     return false;
  }

  mydata.ph = ph;
  mydata.callback = cb;

  // we use libthread_db iterator to iterate thru list of threads.
  if (td_ta_thr_iter(thread_agent, thread_db_callback, &mydata,
                 TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
                 TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS) != TD_OK) {
     td_ta_delete(thread_agent);
     return false;
  }

  // delete thread agent
  td_ta_delete(thread_agent);
  return true;
}

// get number of threads
int get_num_threads(struct ps_prochandle* ph) {
   return ph->num_threads;
}

// get lwp_id of n'th thread
lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
   int count = 0;
   thread_info* thr = ph->threads;
   while (thr) {
      if (count == index) {
         return thr->lwp_id;
      }
      count++;
      thr = thr->next;
   }
   return -1;
}

// get regs for a given lwp
bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct user_regs_struct* regs) {
  return ph->ops->get_lwp_regs(ph, lwp_id, regs);
}

// get number of shared objects
int get_num_libs(struct ps_prochandle* ph) {
   return ph->num_libs;
}

// get name of n'th solib
const char* get_lib_name(struct ps_prochandle* ph, int index) {
   int count = 0;
   lib_info* lib = ph->libs;
   while (lib) {
      if (count == index) {
         return lib->name;
      }
      count++;
      lib = lib->next;
   }
   return NULL;
}

// get base address of a lib
uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
   int count = 0;
   lib_info* lib = ph->libs;
   while (lib) {
      if (count == index) {
         return lib->base;
      }
      count++;
      lib = lib->next;
   }
   return (uintptr_t)NULL;
}

bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
  lib_info *p = ph->libs;
  while (p) {
    if (strcmp(p->name, lib_name) == 0) {
      return true;
    }
    p = p->next;
  }
  return false;
}

//--------------------------------------------------------------------------
// proc service functions

// get process id
pid_t ps_getpid(struct ps_prochandle *ph) {
   return ph->pid;
}

// ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
// of the load object object_name in the target process identified by ph.
// It returns the symbol's value as an address in the target process in
// *sym_addr.

ps_err_e ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
                    const char *sym_name, psaddr_t *sym_addr) {
  *sym_addr = (psaddr_t) lookup_symbol(ph, object_name, sym_name);
  return (*sym_addr ? PS_OK : PS_NOSYM);
}

// read "size" bytes info "buf" from address "addr"
ps_err_e ps_pdread(struct ps_prochandle *ph, psaddr_t  addr,
                   void *buf, size_t size) {
  return ph->ops->p_pread(ph, (uintptr_t) addr, buf, size)? PS_OK: PS_ERR;
}

// write "size" bytes of data to debuggee at address "addr"
ps_err_e ps_pdwrite(struct ps_prochandle *ph, psaddr_t addr,
                    const void *buf, size_t size) {
  return ph->ops->p_pwrite(ph, (uintptr_t)addr, buf, size)? PS_OK: PS_ERR;
}

// ------------------------------------------------------------------------
// Functions below this point are not yet implemented. They are here only
// to make the linker happy.

ps_err_e ps_lsetfpregs(struct ps_prochandle *ph, lwpid_t lid, const prfpregset_t *fpregs) {
  print_debug("ps_lsetfpregs not implemented\n");
  return PS_OK;
}

ps_err_e ps_lsetregs(struct ps_prochandle *ph, lwpid_t lid, const prgregset_t gregset) {
  print_debug("ps_lsetregs not implemented\n");
  return PS_OK;
}

ps_err_e  ps_lgetfpregs(struct  ps_prochandle  *ph,  lwpid_t lid, prfpregset_t *fpregs) {
  print_debug("ps_lgetfpregs not implemented\n");
  return PS_OK;
}

ps_err_e ps_lgetregs(struct ps_prochandle *ph, lwpid_t lid, prgregset_t gregset) {
  print_debug("ps_lgetfpregs not implemented\n");
  return PS_OK;
}

// new libthread_db of NPTL seem to require this symbol
ps_err_e ps_get_thread_area() {
  print_debug("ps_get_thread_area not implemented\n");
  return PS_OK;
}


text:
package org.cloudfoundry.community.servicebroker.s3.config;

import com.amazonaws.ClientConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author David Ehringer
 */
@Component
@ConfigurationProperties
public class AwsClientConfiguration {

    private String awsAccessKey;
    private String awsSecretKey;
    private String proxyHost;
    private String proxyPort;
    private String proxyUsername;
    private String proxyPassword;
    private Boolean preemptiveBasicProxyAuth;

    public ClientConfiguration toClientConfiguration(){
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProxyHost(proxyHost);
        if(proxyPort != null) {
            clientConfiguration.setProxyPort(Integer.parseInt(proxyPort));
        }
        clientConfiguration.setProxyUsername(proxyUsername);
        clientConfiguration.setProxyPassword(proxyPassword);
        if(preemptiveBasicProxyAuth != null) {
            clientConfiguration.setPreemptiveBasicProxyAuth(preemptiveBasicProxyAuth);
        }
        return clientConfiguration;
    }

    public String getAwsAccessKey() {
        return awsAccessKey;
    }

    public void setAwsAccessKey(String awsAccessKey) {
        this.awsAccessKey = awsAccessKey;
    }

    public String getAwsSecretKey() {
        return awsSecretKey;
    }

    public void setAwsSecretKey(String awsSecretKey) {
        this.awsSecretKey = awsSecretKey;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public String getProxyUsername() {
        return proxyUsername;
    }

    public void setProxyUsername(String proxyUsername) {
        this.proxyUsername = proxyUsername;
    }

    public String getProxyPassword() {
        return proxyPassword;
    }

    public void setProxyPassword(String proxyPassword) {
        this.proxyPassword = proxyPassword;
    }

    public Boolean getPreemptiveBasicProxyAuth() {
        return preemptiveBasicProxyAuth;
    }

    public void setPreemptiveBasicProxyAuth(Boolean preemptiveBasicProxyAuth) {
        this.preemptiveBasicProxyAuth = preemptiveBasicProxyAuth;
    }

    public void setProxyPort(String proxyPort) {
        this.proxyPort = proxyPort;
    }
}


text:
using Nest.Queryify.Abstractions.Queries;

namespace Nest.Searchify.Abstractions
{
    public interface ISearchResultQuery<out TSearchParameters>
        where TSearchParameters : class, IParameters
    {
        TSearchParameters Parameters { get; }
    }
}


text:
using System;
using System.Runtime.InteropServices;

namespace Esthar.Core
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Vector3Int32
    {
        public Int32 X;
        public Int32 Y;
        public Int32 Z;
    }
}


text:
package net.poksion.chorong.android.ui.card;

public interface ViewBinder<V, M> {
    void onBind(V view, M model);
}


text:
declare const localStorage: any;
declare const document: any;

export class BrowserStorage {
  supportsLocalStorage: boolean;

  constructor() {
     this.supportsLocalStorage = this.hasLocalStorageSupport();
  }

  private hasLocalStorageSupport(): boolean {
    try {
      localStorage.setItem('_', '_');
      localStorage.removeItem('_');

      return true;
    } catch (e) {
      return false;
    }
  }

  private toExpireInXDay(days: number): string {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    return date.toUTCString();
  }

  set(name: string, value: any, days: number = 1): void {
    if (!!value) {
      value = JSON.stringify(value);
    }

    if (this.supportsLocalStorage) {
      localStorage.setItem(name, value);
    } else {
      const expireDate = this.toExpireInXDay(days);
      document.cookie = `${name}=${value};expires=${expireDate}; path=/`;
    }
  }

  get(name: string): any {
    if (this.supportsLocalStorage) {
      const result = localStorage.getItem(name);
      if (!!result) {
        return JSON.parse(result);
      }
      return null;
    }

    const nameEQ = name + '=';
    let ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') { c = c.substring(1, c.length); };
      if (c.indexOf(nameEQ) === 0) {
        const result = c.substring(nameEQ.length, c.length);
        switch (result) {
          case 'true':
            return true;
          case 'false':
            return false;
          default:
            return JSON.parse(result);
        }
      }
    }
  }

  del(name: string): void {
    if (this.supportsLocalStorage) {
      localStorage.removeItem(name);
    } else {
      this.set(name, '', -1);
    }
  }
}


text:
layout: post
date: 2015-07-29 1:00 PM
categories:
- nginx
- ssl
title: Nginx in Docker with a Self-Signed Root Certificate
description: How to create a docker container for nginx for an SSL endpoint using a self signed root certificate.
---

For a side project at work we needed to get a simple SSL endpoint in front of [Bosun][bosun]. I went about this by sticking Nginx inside of a docker container with a self-signed root certificate. I picked a self-signed root certificate because we didn't want to pay for a trusted certificate for a small project and creating our own trust completely worked out well for the project.

## Generate the root certificate and certificates

This is taken from [ruby documentation][ruby-documentation] as it was the easiest way I found to generate a root certificate.

```ruby
require 'openssl'

root_key = OpenSSL::PKey::RSA.new 2048 # the CA's public/private key
root_ca = OpenSSL::X509::Certificate.new
root_ca.version = 2 # cf. RFC 5280 - to make it a "v3" certificate
root_ca.serial = 1
root_ca.subject = OpenSSL::X509::Name.parse "/DC=org/DC=ruby-lang/CN=Ruby CA"
root_ca.issuer = root_ca.subject # root CA's are "self-signed"
root_ca.public_key = root_key.public_key
root_ca.not_before = Time.now
root_ca.not_after = root_ca.not_before + 2 * 365 * 24 * 60 * 60 # 2 years validity

ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = root_ca
ef.issuer_certificate = root_ca

root_ca.add_extension(ef.create_extension("basicConstraints","CA:TRUE",true))
root_ca.add_extension(ef.create_extension("keyUsage","keyCertSign, cRLSign", true))
root_ca.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false))
root_ca.add_extension(ef.create_extension("authorityKeyIdentifier","keyid:always",false))
root_ca.sign(root_key, OpenSSL::Digest::SHA256.new)

key = OpenSSL::PKey::RSA.new 2048
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 2
cert.subject = OpenSSL::X509::Name.parse "/CN=example.com"
cert.issuer = root_ca.subject # root CA is the issuer
cert.public_key = key.public_key
cert.not_before = Time.now
cert.not_after = cert.not_before + 1 * 365 * 24 * 60 * 60 # 1 years validity
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = root_ca
cert.add_extension(ef.create_extension("keyUsage","digitalSignature", true))
cert.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false))
cert.sign(root_key, OpenSSL::Digest::SHA256.new)

File.open("root.key", "w") do |file|
  file.write(root_key.to_pem)
end
File.open("root.crt", "w") do |file|
  file.write(root_ca.to_pem)
end

File.open("bosun.key", "w") do |file|
  file.write(key.to_pem)
end
File.open("bosun.crt", "w") do |file|
  file.write(cert.to_pem)
end
```

## Setup Nginx in Docker

##### Dockerfile

```docker
FROM nginx
ADD ssl /etc/nginx/ssl
ADD sites /etc/nginx/sites
ADD nginx.conf /etc/nginx/nginx.conf
```

This is my normal nginx setup. Nothing special here.

##### siites/bosun.conf

```nginx
upstream bosun {
  server 192.168.1.1:5000;
}

server {
  listen 443 ssl;

  ssl on;
  ssl_certificate /etc/nginx/ssl/bosun.crt;
  ssl_certificate_key /etc/nginx/ssl/bosun.key;

  location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://bosun;
  }

  client_max_body_size 4G;
  keepalive_timeout 10;
  server_tokens off;

  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
}
```

In this, the only thing that needs to specially pointed out is the `upstream` needs to point at your ip address or wherever the server lives.

## Build and Start Nginx

```bash
docker build -t nginx-ssl .
docker run -t -i -p 4443:443 nginx-ssl
```

## Connecting via Faraday

```ruby
require 'faraday'
require 'json'
require 'openssl'

store = OpenSSL::X509::Store.new
store.add_file("root.pem")

connection = Faraday.new('https://localhost:4443', {
  :ssl => {
    :cert_store => store,
  }
})
```

To setup faraday, you need to create a custom certificate store that contains the `root.pem` file. After the connection is created with the right certificate store, everything just works.

This is also a neat way to get a green SSL bar without having to pay. You can install your new root certificate in your browser and not have trust issues warning you about continuing. This is primarily useful for small side projects that only you will be visiting as anyone without the root certificate trusted will still see warnings.

[bosun]: http://bosun.org/
[ruby-documentation]: http://ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/X509/Certificate.html


text:
@class BasicVTKView;

@interface MyDocument : NSDocument
{
    IBOutlet        BasicVTKView*           leftVTKView;
    IBOutlet        BasicVTKView*           rightVTKView;
}

@end


text:
import sys, os
sys.path.insert(1, os.path.join("..", ".."))
import h2o
from h2o.utils.typechecks import is_type
from h2o.estimators import H2OGradientBoostingEstimator, H2OGeneralizedLinearEstimator
from tests import pyunit_utils

def gbm_model_build():
    """
    Train gbm model
    :returns model, training frame
    """
    prostate_train = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate_train.csv"))
    prostate_train["CAPSULE"] = prostate_train["CAPSULE"].asfactor()

    ntrees = 100
    learning_rate = 0.1
    depth = 5
    min_rows = 10
    # Build H2O GBM classification model:
    gbm_h2o = H2OGradientBoostingEstimator(ntrees=ntrees, learn_rate=learning_rate,
                                           max_depth=depth,
                                           min_rows=min_rows,
                                           distribution="bernoulli")
    gbm_h2o.train(x=list(range(1, prostate_train.ncol)), y="CAPSULE", training_frame=prostate_train)

    # Doing PFI on test data vs train data: In the end, you need to decide whether you want to know how much the
    # model relies on each feature for making predictions (-> training data) or how much the feature contributes to
    # the performance of the model on unseen data (-> test data). To the best of my knowledge, there is no research
    # addressing the question of training vs. test data
    return gbm_h2o, prostate_train

def test_metrics_gbm():
    """
    test metrics values from the Permutation Variable Importance
    """
    # train model
    model, fr = gbm_model_build()  # type: Tuple[h2o.model.ModelBase, H2OFrame]

    # case H2OFrame
    pm_h2o_df = model.permutation_importance(fr, use_pandas=False, metric="AUC")
    for col in ["Relative Importance", "Scaled Importance", "Percentage"]:
        assert isinstance(pm_h2o_df[col][0], float)

    # range in all tests is [1, ncols], first column is str: Importance
    assert is_type(pm_h2o_df[0][0], str)
    # case pandas
    pm_pd_df = model.permutation_importance(fr, use_pandas=True, metric="AUC")
    for col in pm_pd_df.columns:
        assert isinstance(pm_pd_df.iloc[0][col], float)

    metrics = ["AUTO", "MSE", "RMSE", "AUC", "logloss"]
    for metric in metrics:
        pd_pfi = model.permutation_importance(fr, use_pandas=False, metric=metric)
        for col in pd_pfi.col_header[1:]:
            assert isinstance(pd_pfi[col][0], float)

    for metric in metrics:
        pd_pfi = model.permutation_importance(fr, use_pandas=False, n_repeats=5, metric=metric)
        for i, col in enumerate(pd_pfi.col_header[1:]):
            assert col == "Run {}".format(1 + i)
            assert isinstance(pd_pfi[col][0], float)

    try:
        pfi = model.permutation_importance(fr, use_pandas=False, n_samples=0, features=[], seed=42)
        assert False, "This should fail on validation - n_samples=0."
    except h2o.exceptions.H2OValueError:
        pass

    try:
        pfi = model.permutation_importance(fr, use_pandas=False, n_repeats=0, features=[], seed=42)
        assert False, "This should fail on validation - n_repeats = 0."
    except h2o.exceptions.H2OValueError:
        pass

    try:
        pfi = model.permutation_importance(fr[["AGE", "PSA"]], use_pandas=False, seed=42)
        assert False, "This should fail on validation - missing response."
    except h2o.exceptions.H2OValueError:
        pass

    try:
        pfi = model.permutation_importance(fr, use_pandas=False, features=["lorem", "ipsum", "dolor"], seed=42)
        assert False, "This should fail on validation - non-existent features."
    except h2o.exceptions.H2OValueError:
        pass

    try:
        pfi = model.permutation_importance(fr, use_pandas=False, n_samples=1, features=[])
        assert False, "This should throw an exception since we cannot permute one row."
    except h2o.exceptions.H2OValueError:
        pass

    pfi = model.permutation_importance(fr, use_pandas=False, n_samples=10, features=[])
    for col in pfi.col_header[1:]:
        assert isinstance(pfi[col][0], float)

    pfi = model.permutation_importance(fr, use_pandas=False, n_samples=-1, features=["PSA"])
    assert len(pfi.cell_values) == 1  # "[(PSA, ..., ..., ...)]"
    for col in pfi.col_header[1:]:
        assert isinstance(pfi[col][0], float)

    pfi = model.permutation_importance(fr, use_pandas=False, n_samples=-1, features=["PSA", "AGE"])
    assert len(pfi.cell_values) == 2
    for col in pfi.col_header[1:]:
        assert isinstance(pfi[col][0], float)

def test_big_data_cars():
    """
    Test big data dataset, with metric logloss.
    """
    h2o_df = h2o.import_file(path=pyunit_utils.locate("bigdata/laptop/lending-club/loan.csv"))
    predictors = h2o_df.col_names
    response_col = h2o_df.col_names[12]  # loan amount
    predictors.remove(response_col)

    model = H2OGeneralizedLinearEstimator(family="binomial")
    model.train(y=response_col, x=predictors, training_frame=h2o_df)

    metric = "logloss"

    pm_h2o_df = model.permutation_importance(h2o_df, use_pandas=True, n_samples=-1, metric=metric)
    for pred in predictors:
        if pred == "Variable":
            continue
        assert isinstance(pm_h2o_df.loc[pred, "Relative Importance"], float)  # Relative PFI

    pm_h2o_df = model.permutation_importance(h2o_df, use_pandas=True, n_samples=100, metric=metric)
    for pred in predictors:
        if pred == "Variable":
            continue
        assert isinstance(pm_h2o_df.loc[pred, "Relative Importance"], float)  # Relative PFI

def test_permutation_importance_plot_works():
    import matplotlib
    matplotlib.use("agg")
    import matplotlib.pyplot as plt
    # train model
    model, fr = gbm_model_build()  # type: Tuple[h2o.model.ModelBase, H2OFrame]

    # The following should not fail
    # barplot
    model.permutation_importance_plot(fr)
    # boxplot
    model.permutation_importance_plot(fr, n_repeats=5)
    plt.close("all")

pyunit_utils.run_tests([
    test_metrics_gbm,
    test_big_data_cars,
    test_permutation_importance_plot_works
])


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

import com.fasterxml.jackson.annotation.JsonProperty;
import net.asynchronized.yxc.Response;

/**
 *
 * @author enrico
 */
public class Status extends Response {
//    public static final String PATH = ROOT_PATH + "/main/getStatus";
    public static final String METHOD = "/getStatus";

    private String power;
    private Integer sleep;
    private Integer volume;
    private Boolean mute;
    @JsonProperty("max_volume")
    private Integer maxVolume;
    private String input;
    @JsonProperty("distribution_enable")
    private Boolean distributionEnable;
    @JsonProperty("sound_program")
    private String soundProgram;
    private Boolean direct;
    @JsonProperty("pure_direct")
    private Boolean pureDirect;
    private Boolean enhancer;
    @JsonProperty("tone_control")
    private ToneControl toneControl;
    private Equalizer equalizer;
    private Integer balance;
    @JsonProperty("dialogue_level")
    private Integer dialogueLevel;
    @JsonProperty("dialogue_lift")
    private Integer dialogueLift;
    @JsonProperty("clear_voice")
    private Boolean clearVoice;
    @JsonProperty("subwoofer_volume")
    private Integer subwooferVolume;
    @JsonProperty("bass_extensions")
    private Boolean bassExtension;
    @JsonProperty("link_control")
    private String linkControl;
    @JsonProperty("link_audio_delay")
    private String linkAudioDelay;
    @JsonProperty("disable_flags")
    private Integer disableFlags;

    public String getPower() {
        return power;
    }

    public void setPower(String power) {
        this.power = power;
    }

    public Integer getSleep() {
        return sleep;
    }

    public void setSleep(Integer sleep) {
        this.sleep = sleep;
    }

    public Integer getVolume() {
        return volume;
    }

    public void setVolume(Integer volume) {
        this.volume = volume;
    }

    public Boolean getMute() {
        return mute;
    }

    public void setMute(Boolean mute) {
        this.mute = mute;
    }

    public Integer getMaxVolume() {
        return maxVolume;
    }

    public void setMaxVolume(Integer maxVolume) {
        this.maxVolume = maxVolume;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public Boolean getDistributionEnable() {
        return distributionEnable;
    }

    public void setDistributionEnable(Boolean distributionEnable) {
        this.distributionEnable = distributionEnable;
    }

    public String getSoundProgram() {
        return soundProgram;
    }

    public void setSoundProgram(String soundProgram) {
        this.soundProgram = soundProgram;
    }

    public Boolean getDirect() {
        return direct;
    }

    public void setDirect(Boolean direct) {
        this.direct = direct;
    }

    public Boolean getPureDirect() {
        return pureDirect;
    }

    public void setPureDirect(Boolean pureDirect) {
        this.pureDirect = pureDirect;
    }

    public Boolean getEnhancer() {
        return enhancer;
    }

    public void setEnhancer(Boolean enhancer) {
        this.enhancer = enhancer;
    }

    public ToneControl getToneControl() {
        return toneControl;
    }

    public void setToneControl(ToneControl toneControl) {
        this.toneControl = toneControl;
    }

    public Equalizer getEqualizer() {
        return equalizer;
    }

    public void setEqualizer(Equalizer equalizer) {
        this.equalizer = equalizer;
    }

    public Integer getBalance() {
        return balance;
    }

    public void setBalance(Integer balance) {
        this.balance = balance;
    }

    public Integer getDialogueLevel() {
        return dialogueLevel;
    }

    public void setDialogueLevel(Integer dialogueLevel) {
        this.dialogueLevel = dialogueLevel;
    }

    public Integer getDialogueLift() {
        return dialogueLift;
    }

    public void setDialogueLift(Integer dialogueLift) {
        this.dialogueLift = dialogueLift;
    }

    public Boolean getClearVoice() {
        return clearVoice;
    }

    public void setClearVoice(Boolean clearVoice) {
        this.clearVoice = clearVoice;
    }

    public Integer getSubwooferVolume() {
        return subwooferVolume;
    }

    public void setSubwooferVolume(Integer subwooferVolume) {
        this.subwooferVolume = subwooferVolume;
    }

    public Boolean getBassExtension() {
        return bassExtension;
    }

    public void setBassExtension(Boolean bassExtension) {
        this.bassExtension = bassExtension;
    }

    public String getLinkControl() {
        return linkControl;
    }

    public void setLinkControl(String linkControl) {
        this.linkControl = linkControl;
    }

    public String getLinkAudioDelay() {
        return linkAudioDelay;
    }

    public void setLinkAudioDelay(String linkAudioDelay) {
        this.linkAudioDelay = linkAudioDelay;
    }

    public Integer getDisableFlags() {
        return disableFlags;
    }

    public void setDisableFlags(Integer disableFlags) {
        this.disableFlags = disableFlags;
    }

    @Override
    public String toString() {
        return "Status{" + "responseCode=" + getResponseCode() + ", power=" + power + ", sleep=" + sleep + ", volume=" + volume + ", mute=" + mute + ", maxVolume=" + maxVolume + ", input=" + input + ", distributionEnable=" + distributionEnable + ", soundProgram=" + soundProgram + ", direct=" + direct + ", pureDirect=" + pureDirect + ", enhancer=" + enhancer + ", toneControl=" + toneControl + ", equalizer=" + equalizer + ", balance=" + balance + ", dialogueLevel=" + dialogueLevel + ", dialogueLift=" + dialogueLift + ", clearVoice=" + clearVoice + ", subwooferVolume=" + subwooferVolume + ", bassExtension=" + bassExtension + ", linkControl=" + linkControl + ", linkAudioDelay=" + linkAudioDelay + ", disableFlags=" + disableFlags + '}';
    }

}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

.tab.selected {
    padding: 2px 15px 4px 15px;
    z-index: 1;
    border-bottom-left-radius: 3px;
    border-bottom-right-radius: 3px;
    color: #FFF;
    text-shadow: rgba(0, 0, 0, 0.4) 0 1px;
}

.tab.selected u {
    color: #FFF;
    text-shadow: rgba(0, 0, 0, 0.4) 0 1px;
}

.tab u {
    font: -moz-dialog;
}

.tab {
    padding: 2px 15px 4px 15px;
    font: -moz-dialog;
    -moz-appearance: tab;
    cursor: default;
    -moz-user-select: none;
    user-select: none;
    text-transform: capitalize;
    text-align: center;
}

.tab:-moz-focusring {
    /* Tab focus rings need to overlay adjacent tabs. */
    position: relative;
}

/*
* Confirm when to use these styles
.tab:first-of-type {
  padding-inline-start: 2px;
}

.tab:last-of-type {
  padding-inline-end: 2px;
}*/

.tabstrip {
    display: flex;
    justify-content: center;
    margin-bottom: -12px;
}

.tabbox {
    /*padding: 15px;*/
    -moz-appearance: dialog;
    background-color: -moz-Dialog;
    color: -moz-DialogText;
    font: message-box;
}

.tabpanel:not(.single-tab) {
    -moz-appearance: tabpanels;
    padding: 18px 10px 10px;
}

.tab-middle {
    padding: 1px 6px 2px;
}


text:
@value borderColor, secondaryFontColor, primaryFontColor from 'SharedStyles/globalStyles.css';
@value smallBP from 'SharedStyles/globalStyles.css';

/**
 * Discussion styles
 */

.container {
  padding: 20px 10px 0px 10px;
  position: relative;
}

.infoContainer {
  display: flex;
  align-items: center;

  & .avatar {
    width: 42px;
    height: 42px;
    border-radius: 50px;
  }

  & .columnOnSmallBP {
    flex: 1;
    display: flex;
    @media smallBP { flex-direction: column; }
  }

  & .userInfo {
    margin-left: 10px;
    flex: 1;
    display: flex;

    & .name {
      font-weight: 700;
      color: primaryFontColor;
      text-decoration: none;
    }

    & .gitHandler {
      margin-left: 15px;
      text-decoration: none;
      color: secondaryFontColor;
      transition: color 0.3s;
      &:hover { color: primaryFontColor; }

      & .gitIcon { margin-right: 5px; }
    }
  }

  & .dateInfo {
    font-size: 13px;
    color: secondaryFontColor;
    @media smallBP { margin-left: 10px; }
  }
}

.discTitle {
  margin-top: 15px;
  font-size: 24px;
  line-height: 32px;
  font-weight: 400;
}

.discContent {
  margin-top: 10px;
  font-size: 15px;
  line-height: 26px;
}

.discFooter {
  margin-top: 10px;
  display: flex;
  align-items: center;

  @media smallBP {
    flex-direction: column;
    align-items: flex-start;
  }

  & .tags { flex: 1; }

  & .favoriteButton,
  & .deleteButton {
    @media smallBP {
      margin-top: 5px;
      padding-left: 0px;
      padding-right: 0px;
    }
    & i {
      font-size: 20px;
      margin-right: 10px;
    }
  }
}

.deletingDiscussion {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);

  display: flex;
  justify-content: center;
  align-items: center;
}


text:
/* Master Styles */
ul.list-group > li.list-group-item > span.tag.float-xs-left {
    margin-right: 12px;
}

ul.list-group > li.list-group-item > .btn.float-xs-right {
    padding: 2px 12px;
}

div.padded {
    padding-top: 12px;
    padding-bottom: 6px;
}

a.hero-card-link {
    text-decoration: none;
}


text:
<?php

/* FOSUserBundle:Profile:edit_content.html.twig */
class __TwigTemplate_959ffd32ae8bda7c636f8ed8769b5baf8266832bfd913f074765c4e7118005e3 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_4ad76fa4b197fae29923ce1a57eca25f00cdf3f45981bfaaebd3bc988bc466f1 = $this->env->getExtension("native_profiler");
        $__internal_4ad76fa4b197fae29923ce1a57eca25f00cdf3f45981bfaaebd3bc988bc466f1->enter($__internal_4ad76fa4b197fae29923ce1a57eca25f00cdf3f45981bfaaebd3bc988bc466f1_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "FOSUserBundle:Profile:edit_content.html.twig"));

        // line 2
        echo "
<form action=\"";
        // line 3
        echo $this->env->getExtension('routing')->getPath("fos_user_profile_edit");
        echo "\" ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
        echo " method=\"POST\" class=\"fos_user_profile_edit\">
    ";
        // line 4
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget');
        echo "
    <div>
        <input type=\"submit\" value=\"";
        // line 6
        echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("profile.edit.submit", array(), "FOSUserBundle"), "html", null, true);
        echo "\" />
    </div>
</form>
";

        $__internal_4ad76fa4b197fae29923ce1a57eca25f00cdf3f45981bfaaebd3bc988bc466f1->leave($__internal_4ad76fa4b197fae29923ce1a57eca25f00cdf3f45981bfaaebd3bc988bc466f1_prof);

    }

    public function getTemplateName()
    {
        return "FOSUserBundle:Profile:edit_content.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  36 => 6,  31 => 4,  25 => 3,  22 => 2,);
    }
}
/* {% trans_default_domain 'FOSUserBundle' %}*/
/* */
/* <form action="{{ path('fos_user_profile_edit') }}" {{ form_enctype(form) }} method="POST" class="fos_user_profile_edit">*/
/*     {{ form_widget(form) }}*/
/*     <div>*/
/*         <input type="submit" value="{{ 'profile.edit.submit'|trans }}" />*/
/*     </div>*/
/* </form>*/
/* */


text:
import java.math.BigDecimal;

import com.github.sarxos.xchange.ExchangeCache;
import com.github.sarxos.xchange.ExchangeException;
import com.github.sarxos.xchange.ExchangeRate;

public class ConvertCadToUsd {

	public static void main(String[] args) throws ExchangeException, InterruptedException {

		// change apikey to your own value
		ExchangeCache.setParameter("openexchangerates.org.apikey", "apikey");

		// define base currency
		ExchangeCache cache = new ExchangeCache("USD");

		// get the CAD to USD exchange rate
		ExchangeRate rate = cache.getRate("CAD");

		// convert
		BigDecimal amount = new BigDecimal("1000");
		BigDecimal converted = rate.convert(amount);

		System.out.println("The " + amount + " CAD = " + converted + " in USD");
	}
}


text:
from __future__ import absolute_import, unicode_literals

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def routablepageurl(context, page, url_name, *args, **kwargs):
    """
    ``routablepageurl`` is similar to ``pageurl``, but works with
    ``RoutablePage``\s. It behaves like a hybrid between the built-in
    ``reverse``, and ``pageurl`` from Wagtail.

    ``page`` is the RoutablePage that URLs will be generated from.

    ``url_name`` is a URL name defined in ``page.subpage_urls``.

    Positional arguments and keyword arguments should be passed as normal
    positional arguments and keyword arguments.
    """
    request = context['request']
    base_url = page.relative_url(request.site)
    routed_url = page.reverse_subpage(url_name, args=args, kwargs=kwargs)
    return base_url + routed_url


text:
<?php

namespace Workshop\Bundle\AclBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/hello/Fabien');

        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
    }
}


text:
void event_thread()
{
	while (events_running) {
		// process messages
		{
			// using mutex here costs us 100fps (500 -> 400)
			std::unique_lock<std::mutex> lock(tasks_mutex);
			while (!tasks.empty()) {
				auto task(std::move(tasks.front()));
				tasks.pop_front();

				// unlock during the task
				lock.unlock();
				task();
				lock.lock();
			}
		}

		// sleeping here drops fps from 500 to 45
		// std::this_thread::sleep_for(std::chrono::microseconds(1));
	}
}

Dart_NativeFunction ResolveName(Dart_Handle name, int argc, bool * auto_setup_scope)
{
	// If we fail, we return NULL, and Dart throws an exception.
	if (!Dart_IsString(name)) return NULL;
	Dart_NativeFunction result = NULL;
	const char* cname;
	HandleError(Dart_StringToCString(name, &cname));

	result = GetMethod(cname);

	return result;
}

DART_EXPORT Dart_Handle sdl_extension_Init(Dart_Handle parent_library) {
	if (Dart_IsError(parent_library)) return parent_library;

	Dart_Handle result_code =
		Dart_SetNativeResolver(parent_library, ResolveName, NULL);
	if (Dart_IsError(result_code)) return result_code;

	events_running = true;
	ethread = std::thread(event_thread);
	ethread.detach();

	return Dart_Null();
}


text:
namespace content {
class BrowserContext;
}  // namespace content

namespace arc {
class ArcBridgeService;

// Collects information from other ArcServices and send UMA metrics.
class ArcMemoryBridge : public KeyedService {
 public:
  // Returns singleton instance for the given BrowserContext,
  // or nullptr if the browser |context| is not allowed to use ARC.
  static ArcMemoryBridge* GetForBrowserContext(
      content::BrowserContext* context);
  static ArcMemoryBridge* GetForBrowserContextForTesting(
      content::BrowserContext* context);

  ArcMemoryBridge(content::BrowserContext* context,
                  ArcBridgeService* bridge_service);
  ArcMemoryBridge(const ArcMemoryBridge&) = delete;
  ArcMemoryBridge& operator=(const ArcMemoryBridge&) = delete;
  ~ArcMemoryBridge() override;

  // Drops the guest kernel's page caches.
  using DropCachesCallback = base::OnceCallback<void(bool)>;
  void DropCaches(DropCachesCallback callback);

 private:
  THREAD_CHECKER(thread_checker_);

  ArcBridgeService* const arc_bridge_service_;  // Owned by ArcServiceManager.
};

}  // namespace arc

#endif  // ASH_COMPONENTS_ARC_MEMORY_ARC_MEMORY_BRIDGE_H_


text:
import json

import requests

s = requests.Session()

class NanagogoError(Exception):
    def __init__(self, status_code, http_status_code, error_message):
        self.status_code = status_code
        self.http_status_code = http_status_code
        self.error_message = error_message

class NanagogoResponse(object):
    """The response from the 7gogo private JSON API, returned as
    either a dict or a list."""
    pass

class NanagogoResponseDict(dict, NanagogoResponse):
    pass

class NanagogoResponseList(list, NanagogoResponse):
    pass

class NanagogoRequest(object):
    url_template = 'https://api.7gogo.jp/web/v2/{}'

    response = None

    error_translations = {'リンクに問題があるか、ページが削除された可能性があります。': 'Not found'}

    def __init__(self, path, method="GET", params={}, data=None):
        if isinstance(path, str) and path.startswith('https'):
            self.url = path
        elif isinstance(path, (list, tuple)):
            self.url = self.url_template.format('/'.join(path))
        else:
            self.url = self.url_template.format(path)

        self.method = method.lower()

        self.params = params
        self.data = data

        self.start()

    def start(self):
        try:
            requests_method = getattr(s, self.method)
        except AttributeError:
            raise

        self.response = requests_method(self.url,
                                        params=self.params,
                                        data=self.data)

        try:
            self.response.raise_for_status()
        except requests.exceptions.HTTPError:
            error = self._get_error(self.response)
            raise NanagogoError(*error)

    def _get_error(self, response):
        http_status_code = response.status_code
        try:
            data = json.loads(response.text)

            if isinstance(data['error'], dict):
                status = data['error']['code']
                error_message = data['error']['message']
                if error_message in self.error_translations:
                    error_eng = self.error_translations[error_message]
                    error_message = '{} ({})'.format(error_eng,
                                                     error_message)
            else:
                status = data['status']
                error_message = data['error']

            return (status, http_status_code, error_message)

        except ValueError:
            raise

    def wrap(self):
        data = json.loads(self.response.text)['data']

        if isinstance(data, list):
            res = NanagogoResponseList(data)
        elif isinstance(data, dict):
            res = NanagogoResponseDict(data)

        res.response = self.response
        res.headers = res.response.headers

        return res

if __name__ == "__main__":
    pass


text:
.badge {
  border: 1px solid transparent;
  border-radius: 4rem;
  display: inline-block;
  font-size: 1.2rem;
  letter-spacing: 0.1rem;
  line-height: 1;
  padding: 0.6rem 1.6rem;
  text-align: center;
  background-color: var(--color-badge-background);
  border-color: var(--color-badge-border);
  color: var(--color-foreground);
  word-break: break-word;
}


text:
class Profile;

namespace chromeos {
namespace kerberos_ticket_expiry_notification {

using ClickCallback =
    base::RepeatingCallback<void(const std::string& principal_name)>;

// Shows the ticket expiry notification for the given |principal_name|.
// |click_callback| is called when the user clicks on the notification.
void Show(Profile* profile,
          const std::string& principal_name,
          ClickCallback click_callback);

// Closes the ticket expiry notification.
void Close(Profile* profile);

}  // namespace kerberos_ticket_expiry_notification
}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_KERBEROS_KERBEROS_TICKET_EXPIRY_NOTIFICATION_H_


text:
<?xml version="1.0"?>
<ruleset name="Modfied PSR2">

 <description>PSR2 excluding line length</description>

 <rule ref="PSR2"/>

 <!-- The following rules should be kept excluded -->
  <rule ref="Generic.Files.LineLength.TooLong">
  <severity>0</severity>
 </rule>
</ruleset>


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

import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.util.List;

/**
 *
 * @author Suzn
 * @param <T>
 */
public interface DAO<T> {

    int save(T t) throws IOException, JsonIOException, JsonSyntaxException;

    int append(T t) throws IOException, JsonIOException, JsonSyntaxException;

    int update(T t) throws IOException, JsonIOException, JsonSyntaxException;

    int remove(T t) throws IOException, JsonIOException, JsonSyntaxException;

    T findById(int id) throws IOException, JsonIOException, JsonSyntaxException;

    List<T> findAll() throws IOException, JsonIOException, JsonSyntaxException;
}


text:
module Geckoboard
  VERSION = Version = "0.0.2"
end


text:
(function(mapContainer) {
  var container = document.getElementById(mapContainer);
  var particleSize = 2;
  var colorsAvailable = {
    white:    'rgba(245, 245, 245, 0.6)',
    red:      'rgba(245,   0,   0, 0.6)',
    green:    'rgba(  0, 245,   0, 0.6)',
    yellow:   'rgba(245, 245,   0, 0.6)',
    cyan:     'rgba(  0, 245, 245, 0.6)',
    magenta:  'rgba(245,   0, 245, 0.6)',
    orange:   'rgba(245, 122,   0, 0.6)'
  };

  var eventTypes = {
    'event': {
      color: 'white',
      ttl: 1
    }
  };

  var map = new Datamap({
    element: container,
    fills: {
      defaultFill: 'rgba(40,60,80,0.9)'
    },
    geographyConfig: {
      highlightOnHover: true,
      popupOnHover: true,
      hideAntarctica: false,
      borderWidth: 0.5,
      borderColor: 'rgba(17,17,17,1)',
      highlightFillColor: 'rgba(40,60,80,0.7)',
      highlightBorderColor: 'rgba(17,17,17,1)',
      highlightBorderWidth: 0.5,
      popupTemplate: function(geography, data) {
        return '
' + geography.properties.name + '
';
      }
    },
    done: function(datamap) {
    }
  });

  map.addPlugin('particle', function(layer, data, options) {
    var self = this;
    var className = 'datamaps-particle';

    var gradients = layer.selectAll('defs')
                          .data(['defs'])
                          .enter()
                            .append('defs')
                            .selectAll('radialGradient')
                              .data(d3.entries(colorsAvailable))
                              .enter()
                                .append('radialGradient')
                                .attr('id', function(d, i) { return 'gradient-'+d.key; })

    gradients.append('stop')
              .attr('offset', '0%')
              .attr('stop-color', function(d, i) { return d.value; })
              .attr('stop-opacity', 0.90)

    gradients.append('stop')
              .attr('offset', '10%')
              .attr('stop-color', function(d, i) { return d.value; })
              .attr('stop-opacity', 0.80)

    gradients.append('stop')
              .attr('offset', '40%')
              .attr('stop-color', function(d, i) { return d.value; })
              .attr('stop-opacity', 0.50)

    gradients.append('stop')
              .attr('offset', '65%')
              .attr('stop-color', function(d, i) { return d.value; })
              .attr('stop-opacity', 0.15)

    gradients.append('stop')
              .attr('offset', '80%')
              .attr('stop-color', function(d, i) { return d.value; })
              .attr('stop-opacity', 0.0)

    layer
      .selectAll(className)
      .data(data, JSON.stringify)
      .enter()
        .append('circle')
        .attr('class', className)
        .attr('cx', function(datum){
            var latLng = self.latLngToXY(datum.latitude, datum.longitude);
            if (latLng) return latLng[0];
        })
        .attr('cy', function(datum){
            var latLng = self.latLngToXY(datum.latitude, datum.longitude);
            if (latLng) return latLng[1];
        })
        .attr('r', 0)
        .attr('fill', function(datum) { return 'url(#gradient-'+datum.color+')'; })
        .transition(1000) // 1 second to 'fade-in'
          .delay(function(d, i) { return i / data.length * 1000; })
          .attr('r', function(datum) { return datum.size; })
        .transition(1000) // 1 second to 'fade-out'
          .delay(function(d, i) { return 600000 * d.ttl; }) // 10 minutes * ttl lifetime
          .attr('r', 0)
          .remove(); // delete particle (auto purge)
  });

  var createEventParticle = function(e) {
    var eventParticle = {
      id: e.type + '_' + e.id,
      size: particleSize,
      ttl: eventTypes[e.type].ttl,
      color: eventTypes[e.type].color,
      latitude: e.latitude,
      longitude: e.longitude
    };

    // TODO switch on e.type to customize properties

    return eventParticle;
  };

  var onEventMessage = function(e) {
    var data = JSON.parse(e.data);
    var events = [];

    for (var i = 0; i < data.length; i++) {
      events.push(createEventParticle(data[i]));
    }

    if (events.length > 0) {
      map.particle(events);
    }
  };

  var onPingMessage = function(e) {
    // ping
  };

  var onConnectionError = function(show) {
    if (show) {
      console.log("connection lost!");
    }
    else {
      console.log("connected!");
    }
  };

  var WE = (function(){
    var eventSource;

    if (!!window.EventSource) {
      eventSource = new EventSource('/stream');
      eventSource.onopen  = function() { onConnectionError(false); };
      eventSource.onclose = function() { onConnectionError(true); };
      eventSource.onerror = function() { onConnectionError(true); };
      eventSource.addEventListener('ping', onPingMessage);
      eventSource.addEventListener('events', onEventMessage);
    }
    else {
      console.log('Streaming not supported!');
    }

    return eventSource;
  })();

})('container');