text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using BlueConcord.IdentityServer.EntityFrameworkCore.Common.DbContexts;

namespace BlueConcord.IdentityServer.Host.Migrations.ClientConfig
{
    [DbContext(typeof(ClientConfigContext))]
    partial class ClientConfigContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.0.0-rtm-21431")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("AbsoluteRefreshTokenLifetime");

                    b.Property<int>("AccessTokenLifetime");

                    b.Property<int>("AccessTokenType");

                    b.Property<bool>("AllowAccessToAllScopes");

                    b.Property<bool>("AllowAccessTokensViaBrowser");

                    b.Property<bool>("AllowPromptNone");

                    b.Property<bool>("AllowRememberConsent");

                    b.Property<bool>("AlwaysSendClientClaims");

                    b.Property<int>("AuthorizationCodeLifetime");

                    b.Property<string>("ClientId")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 100);

                    b.Property<string>("ClientName")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 255);

                    b.Property<string>("ClientUri")
                        .HasAnnotation("MaxLength", 400);

                    b.Property<bool>("EnableLocalLogin");

                    b.Property<bool>("Enabled");

                    b.Property<int>("IdentityTokenLifetime");

                    b.Property<bool>("IncludeJwtId");

                    b.Property<string>("LogoUri");

                    b.Property<bool>("LogoutSessionRequired");

                    b.Property<string>("LogoutUri");

                    b.Property<bool>("PrefixClientClaims");

                    b.Property<int>("RefreshTokenExpiration");

                    b.Property<int>("RefreshTokenUsage");

                    b.Property<bool>("RequireConsent");

                    b.Property<int>("SlidingRefreshTokenLifetime");

                    b.Property<bool>("UpdateAccessTokenOnRefresh");

                    b.HasKey("Id");

                    b.HasIndex("ClientId")
                        .IsUnique();

                    b.ToTable("Clients");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientClaim<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("Type")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 255);

                    b.Property<string>("Value")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 255);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientClaims");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientCorsOrigin<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("Origin")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 255);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientCorsOrigins");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientGrantType<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("GrantType")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 100);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientGrantTypes");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientPostLogoutRedirectUri<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("Uri")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 400);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientPostLogoutRedirectUris");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientProviderRestriction<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("Provider")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 100);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientProviderRestrictions");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientRedirectUri<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("Uri")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 400);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientRedirectUris");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientScope<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("Scope")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 300);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientScopes");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientSecret<System.Guid>", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid?>("ClientId")
                        .IsRequired();

                    b.Property<string>("Description")
                        .HasAnnotation("MaxLength", 1020);

                    b.Property<DateTime?>("Expiration");

                    b.Property<string>("Type")
                        .HasAnnotation("MaxLength", 255);

                    b.Property<string>("Value")
                        .IsRequired()
                        .HasAnnotation("MaxLength", 100);

                    b.HasKey("Id");

                    b.HasIndex("ClientId");

                    b.ToTable("ClientSecrets");
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientClaim<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("Claims")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientCorsOrigin<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("AllowedCorsOrigins")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientGrantType<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("AllowedGrantTypes")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientPostLogoutRedirectUri<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("PostLogoutRedirectUris")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientProviderRestriction<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("IdentityProviderRestrictions")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientRedirectUri<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("RedirectUris")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientScope<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("AllowedScopes")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.ClientSecret<System.Guid>", b =>
                {
                    b.HasOne("BlueConcord.IdentityServer.EntityFrameworkCore.Entities.Client<System.Guid>", "Client")
                        .WithMany("ClientSecrets")
                        .HasForeignKey("ClientId")
                        .OnDelete(DeleteBehavior.Cascade);
                });
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  IQKeyboardManagerConstantsInternal.h
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#ifndef IQKeyboardManagerConstantsInternal_h
#define IQKeyboardManagerConstantsInternal_h

///-----------------------------------
/// @name IQLayoutGuidePosition
///-----------------------------------

/**
 `IQLayoutGuidePositionNone`
 If there are no IQLayoutGuideConstraint associated with viewController

 `IQLayoutGuidePositionTop`
 If provided IQLayoutGuideConstraint is associated with with viewController topLayoutGuide

 `IQLayoutGuidePositionBottom`
 If provided IQLayoutGuideConstraint is associated with with viewController bottomLayoutGuide
 */
typedef NS_ENUM(NSInteger, IQLayoutGuidePosition) {
    IQLayoutGuidePositionNone,
    IQLayoutGuidePositionTop,
    IQLayoutGuidePositionBottom,
};

#endif


text:
/**
 * @fileoverview Runs `prettier` as an ESLint rule.
 * @author Andres Suarez
 */

'use strict';

// ------------------------------------------------------------------------------
//  Requirements
// ------------------------------------------------------------------------------

const diff = require('fast-diff');
const docblock = require('jest-docblock');

// ------------------------------------------------------------------------------
//  Constants
// ------------------------------------------------------------------------------

// Preferred Facebook style.
const FB_PRETTIER_OPTIONS = {
  singleQuote: true,
  trailingComma: 'all',
  bracketSpacing: false,
  jsxBracketSameLine: true,
  parser: 'flow'
};

const LINE_ENDING_RE = /\r\n|[\r\n\u2028\u2029]/;

const OPERATION_INSERT = 'insert';
const OPERATION_DELETE = 'delete';
const OPERATION_REPLACE = 'replace';

// ------------------------------------------------------------------------------
//  Privates
// ------------------------------------------------------------------------------

// Lazily-loaded Prettier.
let prettier;

// ------------------------------------------------------------------------------
//  Helpers
// ------------------------------------------------------------------------------

/**
 * Gets the location of a given index in the source code for a given context.
 * @param {RuleContext} context - The ESLint rule context.
 * @param {number} index - An index in the source code.
 * @returns {Object} An object containing numeric `line` and `column` keys.
 */
function getLocFromIndex(context, index) {
  // If `sourceCode.getLocFromIndex` is available from ESLint, use it - added
  // in ESLint 3.16.0.
  const sourceCode = context.getSourceCode();
  if (typeof sourceCode.getLocFromIndex === 'function') {
    return sourceCode.getLocFromIndex(index);
  }
  const text = sourceCode.getText();
  if (typeof index !== 'number') {
    throw new TypeError('Expected `index` to be a number.');
  }
  if (index < 0 || index > text.length) {
    throw new RangeError('Index out of range.');
  }
  // Loosely based on
  // https://github.com/eslint/eslint/blob/18a519fa/lib/ast-utils.js#L408-L438
  const lineEndingPattern = /\r\n|[\r\n\u2028\u2029]/g;
  let offset = 0;
  let line = 0;
  let match;
  while ((match = lineEndingPattern.exec(text))) {
    const next = match.index + match[0].length;
    if (index < next) {
      break;
    }
    line++;
    offset = next;
  }
  return {
    line: line + 1,
    column: index - offset
  };
}

/**
 * Converts invisible characters to a commonly recognizable visible form.
 * @param {string} str - The string with invisibles to convert.
 * @returns {string} The converted string.
 */
function showInvisibles(str) {
  let ret = '';
  for (let i = 0; i < str.length; i++) {
    switch (str[i]) {
      case ' ':
        ret += '·'; // Middle Dot, \u00B7
        break;
      case '\n':
        ret += '⏎'; // Return Symbol, \u23ce
        break;
      case '\t':
        ret += '↹'; // Left Arrow To Bar Over Right Arrow To Bar, \u21b9
        break;
      default:
        ret += str[i];
        break;
    }
  }
  return ret;
}

/**
 * Generate results for differences between source code and formatted version.
 * @param {string} source - The original source.
 * @param {string} prettierSource - The Prettier formatted source.
 * @returns {Array} - An array contains { operation, offset, insertText, deleteText }
 */
function generateDifferences(source, prettierSource) {
  // fast-diff returns the differences between two texts as a series of
  // INSERT, DELETE or EQUAL operations. The results occur only in these
  // sequences:
  //           /-> INSERT -> EQUAL
  //    EQUAL |           /-> EQUAL
  //           \-> DELETE |
  //                      \-> INSERT -> EQUAL
  // Instead of reporting issues at each INSERT or DELETE, certain sequences
  // are batched together and are reported as a friendlier "replace" operation:
  // - A DELETE immediately followed by an INSERT.
  // - Any number of INSERTs and DELETEs where the joining EQUAL of one's end
  // and another's beginning does not have line endings (i.e. issues that occur
  // on contiguous lines).

  const results = diff(source, prettierSource);
  const differences = [];

  const batch = [];
  let offset = 0; // NOTE: INSERT never advances the offset.
  while (results.length) {
    const result = results.shift();
    const op = result[0];
    const text = result[1];
    switch (op) {
      case diff.INSERT:
      case diff.DELETE:
        batch.push(result);
        break;
      case diff.EQUAL:
        if (results.length) {
          if (batch.length) {
            if (LINE_ENDING_RE.test(text)) {
              flush();
              offset += text.length;
            } else {
              batch.push(result);
            }
          } else {
            offset += text.length;
          }
        }
        break;
      default:
        throw new Error(`Unexpected fast-diff operation "${op}"`);
    }
    if (batch.length && !results.length) {
      flush();
    }
  }

  return differences;

  function flush() {
    let aheadDeleteText = '';
    let aheadInsertText = '';
    while (batch.length) {
      const next = batch.shift();
      const op = next[0];
      const text = next[1];
      switch (op) {
        case diff.INSERT:
          aheadInsertText += text;
          break;
        case diff.DELETE:
          aheadDeleteText += text;
          break;
        case diff.EQUAL:
          aheadDeleteText += text;
          aheadInsertText += text;
          break;
      }
    }
    if (aheadDeleteText && aheadInsertText) {
      differences.push({
        offset,
        operation: OPERATION_REPLACE,
        insertText: aheadInsertText,
        deleteText: aheadDeleteText
      });
    } else if (!aheadDeleteText && aheadInsertText) {
      differences.push({
        offset,
        operation: OPERATION_INSERT,
        insertText: aheadInsertText
      });
    } else if (aheadDeleteText && !aheadInsertText) {
      differences.push({
        offset,
        operation: OPERATION_DELETE,
        deleteText: aheadDeleteText
      });
    }
    offset += aheadDeleteText.length;
  }
}

// ------------------------------------------------------------------------------
//  Rule Definition
// ------------------------------------------------------------------------------

/**
 * Reports an "Insert ..." issue where text must be inserted.
 * @param {RuleContext} context - The ESLint rule context.
 * @param {number} offset - The source offset where to insert text.
 * @param {string} text - The text to be inserted.
 * @returns {void}
 */
function reportInsert(context, offset, text) {
  const pos = getLocFromIndex(context, offset);
  const range = [offset, offset];
  context.report({
    message: 'Insert `{{ code }}`',
    data: { code: showInvisibles(text) },
    loc: { start: pos, end: pos },
    fix(fixer) {
      return fixer.insertTextAfterRange(range, text);
    }
  });
}

/**
 * Reports a "Delete ..." issue where text must be deleted.
 * @param {RuleContext} context - The ESLint rule context.
 * @param {number} offset - The source offset where to delete text.
 * @param {string} text - The text to be deleted.
 * @returns {void}
 */
function reportDelete(context, offset, text) {
  const start = getLocFromIndex(context, offset);
  const end = getLocFromIndex(context, offset + text.length);
  const range = [offset, offset + text.length];
  context.report({
    message: 'Delete `{{ code }}`',
    data: { code: showInvisibles(text) },
    loc: { start, end },
    fix(fixer) {
      return fixer.removeRange(range);
    }
  });
}

/**
 * Reports a "Replace ... with ..." issue where text must be replaced.
 * @param {RuleContext} context - The ESLint rule context.
 * @param {number} offset - The source offset where to replace deleted text
 with inserted text.
 * @param {string} deleteText - The text to be deleted.
 * @param {string} insertText - The text to be inserted.
 * @returns {void}
 */
function reportReplace(context, offset, deleteText, insertText) {
  const start = getLocFromIndex(context, offset);
  const end = getLocFromIndex(context, offset + deleteText.length);
  const range = [offset, offset + deleteText.length];
  context.report({
    message: 'Replace `{{ deleteCode }}` with `{{ insertCode }}`',
    data: {
      deleteCode: showInvisibles(deleteText),
      insertCode: showInvisibles(insertText)
    },
    loc: { start, end },
    fix(fixer) {
      return fixer.replaceTextRange(range, insertText);
    }
  });
}

// ------------------------------------------------------------------------------
//  Module Definition
// ------------------------------------------------------------------------------

module.exports = {
  showInvisibles,
  generateDifferences,
  rules: {
    prettier: {
      meta: {
        fixable: 'code',
        schema: [
          // Prettier options:
          {
            anyOf: [
              { enum: [null, 'fb'] },
              { type: 'object', properties: {}, additionalProperties: true }
            ]
          },
          // Pragma:
          { type: 'string', pattern: '^@\\w+$' }
        ]
      },
      create(context) {
        const pragma = context.options[1]
          ? context.options[1].slice(1) // Remove leading @
          : null;

        const sourceCode = context.getSourceCode();
        const source = sourceCode.text;

        // The pragma is only valid if it is found in a block comment at the very
        // start of the file.
        if (pragma) {
          // ESLint 3.x reports the shebang as a "Line" node, while ESLint 4.x
          // reports it as a "Shebang" node. This works for both versions:
          const hasShebang = source.startsWith('#!');
          const allComments = sourceCode.getAllComments();
          const firstComment = hasShebang ? allComments[1] : allComments[0];
          if (
            !(
              firstComment &&
              firstComment.type === 'Block' &&
              firstComment.loc.start.line === (hasShebang ? 2 : 1) &&
              firstComment.loc.start.column === 0
            )
          ) {
            return {};
          }
          const parsed = docblock.parse(firstComment.value);
          if (parsed[pragma] !== '') {
            return {};
          }
        }

        if (prettier && prettier.clearConfigCache) {
          prettier.clearConfigCache();
        }

        return {
          Program() {
            if (!prettier) {
              // Prettier is expensive to load, so only load it if needed.
              prettier = require('prettier');
            }

            const eslintPrettierOptions =
              context.options[0] === 'fb'
                ? FB_PRETTIER_OPTIONS
                : context.options[0];
            const prettierRcOptions =
              prettier.resolveConfig && prettier.resolveConfig.sync
                ? prettier.resolveConfig.sync(context.getFilename())
                : null;
            const prettierOptions = Object.assign(
              {},
              prettierRcOptions,
              eslintPrettierOptions
            );

            const prettierSource = prettier.format(source, prettierOptions);
            if (source !== prettierSource) {
              const differences = generateDifferences(source, prettierSource);

              differences.forEach(difference => {
                switch (difference.operation) {
                  case OPERATION_INSERT:
                    reportInsert(
                      context,
                      difference.offset,
                      difference.insertText
                    );
                    break;
                  case OPERATION_DELETE:
                    reportDelete(
                      context,
                      difference.offset,
                      difference.deleteText
                    );
                    break;
                  case OPERATION_REPLACE:
                    reportReplace(
                      context,
                      difference.offset,
                      difference.deleteText,
                      difference.insertText
                    );
                    break;
                }
              });
            }
          }
        };
      }
    }
  }
};


text:
girderTest.importPlugin('jobs');
girderTest.importPlugin('gravatar');
girderTest.importPlugin('database_assetstore');
girderTest.importPlugin('large_image');
girderTest.importPlugin('minerva');

girderTest.importStylesheet('/static/built/plugins/minerva/minerva.min.css');
girderTest.importStylesheet('/static/built/plugins/jobs/plugin.min.css');

girderTest.addScripts([
    '/clients/web/static/built/plugins/minerva/minerva.min.js'
]);

// helper function to make it easy to get Backbone View instance from DOM element
var setElement = Backbone.View.prototype.setElement;
Backbone.View.prototype.setElement = function (element) {
    if (!$(element).data('backboneView')) {
        $(element).data('backboneView', []);
    }
    var views = $(element).data('backboneView');
    if (views) {
        views.push(this);
    }
    return setElement.apply(this, arguments);
};
$(function () {
    girder.auth.login('admin', 'adminpassword!').done(function () {
    });
});

describe('Main view', function () {
    it('contains the minerva app body', function () {
        waitsFor(function () {
            return $('.m-sessions-search-container:visible').length === 1;
        }, 'the main panel to be visible');

        runs(function () {
            expect($('#g-app-body-container').length).toBe(1);
        });
    });

    it('create a new session', function () {
        runs(function () {
            $('.m-session-create-button').click();
        });

        waitsFor(function () {
            return !!$('.m-save-session').length;
        });

        runs(function () {
            $('#m-session-name').val('Test session');
            $('#m-session-description').val('A session created during a client test.');
            $('.m-save-session').click();
        });

        waitsFor(function () {
            return !!$('#m-panel-groups').length;
        });

        runs(function () {
            var panels = $('#m-panel-groups');
            expect(panels.find('#m-data-panel').length).toBe(1);
            expect(panels.find('#m-layer-panel').length).toBe(1);
            expect(panels.find('#m-jobs-panel').length).toBe(1);
        });
    });
});

describe('Session view', function () {
    var layerPanelView = null;
    it('Upload a geojson and a geojson-timeseries files', function () {
        layerPanelView = $('#m-layer-panel').data('backboneView')[0];

        runs(function () {
            window.geo.util.mockVGLRenderer();

            $('.icon-upload').click();
        });

        girderTest.waitForDialog();

        runs(function () {
            girderTest._prepareTestUpload();
            girderTest.sendFile('plugins/minerva/plugin_tests/data/nys_counties.geojson');
            $('#g-files').parent().addClass('hide');
            $('.g-start-upload').click();
        });

        girderTest.waitForLoad();

        runs(function () {
            $('.icon-upload').click();
        });

        girderTest.waitForDialog();

        runs(function () {
            girderTest._prepareTestUpload();
            girderTest.sendFile('plugins/minerva/plugin_tests/data/geojson-timeseries_1.geojson');
            $('#g-files').parent().addClass('hide');
            $('.g-start-upload').click();
        });

        girderTest.waitForLoad();
    });

    it('Add two datasets to session layer', function () {
        runs(function () {
            $('.add-dataset-to-session').click();
            $('.add-dataset-to-session').click();
            $('.add-dataset-to-session').click();
        });

        waitsFor(function () {
            return layerPanelView.$('.layersList ul.datasets').children().length === 3;
        }, 'layers to be created');

        waitsFor(function () {
            var datasetId = layerPanelView.$('.m-anim-frame').closest('[m-dataset-id]').attr('m-dataset-id');
            var dataset = layerPanelView.collection.get(datasetId);
            return dataset && dataset.geoJsLayer;
        }, 'datasets be visualized');
    });

    it('Change animation frames', function () {
        runs(function () {
            var datasetId = layerPanelView.$('.m-anim-frame').closest('[m-dataset-id]').attr('m-dataset-id');
            var dataset = layerPanelView.collection.get(datasetId);
            var series = dataset.get('geoData').series;

            // all features on the timeseries layer should be hidden except for the features of current frame
            expect(_.every(series, function (series, i) {
                return _.every(series.features, function (feature) {
                    return feature.visible() === (i === 0);
                });
            })).toBe(true);

            var geoJsLayer = dataset.geoJsLayer;
            spyOn(geoJsLayer, 'draw');

            layerPanelView.$('.m-anim-frame').val(30);
            layerPanelView.$('.m-anim-frame').trigger('change');

            expect(_.every(series, function (series, i) {
                return _.every(series.features, function (feature) {
                    return feature.visible() === (i === 30);
                });
            })).toBe(true);

            expect(dataset.get('animationFrame')).toBe(30);
            expect(geoJsLayer.draw.calls.length).toBe(1);

            layerPanelView.$('.m-anim-step').click();
            layerPanelView.$('.m-anim-step').click();

            expect(_.every(series, function (series, i) {
                return _.every(series.features, function (feature) {
                    return feature.visible() === (i === 32);
                });
            })).toBe(true);

            layerPanelView.$('.m-anim-step-back').click();

            expect(_.every(series, function (series, i) {
                return _.every(series.features, function (feature) {
                    return feature.visible() === (i === 31);
                });
            })).toBe(true);

            expect(dataset.get('animationFrame')).toBe(31);
            expect(geoJsLayer.draw.calls.length).toBe(4);

            layerPanelView.$('.m-anim-play').click();

            expect(dataset.get('animationFrame')).not.toBe(31);

            layerPanelView.$('.m-anim-stop').click();

            expect(dataset.get('animationFrame')).toBe(0);

            layerPanelView.$('select[class^="m-cycle-duration"]').val(60).change();
            expect(layerPanelView.$('select[class^="m-cycle-duration"]').find(':selected').text()).toBe('1 minute');
            expect(dataset.get('animationDuration')).toBe(60);
        });
    });
});

describe('Datapanel', function () {
    var mapPanel;
    it('Select and unselect datasets', function () {
        $('.source-title#Tiff').trigger('click');
        $('.source-title#GeoJSON').trigger('click');

        // Test category selection
        $('.source-title#Tiff').next('.m-sub-category').find('.category-title#Other input').trigger('change');
        expect($('#m-data-panel .dataset input:checked').length).toEqual(1);
        $('.source-title#GeoJSON').next('.m-sub-category').find('.category-title#Other input').trigger('change');
        expect($('#m-data-panel .dataset input:checked').length).toEqual(5);
        // unselect checked categories
        $('.source-title#Tiff').next('.m-sub-category').find('.category-title#Other input').trigger('change');
        $('.source-title#GeoJSON').next('.m-sub-category').find('.category-title#Other input').trigger('change');
        expect($('#m-data-panel .dataset input:checked').length).toEqual(0);

        // test individual dataset selection
        $('.source-title#GeoJSON').next('.m-sub-category').find('.dataset input').first().prop('checked', true).trigger('change');
        expect($('#m-data-panel .dataset input:checked').length).toEqual(1);
        $('.source-title#GeoJSON').next('.m-sub-category').find('.dataset input').first().prop('checked', false).trigger('change');
        expect($('#m-data-panel .dataset input:checked').length).toEqual(0);
    });

    it('Infoviz widget', function () {
        $($('.dataset').filter(function () { return $(this).children('.m-name:contains("four_states.geojson")').length; })[0]).find('input').first().prop('checked', true).trigger('change');
        $('.show-infoviz').click();
        waitsFor(function () {
            return $('.ui-dialog.m-infoviz-widget-dialog').length;
        }, 'infoviz widget to be rendered');
        runs(function () {
            expect($('.m-infoviz-widget .chart-container .mark-rect path').length).toBe(4);
            $('.m-infoviz-widget .xlabel-selector ul.dropdown-menu li:eq(1) input').trigger('click');
            expect($('.m-infoviz-widget .chart-container .role-axis-title text').first().text()).toEqual('name, population');
        });
    });

    it('Show dataset boundaries', function () {
        mapPanel = $('#m-map-panel').data('backboneView')[0];
        runs(function () {
            $('.source-title#Tiff').next('.m-sub-category').find('.category-title#Other input').trigger('change');
            $('.source-title#GeoJSON').next('.m-sub-category').find('.category-title#Other input').trigger('change');

            $('.icon-button.show-bounds').trigger('click');
        });

        waitsFor(function () {
            return $('.icon-button.remove-bounds').length;
        }, 'boundaries to be drawn');

        runs(function () {
            expect(mapPanel.boundariesAnnotationLayer).not.toBeFalsy();
            expect(mapPanel.boundariesAnnotationLayer.annotations().length).toEqual(5);
        });
    });

    it('Toggle boundary label', function () {
        $('.icon-button.toggle-bounds-label').trigger('click');
        expect(mapPanel.boundariesAnnotationLayer.options().showLabels).toEqual(true);
        $('.icon-button.toggle-bounds-label').trigger('click');
        expect(mapPanel.boundariesAnnotationLayer.options().showLabels).toEqual(false);
    });

    it('Hide dataset boundaries', function () {
        $('.icon-button.remove-bounds').trigger('click');
        expect(mapPanel.boundariesAnnotationLayer).toBeFalsy();
    });

    it('Create boundary dataset with drawing', function () {
        $('.icon-button.m-boundary-dataset').trigger('click');
        mapPanel.drawDatasetLayer.geojson({ 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', 'geometry': { 'type': 'Polygon', 'coordinates': [[[-123.774414, 32.887971], [-123.774414, 39.748663], [-104.721679, 39.748663], [-104.721679, 32.887971], [-123.774414, 32.887971]]] }, 'properties': { 'annotationType': 'rectangle', 'name': 'Rectangle 1', 'annotationId': 1, 'fill': true, 'fillColor': '#00ff00', 'fillOpacity': 0.25, 'stroke': true, 'strokeColor': '#000000', 'strokeOpacity': 1, 'strokeWidth': 3 } }] });
        mapPanel.drawDatasetLayer.geoTrigger(geo.event.annotation.state, {});
        waitsFor(function () {
            return $('.bootbox-prompt .modal-footer .btn-primary').length;
        }, 'confirm modal to show');
        runs(function () {
            $('.bootbox-prompt .modal-footer .btn-primary').trigger('click');
        });
        waitsFor(function () {
            return $('.m-datasets[data-category=Boundary] .dataset .m-name:contains(Boundary)').length &&
                !$('.modal-backdrop').length;
        }, 'Boundary dataset to be created');
    });

    it('Filter datasets by intersecting', function () {
        $('.m-datasets[data-category=Boundary] .dataset .m-name:contains(Boundary)').first().parent().find('input').trigger('click');
        $('.icon-button.intersect-filter').trigger('click');
        waitsFor(function () {
            return $('.icon-button.clear-filters').length;
        }, 'dataset to be filtered');
        runs(function () {
            expect($('.m-datasets .dataset').length).toBe(5);
            $('.icon-button.clear-filters').trigger('click');
            expect($('.m-datasets .dataset').length).not.toBe(4);
        });
    });

    it('Filter datasets by dataset name', function () {
        $('#m-data-panel .search-bar input').val('geojson').trigger('keyup');
        waitsFor(function () {
            return $('.icon-button.clear-filters').length;
        }, 'dataset to be filtered');
        runs(function () {
            expect($('.m-datasets .dataset').length).toBe(4);
            $('.icon-button.clear-filters').trigger('click');
            expect($('.m-datasets .dataset').length).not.toBe(4);
            $('#m-data-panel .search-bar input').val('raster').trigger('keyup');
        });
        waitsFor(function () {
            return $('.icon-button.clear-filters').length;
        }, 'dataset to be filtered');
        runs(function () {
            expect($('.m-datasets .dataset').length).toBe(1);
            $('.icon-button.clear-filters').trigger('click');
        });
    });

    it('Rename dataset', function () {
        $($('.dataset').filter(function () { return $(this).children('.m-name:contains("three_states.geojson")').length; })[0]).find('.dataset-info').click();
        waitsFor(function () {
            return $('.m-dataset-info-widget').length;
        }, 'Dataset info modal to be created');
        runs(function () {
            $('.m-dataset-info-widget .edit-name').click();
            // canceling edit with esc key
            $('.m-dataset-info-widget .dataset-name input').val('abc');
            var e = $.Event('keydown', { keyCode: 27 });
            $('.m-dataset-info-widget .dataset-name input').trigger(e);
            $('.m-dataset-info-widget .edit-name').click();
            expect($('.m-dataset-info-widget .dataset-name input').val()).toBe('three_states.geojson');
            // Test change dataset name
            $('.m-dataset-info-widget .dataset-name input').val('Three states');
            $('.m-dataset-info-widget .dataset-name input').trigger('change');
            $('.m-dataset-info-widget .dataset-name button.commit-name').click();
            waitsFor(function () {
                return $('.dataset .m-name:contains("Three states")').length;
            }, 'dataset name change on dataset panel');
        });
    });

    it('Persist in memory dataset', function () {
        minerva.events.trigger('m:addExternalGeoJSON', {
            name: 'In memory dataset',
            data: { 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', 'properties': {}, 'geometry': { 'type': 'Point', 'coordinates': [-91.7578125, 41.244772343082076] } }] }
        });
        $($('.dataset').filter(function () { return $(this).children('.m-name:contains("In memory dataset")').length; })[0]).find('.persist-dataset').click();
        waitsFor(function () {
            var datasetElement = $($('.dataset').filter(function () { return $(this).children('.m-name:contains("In memory dataset")').length; })[0]);
            return datasetElement.length === 1 && datasetElement.find('.persist-dataset').length === 0;
        }, 'In memory dataset be persisted');
    });
});

describe('Layerpanel', function () {
    it('Zoom to dataset', function () {
        var mapPanel = $('#m-map-panel').data('backboneView')[0];
        var zoom = mapPanel.map.zoom();
        $('.layersList .dataset').first().find('.m-zoom-to').trigger('click');
        expect(zoom).not.toEqual(mapPanel.map.zoom());
    });
});

describe('Mappanel', function () {
    it('Take screenshot', function () {
        $('button.m-screenshot').click();
        waitsFor(function () {
            return $('.m-screenshot-result').length;
        }, 'screenshot be taken and shown');
        runs(function () {
            var screenshotResult = $('.m-screenshot-result');
            var image = screenshotResult.find('img').attr('src');
            var image2 = screenshotResult.find('a.save').attr('href');
            expect(image).toEqual(image2);
            expect(image.startsWith('data:image/png;base64,')).toBe(true);
        });
    });
});


text:
package com.idunnololz.igo;

import android.app.Dialog;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.idunnololz.utils.AlertDialogFragment;
import com.idunnololz.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private View btnNewGame;
    private View btnAbout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnNewGame = findViewById(R.id.new_game);
        btnAbout = findViewById(R.id.about);

        btnNewGame.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                (NewGameDialogFragment.newInstance()).show(getSupportFragmentManager(), "adialog");
            }

        });

        btnAbout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialogFragment.Builder()
                        .setMessage("igo created by Gary Guo")
                        .create().show(getSupportFragmentManager(), "d");
            }

        });
    }

    public static class NewGameDialogFragment extends DialogFragment {
        private Spinner boardSize;
        private Spinner handicap;
        private Spinner komi;
        private View rootView;
        private Button startGame;

        private List<CharSequence> handicapOptions = new ArrayList<CharSequence>();

        private static NewGameDialogFragment newInstance() {
            NewGameDialogFragment f = new NewGameDialogFragment();
            return f;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Dialog dialog = super.onCreateDialog(savedInstanceState);

            // request a window without the title
            dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            return dialog;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.dialog_new_game, container, false);
            boardSize = (Spinner) rootView.findViewById(R.id.boardSize);
            handicap = (Spinner) rootView.findViewById(R.id.handicap);
            komi = (Spinner) rootView.findViewById(R.id.komi);
            startGame = (Button) rootView.findViewById(R.id.btnStartGame);

            {
                ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                        R.array.board_size_array, R.layout.simple_spinner_item);
                adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
                boardSize.setAdapter(adapter);
                boardSize.setSelection(2);
                boardSize.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0, View v,
                                               int position, long arg3) {
                        int maxHandicap = 9;

                        handicapOptions.clear();

                        switch (getChosenBoardSize()) {
                            case 9:
                                maxHandicap = 4;
                                break;
                            default:
                                break;
                        }

                        for (int i = 0; i <= maxHandicap; i++) {
                            handicapOptions.add(String.valueOf(i));
                        }
                        ((ArrayAdapter<?>)handicap.getAdapter()).notifyDataSetChanged();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // do nothing...
                    }

                });
            }

            {
                for (int i = 0; i < 9; i++) {
                    handicapOptions.add(String.valueOf(i));
                }

                ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(),
                        R.layout.simple_spinner_item, handicapOptions);
                adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
                handicap.setAdapter(adapter);
            }

            {
                List<CharSequence> list = new ArrayList<CharSequence>();
                for (float i = 0; i < 10; i+=0.5f) {
                    list.add(String.valueOf(i));
                }

                ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(),
                        R.layout.simple_spinner_item, list);
                adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
                komi.setAdapter(adapter);
                komi.setSelection((int)(6.5f / .5f));
            }

            startGame.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    int boardSize = getChosenBoardSize();

                    int handicaps = handicap.getSelectedItemPosition();

                    float komiPoints = Float.valueOf(komi.getSelectedItem().toString());

                    LogUtils.d(TAG, "Board Size: " + boardSize + " handicaps: " + handicaps + " komi: " + komiPoints);

                    Intent i = new Intent(getActivity(), GameActivity.class);
                    i.putExtra(GameActivity.ARGS_BOARD_SIZE, boardSize);
                    i.putExtra(GameActivity.ARGS_HANDICAP, handicaps);
                    i.putExtra(GameActivity.ARGS_KOMI, komiPoints);
                    startActivity(i);
                }

            });

            return rootView;
        }

        private int getChosenBoardSize() {
            String strBoardSize = boardSize.getSelectedItem().toString();
            return Integer.valueOf(strBoardSize.substring(0, strBoardSize.lastIndexOf('x')));
        }
    }
}


text:
Parse and analyze nagios/icinga log.
Cli utilily now outputs uptime for a given log in json format.


text:
option(SUPPRESS_QtTesting_BUILD_OUTPUT "Suppress CGM build output" ON)
mark_as_advanced(SUPPRESS_QtTesting_BUILD_OUTPUT)

if(SUPPRESS_QtTesting_BUILD_OUTPUT)
  set(suppress_build_out SUPPRESS_BUILD_OUTPUT)
endif()

add_external_project(QtTesting
  DEPENDS qt
  CMAKE_ARGS
    ${extra_cmake_args}
    -DCMAKE_INSTALL_PREFIX=<INSTALL_DIR>
  ${suppress_build_out}
  )


text:
<!DOCTYPE html>

        <title>section-1.html</title>
        <link rel="stylesheet" type="text/css" href="playground.css" />
        <meta charset='utf-8'>
        <meta id="xcode-display" name="xcode-display" content="render" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name = "viewport" content = "width = device-width, maximum-scale=1.0">

">

  Functions are a first-class type. This means that a function can return another function as its value.


text:
package com.uber.tchannel.json;

public class RequestPojo {
    private final long requestId;
    private final String requestMessage;

    public RequestPojo(long requestId, String requestMessage) {
        this.requestId = requestId;
        this.requestMessage = requestMessage;
    }

    public long getRequestId() {
        return requestId;
    }

    public String getRequestMessage() {
        return requestMessage;
    }

    @Override
    public String toString() {
        return String.format("<%s id=%d message=%s>",
                this.getClass().getSimpleName(),
                this.requestId,
                this.requestMessage
        );
    }

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Data Controller
|--------------------------------------------------------------------------
| It manages all the data points.
|
*/
class Datapoint extends MY_Controller {

	function __construct()
	{
		$this->dontAuth = array('getData','getDataJSON','compare','export');
		parent::__construct();
		$this->load->model('variables','',TRUE);
		$this->load->model('sources','',TRUE);
		$this->load->model('datapoints','',TRUE);
		$this->load->model('sc','',TRUE);
		$this->load->model('site','',TRUE);
		$this->load->library('form_validation');
	}

	private function cNull($val)
	{
		if(strtolower($val)=="null")
		{
			return NULL;
		}
		return $val;
	}

	private function createDP($date,$time,$val,$siteid,$varid,$methid,$sourceid)
	{

		$LocalDateTime = $date . " " . $time;
		$localtimestamp = strtotime($LocalDateTime);
		$ms = $this->config->item('UTCOffset') * 3600;
		$utctimestamp = $localtimestamp - ($ms);
		$DateTimeUTC = date("Y-m-d H:i:s", $utctimestamp);
		$LocalDateTime = date("Y-m-d H:i:s", $localtimestamp);

		$dataPoint = array(
		'DataValue' => $val,
		'ValueAccuracy' => $this->cNull($this->config->item('ValueAccuracy')),
		'LocalDateTime' => $LocalDateTime,
		'UTCOffset' => $this->cNull($this->config->item('UTCOffset')),
		'DateTimeUTC' => $DateTimeUTC,
		'SiteID' => $siteid,
		'VariableID' => $varid,
		'OffsetValue' => $this->cNull($this->config->item('OffsetValue')),
		'OffsetTypeID' => $this->cNull($this->config->item('OffsetTypeID')),
		'CensorCode' => $this->cNull($this->config->item('CensorCode')),
		'QualifierID' => $this->cNull($this->config->item('QualifierID')),
		'MethodID' => $methid,
		'SourceID' => $sourceid,
		'SampleID' => $this->cNull($this->config->item('SampleID')),
		'DerivedFromID' => $this->cNull($this->config->item('DerivedFromID')),
		'QualityControlLevelID' => $this->cNull($this->config->item('QualityControlLevelID')));

		return $dataPoint;
	}

	public function addvalue()
	{

		if($_POST)
		{
			$this->form_validation->set_rules('SourceID', 'SourceID', 'trim|required');
			$this->form_validation->set_rules('SiteID', 'SiteID', 'trim|required');
			$this->form_validation->set_rules('VariableID', 'SourceID', 'trim|required');
			$this->form_validation->set_rules('MethodID', 'SiteID', 'trim|required');
			$this->form_validation->set_rules('value', 'SourceID', 'trim|required|xss_clean');
			$this->form_validation->set_rules('datepicker', 'SiteID', 'trim|required');
			$this->form_validation->set_rules('timepicker', 'SiteID', 'trim|required');
		}
		if ($this->form_validation->run() == FALSE)
		{
			  $errors = validation_errors();
			  if(!empty($errors))
			  {addError($errors);}
		}
		else
		{

			$dataPoint = $this->createDP($this->input->post('datepicker'),$this->input->post('timepicker'),$this->input->post('value'),$this->input->post('SiteID'),$this->input->post('VariableID'),$this->input->post('MethodID'),$this->input->post('SourceID'));

			$result=$this->datapoints->addPoint($dataPoint);
			if($result)
			{
				addSuccess(getTxt('ValueSuccessfully'));
				$this->updateSC();
			}
			else
			{
				addError(getTxt('ProcessingError'));
			}
		}

		//GetSources
		$sources = $this->sources->getAll();
		$sourceOptions = optionsSource($sources);
		//Get Variables
		$variables = $this->variables->getAll();
		$varOptions = optionsVariable($variables);
		//List of CSS to pass to this view
		$data=$this->StyleData;
		$data['sourcesOptions']=$sourceOptions;
		$data['variableOptions']=$varOptions;
		$this->load->view('datapoint/addvalue',$data);
	}

	public function addmultiplevalues()
	{
		if($_POST)
		{
			$dataset=array();
			$rows = $this->input->post('finalRows');
			for($i=1;$i<=$rows;$i++)
			{
				$dataPoint = $this->createDP($this->input->post('datepicker'.$i),$this->input->post('timepicker'.$i),$this->input->post('value'.$i),$this->input->post('SiteID'),$this->input->post('VariableID'.$i),$this->input->post('MethodID'.$i),$this->input->post('SourceID'));
				$dataset[]=$dataPoint;
			}

			$result=$this->datapoints->addPoints($dataset);
			if($result==$rows)
			{
				addSuccess(getTxt('DataEnteredSuccessfully'));
				$this->updateSC();
			}
			else
			{
				addError(getTxt('ProcessingError'));
			}
		}
		//GetSources
		$sources = $this->sources->getAll();
		$sourceOptions = optionsSource($sources);
		//List of CSS to pass to this view
		$data=$this->StyleData;
		$data['sourcesOptions']=$sourceOptions;
		$this->load->view('datapoint/addmultiplevalues',$data);
	}

	private function fileUploadHandler()
	{
		$newDir = "./uploads/temp".time().rand();
		$oldmask = umask(0);
		$result = mkdir($newDir,0777);
		umask($oldmask);
		if(!$result)
		{
			addError(getTxt('FailTemp'));
			return false;
		}

		//Upload files.
		$config['upload_path'] = $newDir;
		$config['allowed_types'] = 'csv|CSV';
		$this->load->library('upload', $config);
		if ( ! $this->upload->do_multi_upload('files'))
		  {
			  addError(getTxt('FailMoveFile').$this->upload->display_errors());
			  return false;
		  }
		return $this->upload->get_multi_upload_data();
	}

	private function getIDS($array, $id)
	{
		$ids=array();
		foreach($array as $row)
		{
			$ids[]=$row[$id];
		}
		return $ids;
	}

	private function processFiles($files)
	{
		$check=false;
		if($this->input->post('valueSpec'))
		{
			$check=true;
			//Values will be checked and fetched while processing.
			//Build ID tables.
			$siteIDS = $this->getIDS($this->site->getAll(),"SiteID");
			$sourceIDS = $this->getIDS($this->sources->getAll(),"SourceID");
			$varIDS = $this->getIDS($this->variables->getAll(),"VariableID");
			$this->load->model('method','',true);
			$methIDS = $this->getIDS($this->method->getAll(),"MethodID");
		}
		else
		{
			$source =  $this->input->post('SourceID');
			$site =  $this->input->post('SiteID');
			$var =  $this->input->post('VariableID');
			$meth =  $this->input->post('MethodID');
		}
		$dataset=array();
		foreach($files as $file)
		{
			$filepath = $file['full_path'];
			$handle = fopen($filepath, "r");
			if(!$handle)
			{
				addError(getTxt('FailInputStream'));
				return;
			}
			$flag=0;
			$row=1;
			$tracker=1;
			$dtIndex = 0;
			$valIndex = 1;
			while (($data = fgetcsv($handle)) !== FALSE) {
				if($flag==0)
				{
					if($check)
					{
						$dtIndex=4;
						$valIndex = 5;
						if(($data[0]!="SourceID")||($data[1]!="SiteID")||($data[2]!="VariableID")||($data[3]!="MethodID")||($data[4]!="LocalDateTime")||($data[5]!="DataValue"))
						{
						addError(getTxt('InvalidHeading')."SourceID,SiteID,VariableID,MethodID,LocalDateTime,DataValue".getTxt('PleaseFix'));
						return false;
						}
					}
					else
					{

						//Allow switching of columns.
						$dtIndex = array_search(strtolower("LocalDateTime"),array_map('strtolower',$data));
						$valIndex=array_search(strtolower("DataValue"),array_map('strtolower',$data));
						if($dtIndex===false||$valIndex===false)
						{
						addError(getTxt('InvalidHeading')."LocalDateTime,DataValue".getTxt('PleaseFix'));
						return false;
						}
					}
					$flag=1;
					continue;
				}

				try {
					$date = new DateTime($data[$dtIndex]);
				} catch (Exception $e) {
					//add error for invalid datatime format. on $row in file
					$msg=getTxt('InvalidTime').' '.$row.' '.getTxt('In').' '.$file['file_name'];
					addError($msg.getTxt('PleaseFix')."(".$e->getMessage().")");
					return false;
				}
				//Validate Value
				$value = $data[$valIndex];
				$regex="/^[\-+]?[0-9]*\.?[0-9]+$/";

				if (!preg_match($regex,$value)) {
				   $msg=getTxt('InvalidChar').' '.$row.' '.getTxt('In').' '.$file['file_name'];
				   addError($msg.getTxt('PleaseFix'));
				   return false;
				}
				$dateVal = $date->format("Y-m-d");
				$timeVal = $date->format("H:i:s");

				if($check)
				{
					//Verify if entered IDS are correct.
					$source =  $data[0];
					$site =  $data[1];
					$var =  $data[2];
					$meth =  $data[3];
					if(!in_array($source,$sourceIDS))
					{
						$msg=getTxt('invalid').' '.getTxt('sourceid').'.Row: '.$row.' '.getTxt('In').' '.$file['file_name'];
						addError($msg.getTxt('PleaseFix'));
						return false;
					}
					if(!in_array($site,$siteIDS))
					{
						$msg=getTxt('invalid').' '.getTxt('siteid').'.Row: '.$row.' '.getTxt('In').' '.$file['file_name'];
						addError($msg.getTxt('PleaseFix'));
						return false;
					}
					if(!in_array($var,$varIDS))
					{
						$msg=getTxt('invalid').' '.getTxt('varid').'.Row: '.$row.' '.getTxt('In').' '.$file['file_name'];
						addError($msg.getTxt('PleaseFix'));
						return false;
					}
					if(!in_array($meth,$methIDS))
					{
						$msg=getTxt('invalid').' '.getTxt('methodid').'.Row: '.$row.' '.getTxt('In').' '.$file['file_name'];
						addError($msg.getTxt('PleaseFix'));
						return false;
					}
				}

				$dataPoint = $this->createDP($dateVal,$timeVal,$value,$site,$var,$meth,$source);
				$dataset[]=$dataPoint;
				$row++;
			}

		}
		return $dataset;
	}

	public function importfile()
	{

		if($_POST)
		{
			$result = $this->fileUploadHandler();
			if($result)
			{
				$dataset = $this->processFiles($result);
				if($dataset)
				{
					$rows = count($dataset);
					$result=$this->datapoints->addPoints($dataset);
					if($result)
					{
						addSuccess(getTxt('Success'));
						$this->updateSC();
					}
					else
					{
						addError(getTxt('ProcessingError')."Error in data input");
					}
				}
			}
		}

		//GetSources
		$sources = $this->sources->getAll();
		$sourceOptions = optionsSource($sources);
		//Get Variables
		$variables = $this->variables->getAll();
		$varOptions = optionsVariable($variables);
		//List of CSS to pass to this view
		$data=$this->StyleData;
		$data['sourcesOptions']=$sourceOptions;
		$data['variableOptions']=$varOptions;

		$this->load->view('datapoint/importfile',$data);
	}

	public function getData()
	{
		$var = $this->input->get('varid', TRUE);
		$site = $this->input->get('siteid', TRUE);
		$method = $this->input->get('meth', TRUE);
		$start = $this->input->get('startdate', TRUE);
		$end = $this->input->get('enddate', TRUE);
		if($var!==false&&$site!==false&&$method!==false&&$start!==false&&$end!==false)
		{
			$result = $this->datapoints->getData3($site,$var,$method,$start,$end);
			$variable = $this->variables->getVariableWithUnit($var);
			$variable = $variable[0];
			//Additional logic to get the unit. sometimes its unitsType and sometimes UnitsType
			$unit = "No unit Found";
			if(array_key_exists('UnitsType', $variable))
			{
				$unit = $variable['UnitsType'];
			}
			if(array_key_exists('unitsType', $variable))
			{
				$unit = $variable['unitsType'];
			}
			$noValue = $variable['NoDataValue'];

			echo("var data_test = [\r\n");
			$num_rows = count($result);
			$count=1;
			//To echo Data in javascript format
			foreach ($result as $row)
			{
				$pieces = explode("T", $row['LocalDateTime']);
				$pieces2 = explode("-", $pieces[0]);

				$output="[Date.UTC(".$pieces2[0].",".$pieces2[1].",".$pieces2[2].",00,00,00),".$row['DataValue']."]";

				//Check for NoDataValue (Default is -9999))
				if (!($row['DataValue'] == $noValue))
				{
					echo $output;
					 if($count!=$num_rows)
						{echo ",";}
					 $count=$count+1;
					 echo ("\r\n");
				}
			}
			echo("];");
		}
		else
		{
			$data['errorMsg']="One of the parameters: VariableID, SiteID,MethodID is not defined. An example request would be getData?varid=1&siteid=2&methodid=1&startdate=2012-04-02 00:00:00&enddate=2012-04-02 00:00:00";
			$this->load->view('templates/apierror',$data);
		}

	}

	public function getDataJSON()
	{
		$var = $this->input->get('varid', TRUE);
		$site = $this->input->get('siteid', TRUE);
		$method = $this->input->get('meth', TRUE);
		$start = $this->input->get('startdate', TRUE);
		$end = $this->input->get('enddate', TRUE);
		if($var!==false&&$site!==false&&$method!==false&&$start!==false&&$end!==false)
		{
			$result = $this->datapoints->getData3($site,$var,$method,$start,$end);
			echo json_encode($result);
		}
		else
		{
			$data['errorMsg']="One of the parameters: VariableID, SiteID,MethodID is not defined. An example request would be getDateJSON?varid=1&siteid=2&methodid=1&startdate=2012-04-02 00:00:00&enddate=2012-04-02 00:00:00";
			$this->load->view('templates/apierror',$data);
		}
	}

	public function delete()
	{
		$valueid = end($this->uri->segment_array());
		if($valueid=="delete")
		{
			$data['errorMsg']="One of the parameters: ValueID is not defined. An example request would be delete/1";
			$this->load->view('templates/apierror',$data);
			return;
		}
		$result = $this->datapoints->delete($valueid);
		if($result)
			{
				$output="success";
				$this->updateSC();
			}
		else
			{
				$output="failed";
			}
		$output = array("status"=>$output);
		echo json_encode($output);
	}

	public function edit()
	{
		$valueid = end($this->uri->segment_array());
		if($valueid=="edit")
		{
			$data['errorMsg']="One of the parameters: ValueID,date,time,value is not defined. An example request would be edit/1?val=2&dt=2001-01-01&time=12:00";
			$this->load->view('templates/apierror',$data);
			return;
		}
		$value = $this->input->get('val', TRUE);
		$dt=$this->input->get('dt', TRUE);
		$time = $this->input->get('time', TRUE);

		if($valueid!==false&&$value!==false&&$dt!==false&&$time!==false)
		{
			$LocalDateTime = $dt . " " . $time . ":00";
			$localtimestamp = strtotime($LocalDateTime);
			$ms = $this->config->item('UTCOffset') * 3600;
			$utctimestamp = $localtimestamp - ($ms);
			$DateTimeUTC = date("Y-m-d H:i:s", $utctimestamp);
			$result = $this->datapoints->editPoint($valueid,$value,$LocalDateTime,$DateTimeUTC);
			if($result)
			{
				$output="success";
				$this->updateSC();
			}
			else
			{
				$output="failed";
			}
			$output = array("status"=>$output);
			echo json_encode($output);
		}
		else
		{
			$data['errorMsg']="One of the parameters: ValueID,date,time,value is not defined. An example request would be edit/1?val=2&dt=2001-01-01&time=12:00";
			$this->load->view('templates/apierror',$data);
		}
	}

	public function export()
	{
		$var = $this->input->get('varid', TRUE);
		$site = $this->input->get('siteid', TRUE);
		$method = $this->input->get('meth', TRUE);
		$start = $this->input->get('startdate', TRUE);
		$end = $this->input->get('enddate', TRUE);
		if($var!==false&&$site!==false&&$method!==false&&$start!==false&&$end!==false)
		{
			$result = $this->datapoints->getData3($site,$var,$method,$start,$end);
			$methodDesc = $this->datapoints->getMethodDescription($method);
			//print_r($result);

			$retVal = "\"time\",\"value\",\"method\"\n";

			foreach($result as &$var)
			{
				$retVal .= "\"".$var['LocalDateTime'] ."\",";
				$retVal .= $var['DataValue'].",";
				$retVal .= "\"".$methodDesc."\"\n";
			}
			$outFileName = $this->datapoints->getOutputFileName($site, $var, $method);

			header( 'Content-Type: text/csv' );
			header("Content-Disposition: attachment; filename=$outFileName".$site.'.csv');
			//$this->load->dbutil();
			//echo $this->dbutil->csv_from_result($result);
			echo $retVal;
		}
		else
		{
			$data['errorMsg']="One of the parameters: VariableID, SiteID,MethodID is not defined. An example request would be export?varid=1&siteid=2&methodid=1&startdate=2012-04-02 00:00:00&enddate=2012-04-02 00:00:00";
			$this->load->view('templates/apierror',$data);
		}
	}

	public function add()
	{
		$var = $this->input->get('varid', TRUE);
		$site = $this->input->get('sid', TRUE);
		$method = $this->input->get('mid', TRUE);
		$value = $this->input->get('val', TRUE);
		$dt=$this->input->get('dt', TRUE);
		$time = $this->input->get('time', TRUE);
		$source = $this->sc->getSourceBySite($site);
		$sourceID = $source[0]['SourceID'];
		if($var!==false&&$value!==false&&$dt!==false&&$time!==false&&$site!==false&&$method!==false)
		{
			$dataPoint = $this->createDP($dt,$time,$value,$site,$var,$method,$sourceID);
			$result=$this->datapoints->addPoint($dataPoint);
			if($result)
			{
				$output="success";
				$this->updateSC();
			}
			else
			{
				$output="failed";
			}
			$output = array("status"=>$output,"id"=>$result);
			echo json_encode($output);
		}

		else
		{
			$data['errorMsg']="One of the parameters: VariableID,date,time,value,SiteID,MethodID, is not defined. An example request would be add?val=2&dt=2001-01-01&time=12:00&sid=1&mid=1&varid=1";
			$this->load->view('templates/apierror',$data);
		}
	}
	public function compare()
	{
		$valueid = end($this->uri->segment_array());
		if($valueid=="compare")
		{
			$data['errorMsg']="One of the parameters: compareID. An example request would be compare/1";
			$this->load->view('templates/apierror',$data);
			return;
		}
		//List of CSS to pass to this view
		$data=$this->StyleData;

		if($valueid==2)
		{
			$siteid = $this->input->get('siteid', TRUE);
			$site = $this->site->getSite($siteid);
			$data['SiteName']=$site[0]['SiteName'];
		}

		$this->load->view("compare/".$valueid,$data);
	}

	public function updateSC()
	{
		//UPDATES THE SERIES CATALOG.
		//BREAKING FROM CODEIGINITER POLICIES HERE
		//Its just better for now to use the same script.

		$connection = mysqli_connect($this->config->item('database_host'), $this->config->item('database_username'), $this->config->item('database_password'),$this->config->item('database_name'))
		or die("
Error connecting to database: " .
				   mysqli_error() . "
");
		mysqli_set_charset ($connection,"utf8");
		  //echo "
Connected to MySQL!
";

		/*  $db = mysql_select_db($this->config->item('database_name'),$connection)
			or die("
Error selecting the database " . $this->config->item('database_name') .
			  mysql_error() . "
");
		*/
		require_once APPPATH.'../assets/update_series_catalog.php';
	}
}


text:
.. _nginx-stage-app:

nginx_stage app
===============

This command will generate a web application NGINX configuration file
and subsequently restart the NGINX process as the user.

.. code-block:: sh

   sudo nginx_stage app [OPTIONS]

.. program:: nginx_stage app

Required Options
----------------

.. option:: -u <user>, --user <user>

   The user of the per-user NGINX process.

.. option:: -r <sub_request>, --sub-request <sub_request>

   The request URI path beneath the sub-URI path.

General Options
---------------

.. option:: -i <sub_uri>, --sub-uri <sub_uri>

  The sub-URI path in the request.

.. option:: -N, --skip-nginx

   Skip execution of the per-user NGINX process.

.. note::

   The sub-URI corresponds to any reverse proxy namespace that denotes the
   request should be proxied to the per-user NGINX server (e.g., ``/pun``)

Examples
--------

To generate an app config from the request::

  http://ondemand.center.edu/pun/usr/jim/myapp/session/1

and subsequently restart the per-user NGINX process:

.. code-block:: sh

   sudo nginx_stage app --user 'bob' --sub-uri '/pun' --sub-request '/usr/jim/myapp/session/1'

To generate **only** the app config:

.. code-block:: sh

   sudo nginx_stage app --user 'bob' --sub-uri '/pun' --sub-request '/sys/dashboard' --skip-nginx

This will return the path to the app config and will not restart the
NGINX process.

Default Installation
....................

:numref:`app-mapping-table` details the mapping between the requested URL path
to the app root directory for in the NGINX app config under a default
installation.

.. _app-mapping-table:
.. list-table:: Mapping of apps for a default installation
   :header-rows: 1

   * - App type
     - URL path
     - File system path
   * - dev
     - :file:`/dev/{app_name}/\*`
     - :file:`/var/www/ood/apps/dev/{app_owner}/gateway/{app_name}`
   * - usr
     - :file:`/usr/{app_owner}/{app_name}/\*`
     - :file:`/var/www/ood/apps/usr/{app_owner}/gateway/{app_name}`
   * - sys
     - :file:`/sys/{app_name}/\*`
     - :file:`/var/www/ood/apps/sys/{app_name}`


text:
<?php
namespace SpareParts\Enum\Exception;

class InvalidEnumClassException extends \InvalidArgumentException
{

}


text:
#ifndef RPC_SERVER_REQUEST_DATA_H_
#define RPC_SERVER_REQUEST_DATA_H_

#include <3rdparty/msgpack/msgpack.hpp>
namespace sf1r
{

struct RpcServerRequestData
{
};

struct TestData: public RpcServerRequestData
{
    bool ret;
    MSGPACK_DEFINE( ret )
};
}

#endif /* RPC_SERVER_REQUEST_DATA_H_ */


text:
UENUM(BlueprintType)
enum class EControlPanelEffectType : uint8
{
    GRAVITY          UMETA(DisplayName="Gravity"),
    COLLISION        UMETA(DisplayName="Collision"),
    ROTATION         UMETA(DisplayName="Rotation"),
    TRANSLATION      UMETA(DisplayName="Translation"),
    SCALE            UMETA(DisplayName="Scale"),
    WORLD_TIME       UMETA(DisplayName="World time"),
    WORLD_GRAVITY    UMETA(DisplayName="World gravity")
};


text:
<?php

function get_climate_events_by_distance_from_zip() {
 $all_climate_events = getAllClimateEvents();
  $distance = getDistanceFromGetParams();
  $zip = getZipFromGetParams();
  $filtered_climate_events = filterClimateEventsByDistanceFromZip($all_climate_events, $distance, $zip);
  $json_formatted_filtered_climate_events = formatClimateEventObjectsIntoJSON($filtered_climate_events, $distance);

  drupal_json_output($json_formatted_filtered_climate_events);
}

function getDistanceFromGetParams() {
  $url_params = $_GET['q'];
  return explode('/', $url_params)[3];
}

function getZipFromGetParams() {
  $url_params = $_GET['q'];
  return explode('/', $url_params)[2];
}

function getAllClimateEvents() {
  return views_get_view_result('climate_events', 'services_1');
}

function filterClimateEventsByDistanceFromZip($climate_events, $distance, $zip) {
  include_once(DRUPAL_ROOT . '/sites/all/modules/custom/climate_events/includes/classes/ClimateEvent.php');
  include_once(DRUPAL_ROOT . '/sites/all/modules/custom/climate_events/includes/classes/DrupalWrappers/ZipCode.php');

  if($distance === 'all') {
    return $climate_events;
  }

  $zip = new ZipCode($zip);
  $climate_events_within_range = [];
  foreach($climate_events as $drupal_climate_event) {
    $climate_event = new ClimateEvent($drupal_climate_event);

    if(getDistanceInMilesBetweenLatLongPoints($climate_event->getLatLong(), $zip->getLatLong()) < $distance) {
      $climate_events_within_range[] = $drupal_climate_event;
    }
  }

  return $climate_events_within_range;

}

function getDistanceInMilesBetweenLatLongPoints($event_latlong, $point_latlong){
  $radius_of_earth_in_miles = 3961;

  $dLat = deg2rad($event_latlong->getLatitude() - $point_latlong->getLatitude());
  $dLon = deg2rad($event_latlong->getLongitude() - $point_latlong->getLongitude());
  $lat1 = deg2rad($event_latlong->getLatitude());
  $lat2 = deg2rad($point_latlong->getLatitude());

  $a = sin($dLat/2) * sin($dLat/2) +
    sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2);

  $c = 2 * atan2(sqrt($a), sqrt(1-$a));
  return $radius_of_earth_in_miles * $c;
}

function formatClimateEventObjectsIntoJSON($climate_events, $distance) {
  //TODO: refactor so this doesn't have non-formatting logic in it
  include_once(DRUPAL_ROOT . '/sites/all/modules/services_views/services_views.resource.inc');
  $view_info['view_name'] = 'climate_events';
  $view_info['display_id'] = 'services_1';
  $climate_events_view = views_get_view('climate_events', 'services_1');
  $nids = getNidsFromViewResults($climate_events);
  //$nids = implode('|',$nids);
  if (empty($nids) && $distance !== 'all') {
    return [];
  }

  if ($distance !== 'all') {
    $climate_events_view->set_arguments(array($nids));
    //TODO: refactor so we call this function in the first place and don't have to call it
    // again here
  }
    $result = services_views_execute_view(null, $climate_events_view, 'services_1');

  $result = addEventTypeNameAlongsideTypeId($result);
  $result = renameClimateEventsKeys($result);
  $result = groupByEventDay($result);
  return $result;
}

function formatClimateEventObjectIntoJSON($climate_event, $drupal_to_json_mappings) {
  $formatted_event = [];
  $climate_event_obj = $climate_event->_field_data['nid']['entity'];

  foreach($drupal_to_json_mappings as $key => $value) {
    $formatted_event[$value['label']] = $climate_event_obj->{$key};
  }
}

function getNidsFromViewResults($results) {
  $nids = [];
  foreach($results as $key => $value) {
    $nids[] = $value->nid;
  }
  return $nids;
}

//function filterResultsHereBecauseICantGetViewsToFilterBasedOnMyArguments($results_to_filter, $nids) {
//  $filtered_results = [];
//  foreach($results_to_filter as $key => $value) {
//    if($value->nid) {
//      $filtered_results[] = $value;
//    }
//  }
//  return $filtered_results;
//}


text:
package com.valiha

import org.junit.runner.RunWith
import org.scalatest._
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class AuthorizeTest_Spec extends FreeSpec {

  "Is Authorize.net Raw WS available? " - {

    val host = "https://apitest.authorize.net/soap/v1/Service.asmx"
    val req = <IsAlive xmlns="https://api.authorize.net/soap/v1/"/>
    val cli = new RawSoapClient
    println("##### request:\n" + cli.wrap(req))
    val resp = cli.sendMessage(host, req)
    assert(resp.isDefined)
    println("##### response:\n" + resp.get.toString())
    assert(List("Ok") == (resp.get \\ "resultCode").map(_.text))

  }

  "Is Authorize.net JAX-WS available? " - {

  //val host = "http://localhost:80/soap/v1/Service.asmx?WSDL"
  val host = "https://apitest.authorize.net/soap/v1/Service.asmx?WSDL"

    val client = new JaxWSClient(new java.net.URL(host))
    assert(client.isAlive.get == "Ok")

  }

}


text:
#include <Furrovine++/Plane.h>
#include <Furrovine++/Matrix.h>

namespace Furrovine {

	template <typename T>
	struct TFrustum {
		TPlane<T> nearplane, farplane, bottomplane, topplane, leftplane, rightplane;
		TMatrix4<T> matrix;

		TFrustum( const RMatrix4<T>& ViewProj = Matrix::Identity ) : matrix( ViewProj ) {

			leftplane.distance = -( ViewProj.m33 + ViewProj.m41 );
			leftplane.normal.x = -( ViewProj.m14 + ViewProj.m11 );
			leftplane.normal.y = -( ViewProj.m13 + ViewProj.m21 );
			leftplane.normal.z = -( ViewProj.m23 + ViewProj.m31 );

			rightplane.distance = -( ViewProj.m33 - ViewProj.m41 );
			rightplane.normal.x = -( ViewProj.m14 - ViewProj.m11 );
			rightplane.normal.y = -( ViewProj.m13 - ViewProj.m21 );
			rightplane.normal.z = -( ViewProj.m23 - ViewProj.m31 );

			topplane.distance = -( ViewProj.m33 - ViewProj.m42 );
			topplane.normal.x = -( ViewProj.m14 - ViewProj.m12 );
			topplane.normal.y = -( ViewProj.m13 - ViewProj.m22 );
			topplane.normal.z = -( ViewProj.m23 - ViewProj.m32 );

			bottomplane.distance = -( ViewProj.m33 + ViewProj.m42 );
			bottomplane.normal.x = -( ViewProj.m14 + ViewProj.m12 );
			bottomplane.normal.y = - ( ViewProj.m13 + ViewProj.m22 );
			bottomplane.normal.z = - ( ViewProj.m23 + ViewProj.m32 );

			nearplane.distance = -ViewProj.m32;
			nearplane.normal.x = -ViewProj.m13;
			nearplane.normal.y = - ViewProj.m12;
			nearplane.normal.z = - ViewProj.m22;

			farplane.distance = -( ViewProj.m33 - ViewProj.m43 );
			farplane.normal.x = -( ViewProj.m14 - ViewProj.m13 );
			farplane.normal.y = -( ViewProj.m13 - ViewProj.m23 );
			farplane.normal.z = -( ViewProj.m23 - ViewProj.m33 );
		}

		const Plane& Near( ) const {
			return nearplane;
		}

		const Plane& Far( ) const {
			return farplane;
		}

		const Plane& Right( ) const {
			return rightplane;
		}

		const Plane& Left( ) const {
			return leftplane;
		}

		const Plane& Top( ) const {
			return topplane;
		}

		const Plane& Bottom( ) const {
			return bottomplane;
		}

		const Matrix& FrustumMatrix( ) const {
			return matrix;
		}

	};
}


text:
Javascript faceoff!

Angular vs React


text:
goog.provide('shaka.util.DelayedTick');

/**
 * @summary
 * This class wraps a function so that we can defer executing the function by X
 * seconds.
 *
 * @final
 */
shaka.util.DelayedTick = class {
  /**
   * @param {function()} onTick
   */
  constructor(onTick) {
    /** @private {function()} */
    this.onTick_ = onTick;

    /** @private {?function()} */
    this.cancelPending_ = null;
  }

  /**
   * Call |onTick| after |delayInSeconds| has elapsed. If there is already a
   * pending call to |onTick|, the pending call will be canceled.
   *
   * @param {number} delayInSeconds
   * @return {!shaka.util.DelayedTick}
   */
  tickAfter(delayInSeconds) {
    // We only want one timeout set at a time, so make sure no other timeouts
    // are running.
    this.stop();

    // We will wrap these values in a function to allow us to cancel the timeout
    // we are about to create.
    let alive = true;
    let timeoutId = null;

    this.cancelPending_ = () => {
      window.clearTimeout(timeoutId);
      alive = false;
    };

    // For some reason, a timeout may still execute after we have cleared it in
    // our tests. We will wrap the callback so that we can double-check our
    // |alive| flag.
    const onTick = () => {
      if (alive) {
        this.onTick_();
      }
    };

    timeoutId = window.setTimeout(onTick, delayInSeconds * 1000);

    return this;
  }

  /**
   * Cancel any pending calls to |onTick|. If there are no pending calls to
   * |onTick|, this will be a no-op.
   */
  stop() {
    if (this.cancelPending_) {
      this.cancelPending_();
      this.cancelPending_ = null;
    }
  }
};


text:
from setuptools import setup, find_packages
from os.path import join, dirname

import {{ project }}

setup(
    name='{{ project }}',
    version={{ project }}.__version__,
    packages=find_packages(),
    long_description=open(join(dirname(__file__), 'README.md')).read(),
    )


text:
package artronics.chapar.core.analyser;

import org.junit.Test;

import static org.junit.Assert.*;

public class CsvLoggerWrapperTest
{
    @Test
    public void Test_read_config_file()
    {

        String[] foo = {"packets", "network_map"};
        CsvLoggerWrapper csv = new CsvLoggerWrapper();
//        assertArrayEquals(foo,csv.csvFiles);
    }

    @Test
    public void It_shoud_log_to_csv()
    {
//        CsvLoggerWrapper.log("packets", new Analysable()
//        {
//            @Override
//            public String toCsv()
//            {
//                return "foo kir";
//            }
//        });
    }

}


text:
package org.kie.workbench.common.screens.datamodeller.model.index;

import java.util.ArrayList;
import java.util.List;

import org.kie.workbench.common.screens.datamodeller.model.index.terms.valueterms.ValueJavaTypeInterfaceIndexTerm;
import org.kie.workbench.common.services.refactoring.model.index.IndexElementsGenerator;
import org.uberfire.commons.data.Pair;
import org.uberfire.commons.validation.PortablePreconditions;

public class JavaTypeInterface implements IndexElementsGenerator {

    private ValueJavaTypeInterfaceIndexTerm javaTypeInterfaceTerm;

    public JavaTypeInterface( final ValueJavaTypeInterfaceIndexTerm javaTypeInterfaceTerm ) {
        this.javaTypeInterfaceTerm = PortablePreconditions.checkNotNull( "javaTypeInterfaceTerm",
                javaTypeInterfaceTerm );
    }

    @Override
    public List<Pair<String, String>> toIndexElements() {
        final List<Pair<String, String>> indexElements = new ArrayList<Pair<String, String>>();
        indexElements.add( new Pair<String, String>( javaTypeInterfaceTerm.getTerm(),
                javaTypeInterfaceTerm.getValue() ) );
        return indexElements;
    }
}


text: Binary Search Tree based implementation of the Book Store.


text:
#include "MQ/Web/QueueManagerInquire.h"

namespace MQ {
namespace Web {

QueueManagerInquire::QueueManagerInquire(CommandServer& commandServer, Poco::JSON::Object::Ptr input)
: PCFCommand(commandServer, MQCMD_INQUIRE_Q_MGR, "QueueManager", input)
{
	// Optional parameters
	addParameter<std::string>(MQCACF_COMMAND_SCOPE, "CommandScope");
	addAttributeList(MQIACF_Q_MGR_ATTRS, "QMgrAttrs");
}

QueueManagerInquire::~QueueManagerInquire()
{
}

Poco::JSON::Array::Ptr QueueManagerInquire::execute()
{
	PCFCommand::execute();

	Poco::JSON::Array::Ptr json = new Poco::JSON::Array();

	for(PCF::Vector::const_iterator it = begin(); it != end(); it++)
	{
		if ( (*it)->isExtendedResponse() ) // Skip extended response
			continue;

		Poco::JSON::Object::Ptr data = new Poco::JSON::Object();
		json->add(createJSON(**it));
	}

	return json;
}

}} //  Namespace MQ::Web


text:
<?php
/**
 * Created by PhpStorm.
 * User: matthes
 * Date: 28.07.17
 * Time: 12:20
 */

namespace Phore\File;

use Phore\File\Exception\FileAccessException;

class FileStream
{

    private $res;
    /**
     * @var File
     */
    private $file;

    public function __construct($res, File $file)
    {
        $this->res = $res;
        $this->file = $file;
    }

    public function flock(int $operation) : self {
        if ( ! @flock($this->res, $operation)) {
            throw new FileAccessException("Cannot flock('$this->file'): " . error_get_last()["message"]);
        }
        return $this;
    }

    public function feof() : bool {
        return @feof($this->res);
    }

    public function fwrite ($data) : self {
        if (false === @fwrite($this->res, $data))
            throw new FileAccessException("Cannot get fwrite('$this->file'): " . error_get_last()["message"]);
        return $this;
    }

    public function fread (int $length) : string {
        if (false === ($data = @fread($this->res, $length)))
            throw new FileAccessException("Cannot get fread('$this->file'): " . error_get_last()["message"]);
        return $data;
    }

    public function fgets (int $length=null) {
        if (false === ($data = @fgets($this->res, $length)) && ! @feof($this->res))
            throw new FileAccessException("Cannot get fgets('$this->file'): " . error_get_last()["message"]);
        return $data;
    }

    public function freadcsv (int $length=0, string $delimiter=",", string $enclosure='"', string $escape_char = "\\") : array {
        if (false === ($data = @fgetcsv($this->res, $length, $delimiter, $enclosure, $escape_char)) && ! @feof($this->res))
            throw new FileAccessException("Cannot get fgetcsv('$this->file'): " . error_get_last()["message"]);
        return $data;
    }

    public function fputcsv (array $fields, string $delimiter=",", string $enclosure='"', string $escape_char = "\\") : self {
        if (false === @fputcsv($this->res, $fields, $delimiter, $enclosure, $escape_char))
            throw new FileAccessException("Cannot get fgets('$this->file'): " . error_get_last()["message"]);
        return $this;
    }

    public function fclose() : File {
        if (false === @fclose($this->res))
            throw new FileAccessException("Cannot get fgets('$this->file'): " . error_get_last()["message"]);
        return $this->file;
    }

}


text:
/**
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * */

package org.myrobotlab.control;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.service.GUIService;
import org.myrobotlab.service.Twitter;
import org.myrobotlab.service._TemplateService;
import org.slf4j.Logger;

public class TwitterGUI extends ServiceGUI implements ActionListener {

	static final long serialVersionUID = 1L;
	public final static Logger log = LoggerFactory.getLogger(_TemplateServiceGUI.class.getCanonicalName());

	JPasswordField consumerKey = new JPasswordField("XXXXXX", 20);
	JPasswordField consumerSecret = new JPasswordField("XXXXXX", 20);
	JPasswordField accessToken = new JPasswordField("XXXXXX", 20);
	JPasswordField accessTokenSecret = new JPasswordField("XXXXXX", 20);
	JButton setKeys = new JButton("set keys");
	JTextField text = new JTextField(20);
	JButton tweet = new JButton("tweet");
	Twitter twitter = null;

	public TwitterGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) {
		super(boundServiceName, myService, tabs);
		display.setLayout(new BorderLayout());
		JPanel keyInfo = new JPanel(new GridLayout(5, 2));
		keyInfo.add(new JLabel("consumer key"));
		keyInfo.add(consumerKey);
		keyInfo.add(new JLabel("consumer secret"));
		keyInfo.add(consumerSecret);
		keyInfo.add(new JLabel("access token"));
		keyInfo.add(accessToken);
		keyInfo.add(new JLabel("access token secret"));
		keyInfo.add(accessTokenSecret);
		keyInfo.add(new JLabel(""));
		keyInfo.add(setKeys);
		setKeys.addActionListener(this);
		tweet.addActionListener(this);
		// display.setLayout(new BorderLayout());
		display.add(keyInfo, BorderLayout.NORTH);
		gc.gridx = 0;
		JPanel tweetPanel = new JPanel(new GridLayout(2, 1));
		tweetPanel.add(text);
		tweetPanel.add(tweet);
		display.add(tweetPanel, BorderLayout.SOUTH);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		Object o = event.getSource();
		if (o == setKeys) {
			myService.send(boundServiceName, "setSecurity", new String(consumerKey.getPassword()), new String(consumerSecret.getPassword()), new String(accessToken.getPassword()),
					new String(accessTokenSecret.getPassword()));
		} else if (o == tweet) {

			myService.send(boundServiceName, "tweet", new String(text.getText()));

		}

		// TODO Auto-generated method stub

	}

	@Override
	public void attachGUI() {
		subscribe("publishState", "getState", _TemplateService.class);
		myService.send(boundServiceName, "publishState");
	}

	@Override
	public void detachGUI() {
		unsubscribe("publishState", "getState", _TemplateService.class);
	}

	public void getState(final Twitter twitter) {
		this.twitter = twitter;
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				consumerKey.setText(twitter.consumerKey);
				consumerSecret.setText(twitter.consumerSecret);
				accessToken.setText(twitter.accessToken);
				accessTokenSecret.setText(twitter.accessTokenSecret);
				text.setText("Your Text Here");

			}
		});
	}

	@Override
	public void init() {

	}

	public void setState() {
		myService.send(boundServiceName, "setState", twitter);
	}

}


text:
package org.apache.logging.log4j.core.config;

import static org.junit.Assert.*;

import java.util.Map;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.plugins.PluginManager;
import org.junit.Test;

public class BaseConfigurationTest {

    @Test
    public void testMissingRootLogger() throws Exception {
        PluginManager.addPackage("org.apache.logging.log4j.test.appender");
        final LoggerContext ctx = Configurator.initialize("Test1", "missingRootLogger.xml");
        final Logger logger = LogManager.getLogger("sample.Logger1");
        final Configuration config = ctx.getConfiguration();
        assertNotNull("Config not null", config);
//        final String MISSINGROOT = "MissingRootTest";
//        assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(),
//                MISSINGROOT.equals(config.getName()));
        final Map<String, Appender> map = config.getAppenders();
        assertNotNull("Appenders not null", map);
        assertEquals("Appenders Size", 2, map.size());
        assertTrue("Contains List", map.containsKey("List"));
        assertTrue("Contains Console", map.containsKey("Console"));

        final Map<String, LoggerConfig> loggerMap = config.getLoggers();
        assertNotNull("loggerMap not null", loggerMap);
        assertEquals("loggerMap Size", 1, loggerMap.size());
        // only the sample logger, no root logger in loggerMap!
        assertTrue("contains key=sample", loggerMap.containsKey("sample"));

        final LoggerConfig sample = loggerMap.get("sample");
        final Map<String, Appender> sampleAppenders = sample.getAppenders();
        assertEquals("sampleAppenders Size", 1, sampleAppenders.size());
        // sample only has List appender, not Console!
        assertTrue("sample has appender List", sampleAppenders.containsKey("List"));

        final BaseConfiguration baseConfig = (BaseConfiguration) config;
        final LoggerConfig root = baseConfig.getRootLogger();
        final Map<String, Appender> rootAppenders = root.getAppenders();
        assertEquals("rootAppenders Size", 1, rootAppenders.size());
        // root only has Console appender!
        assertTrue("root has appender Console", rootAppenders.containsKey("Console"));
        assertEquals(Level.ERROR, root.getLevel());

        logger.isDebugEnabled();
        Configurator.shutdown(ctx);
    }

}


text:
/* global define */
/* global context, describe, it */

define([
  'shared',
  'sulfur/schema/regex/branch',
  'sulfur/schema/regex/codepoint',
  'sulfur/schema/regex/codeunit',
  'sulfur/schema/regex/group',
  'sulfur/schema/regex/pattern',
  'sulfur/schema/regex/piece',
  'sulfur/schema/regex/quant'
], function (
    shared,
    Branch,
    Codepoint,
    Codeunit,
    Group,
    Pattern,
    Piece,
    Quant
) {

  'use strict';

  var expect = shared.expect;
  var sinon = shared.sinon;

  describe('sulfur/schema/regex/piece', function () {

    describe('#initialize()', function () {

      it("should initialize the piece with the given atom", function () {
        var c = Codepoint.create('a');
        var p = Piece.create(c);
        expect(p.atom).to.equal(c);
      });

      it("should initialize the piece with the given quantifier", function () {
        var c = Codepoint.create('a');
        var q = Quant.create(1, 3);
        var p = Piece.create(c, q);
        expect(p.quant).to.equal(q);
      });

      context("when called without quantifier", function () {

        it("should use a quantifier of exactly 1", function () {
          var p = Piece.create();
          expect(p.quant).to.eql(Quant.create(1));
        });

      });

    });

    describe('#containsEmptyGroup()', function () {

      context("when .atom is a group", function () {

        it("should return the result of calling .isEmpty on the group", function () {
          var group = Group.create();
          var spy = sinon.spy(group, 'isEmpty');
          var piece = Piece.create(group);
          var result = piece.containsEmptyGroup();
          expect(spy).to.be.calledOn(piece.atom);
          expect(result).to.equal(spy.getCall(0).returnValue);
        });

      });

      context("when .atom is a pattern", function () {

        it("should return the result of calling .containsEmptyGroup on the pattern", function () {
          var pattern = Pattern.create([ Branch.create() ]);
          var spy = sinon.spy(pattern, 'containsEmptyGroup');
          var piece = Piece.create(pattern);
          var result = piece.containsEmptyGroup();
          expect(spy).to.be.calledOn(piece.atom);
          expect(result).to.equal(spy.getCall(0).returnValue);
        });

      });

      context("when .atom is anything else", function () {

        it("should return false", function () {
          var piece = Piece.create(Codepoint.create('a'));
          expect(piece.containsEmptyGroup()).to.be.false;
        });

      });

    });

    describe('#containsGroupWithSurrogateCodepoints()', function () {

      context("when .atom is a group", function () {

        it("should return the result of calling .containsSurrogateCodepoints on the group", function () {
          var group = Group.create([ Codeunit.create(0xD800) ]);
          var spy = sinon.spy(group, 'containsSurrogateCodepoints');
          var piece = Piece.create(group);
          var result = piece.containsGroupWithSurrogateCodepoints();
          expect(spy).to.be.calledOn(piece.atom);
          expect(result).to.equal(spy.getCall(0).returnValue);
        });

      });

      context("when .atom is a pattern", function () {

        it("should return the result of calling .containsGroupWithSurrogateCodepoints on the pattern", function () {
          var pattern = Pattern.create([ Branch.create() ]);
          var spy = sinon.spy(pattern, 'containsGroupWithSurrogateCodepoints');
          var piece = Piece.create(pattern);
          var result = piece.containsGroupWithSurrogateCodepoints();
          expect(spy).to.be.calledOn(piece.atom);
          expect(result).to.equal(spy.getCall(0).returnValue);
        });

      });

      context("when .atom is anything else", function () {

        it("should return false", function () {
          var piece = Piece.create(Codepoint.create('a'));
          expect(piece.containsEmptyGroup()).to.be.false;
        });

      });

    });

  });

});


text:
import Ember from 'ember';

var Router = Ember.Router.extend({
  location: BancoENV.locationType
});

Router.map(function() {
  this.resource('accounts');

  this.resource('account', { path: '/accounts/:account_id' }, function() {
    this.route('transactions', { path: '/' }, function() {
      this.route('image', { path: '/transactions/:transaction_id/image' });
    });
  });

  this.resource('transfers', function() {
    this.route('new');
    this.route('confirm', { path: '/:transfer_id/confirm' });
    this.route('show', { path: '/:transfer_id' });
  });

  this.route('modelNotFound', { path: '/not-found' });
});

export default Router;