text:
namespace AE.Http.Proxy.Integration.Autofac
{
    using System;
    using System.Reflection;

    using AE.Http.Proxy.Abstractions;
    using AE.Http.Proxy.Abstractions.Context.Converters;
    using AE.Http.Proxy.Abstractions.Context.Filters;

    using global::Autofac;
    using global::Autofac.Builder;
    using global::Autofac.Features.Scanning;

    public static class ContainerBuilderExtensions
    {
        public static IRegistrationBuilder<IProxy, SimpleActivatorData, SingleRegistrationStyle> RegisterProxy(this ContainerBuilder builder)
        {
            return builder.Register(BuildProxy);
        }

        public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> RegisterProxyFilters(
            this ContainerBuilder builder,
            Assembly assembly)
        {
            return builder.RegisterAssemblyTypesAssignableFrom(assembly, typeof(IProxyFilter));
        }

        public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> RegisterProxyMessageConverters(
            this ContainerBuilder builder,
            Assembly assembly)
        {
            return builder.RegisterAssemblyTypesAssignableFrom(assembly, typeof(IMessageConverter));
        }

        public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> RegisterProxyCaller(
            this ContainerBuilder builder,
            Assembly assembly)
        {
            return builder.RegisterAssemblyTypesAssignableFrom(assembly, typeof(IProxyCaller));
        }

        private static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> RegisterAssemblyTypesAssignableFrom(
            this ContainerBuilder builder,
            Assembly assembly,
            Type type)
        {
            return builder.RegisterAssemblyTypes(assembly).Where(type.IsAssignableFrom);
        }

        private static IProxy BuildProxy(IComponentContext c)
        {
            return new AutofacProxyBuilder(c).AddFilters().AddMessageConverters().Build();
        }
    }
}


text:
'use strict';

var path = require('path');
var assume = require('assume');
var rimraf = require('rimraf');
var async = require('async');

var helpers = require('./helpers');
var macros = require('./macros');

describe('fetch.test', function () {
  this.timeout(3E5);
  var limit = 2;

  afterEach(function (done) {
    helpers.cleanup(done);
  });

  it('should fetch and unpack packages when given a list of packages',
    macros.fetchAndUntar({
      dir: helpers.dir,
      limit: limit,
      packages: helpers.packages
    })
  );
});

redpajama_set_name: RedPajamaGithub


text:
@interface MDMViewController : UIViewController

@end


text:
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Analytics.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;

namespace LinqAn.Google.Profiles
{
    /// <summary>
    ///     Encapsulates profile information used to connect to the Google Analytics API.
    /// </summary>
    public class AnalyticsProfile : IAnalyticsProfile
    {
        /// <summary>
        ///     Instantiates an <seealso cref="AnalyticsProfile" /> with the given service account email, key file, and
        ///     application name.
        /// </summary>
        /// <param name="serviceAccountEmail">The email address of the service account connected to the View.</param>
        /// <param name="keyFilePath">The path to the credential key file as a .p12 file.</param>
        /// <param name="applicationName">The name of the application requesting analytics, for reporting purposes.</param>
        public AnalyticsProfile(string serviceAccountEmail, string keyFilePath, string applicationName)
        {
            ServiceAccountEmail = serviceAccountEmail;
            KeyFilePath = keyFilePath;
            ApplicationName = applicationName;
        }

        /// <summary>
        ///     The email address of the service account connected to the View.
        /// </summary>
        public string ServiceAccountEmail { get; }

        /// <summary>
        ///     The path to the credential key file as a .p12 file.
        /// </summary>
        public string KeyFilePath { get; }

        /// <summary>
        ///     The name of the application requesting analytics, for reporting purposes.
        /// </summary>
        public string ApplicationName { get; }

        /// <summary>
        ///     Creates a <seealso cref="BaseClientService.Initializer" /> instance corresponding to this
        ///     <seealso cref="IAnalyticsProfile" />.
        /// </summary>
        /// <returns>
        ///     A <seealso cref="BaseClientService.Initializer" /> instance corresponding to this
        ///     <seealso cref="IAnalyticsProfile" />.
        /// </returns>
        public BaseClientService.Initializer ToBaseClientServiceInitializer()
        {
            var certificate = new X509Certificate2(KeyFilePath, "notasecret",
                X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
            var credential =
                new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(ServiceAccountEmail)
                    {
                        Scopes = new[] { AnalyticsService.Scope.Analytics }
                    }.FromCertificate(certificate));
            return new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName
            };
        }
    }
}


text:
// -*- mode: javascript; js-indent-offset: 2; -*-
// Copyright © 2020 Massachusetts Institute of Technology, All rights reserved.
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

'use strict';

goog.provide('Blockly.SPARQL');

goog.require('Blockly.Generator');

Blockly.SPARQL = new Blockly.Generator('SPARQL');
Blockly.SPARQL.ORDER_ATOMIC = 0;
Blockly.SPARQL.ORDER_FUNCTION_CALL = 0;
Blockly.SPARQL.ORDER_PARENS = 1;
Blockly.SPARQL.ORDER_UNARY = 2;
Blockly.SPARQL.ORDER_MULTIPLY = 3;
Blockly.SPARQL.ORDER_ADDITION = 4;
Blockly.SPARQL.ORDER_RELATIONAL = 5;
Blockly.SPARQL.ORDER_AND = 6;
Blockly.SPARQL.ORDER_OR = 7;
Blockly.SPARQL.ORDER_NONE = 99;
Blockly.SPARQL.INDENT = '';

Blockly.SPARQL.scrub_ = function(block, code) {
  var next = block.getNextBlock();
  if (next) {
    code = code + '\n' + Blockly.SPARQL.blockToCode(next);
  }
  return code;
}

Blockly.SPARQL.blockToCode1 = function(block) {
  this.yailBlocks = 0;
  return this.blockToCode(block);
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['text'] = function() {
  var text = this.getFieldValue('TEXT');
  text = text.replace(/"/, '\\"');
  text = text.replace(/\n/, '\\n');
  return ['"' + text + '"', Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['math_number'] = function() {
  return [this.getFieldValue('NUM'), Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_boolean'] = function() {
  return [this.getFieldValue('BOOL').toLowerCase(), Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_false'] = function() {
  return Blockly.SPARQL['logic_boolean'].call(this);
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_select'] = function() {
  var code = '';
  var allBlocks= this.workspace.getTopBlocks(true);
  allBlocks.forEach(function (block) {
    if (block.type === 'logic_namespace_decl') {
      code += Blockly.SPARQL.blockToCode(block);
      code += '\n';
    }
  });
  code += 'SELECT ';
  if (this.getFieldValue('DISTINCT') === 'true') {
    code += 'DISTINCT ';
  }
  code += Blockly.SPARQL.statementToCode(this, 'VARS').replace(/\r?\n/g, " ") || '*';
  code += ' WHERE {\n';
  code += Blockly.SPARQL.statementToCode(this, 'WHERE');
  code += '\n}';
  var modifiers = Blockly.SPARQL.statementToCode(this, 'MODIFIERS');
  if (modifiers) {
    code += ' ' + modifiers;
  }
  return code;
}

Blockly.SPARQL['logic_sparql_star'] = function() {
  return '*';
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_namespace_decl'] = function() {
  var code = 'PREFIX ';
  code += this.getFieldValue('PREFIX');
  code += ': ';
  code += Blockly.SPARQL.valueToCode(this, 'URI', Blockly.SPARQL.ORDER_NONE);
  code += ' ';
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_optional'] = function() {
  var code = 'OPTIONAL {\n';
  code += Blockly.SPARQL.statementToCode(this, 'CLAUSES');
  code += '}';
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_union'] = function() {
  var code = '{\n';
  var separator = '';
  for (var i = 0; i < this.itemCount_; i++) {
    code += separator;
    code += Blockly.SPARQL.statementToCode(this, this.repeatingInputName + i);
    separator = '\n} UNION {\n';
  }
  code += '\n}';
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_operator'] = function() {
  var code = '';
  code += this.getFieldValue('OPERATOR');
  code += '(';
  code += Blockly.SPARQL.valueToCode(this, 'OPERAND', Blockly.SPARQL.ORDER_NONE) || 'true';
  code += ')';
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_offset'] = function() {
  var code = 'OFFSET ';
  var offset = Blockly.SPARQL.valueToCode(this, 'VALUE', Blockly.SPARQL.ORDER_ATOMIC);
  if (offset) {
    code += offset[0];
  } else {
    code += '0';
  }
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_limit'] = function() {
  var code = 'LIMIT ';
  var limit = Blockly.SPARQL.valueToCode(this, 'VALUE', Blockly.SPARQL.ORDER_ATOMIC);
  if (limit) {
    code += limit[0];
  } else {
    code += '100';
  }
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_groupby'] = function() {
  var code = 'GROUP BY(';
  code += ')';
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_orderby'] = function() {
  var code = 'ORDER BY ' + this.getFieldValue('DIR') + ' ';
  var field = Blockly.SPARQL.valueToCode(this, 'VALUE', Blockly.SPARQL.ORDER_NONE);
  if (field) {
    code += field;
  } else {
    return '';
  }
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_sparql_uri'] = function() {
  var parent = this.getParent();
  var code = '';
  if (!parent || parent.type !== 'logic_triple_pattern') {
    return ['as']
  } else {

  }
  return [code, Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_var'] = function() {
  return '?' + this.getFieldValue('VARNAME');
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_sparql_graph'] = function() {
  var code = 'GRAPH ';
  var variable = Blockly.SPARQL.valueToCode(this, 'GRAPH', Blockly.SPARQL.ORDER_NONE);
  if (variable) {
    code += variable[0];
  } else {
    code += '<>';
  }
  code += ' {\n';
  code += Blockly.SPARQL.statementToCode(this, 'PATTERN');
  code += '\n}';
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_sparql_builtin_unary'] = function() {
  var a0 = Blockly.SPARQL.valueToCode(this, 'ARG0', Blockly.SPARQL.ORDER_NONE);
  var op = this.getFieldValue('OPERATOR');

  var code = op + "(" + a0 + ")";

  return [code, Blockly.SPARQL.ORDER_FUNCTION_CALL];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_sparql_builtin_binary'] = function() {
  var a0 = Blockly.SPARQL.valueToCode(this, 'ARG0', Blockly.SPARQL.ORDER_NONE);
  var a1 = Blockly.SPARQL.valueToCode(this, 'ARG1', Blockly.SPARQL.ORDER_NONE);
  var op = this.getFieldValue('OPERATOR');

  var code = op + "(" + a0 + "," + a1 + ")";

  return [code, Blockly.SPARQL.ORDER_FUNCTION_CALL];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_sparql_builtin_regex'] = function() {
  var code = 'REGEX(';
  code += Blockly.SPARQL.valueToCode(this, 'TEXT', Blockly.SPARQL.ORDER_FUNCTION_CALL);
  code += ', ';
  code += Blockly.SPARQL.valueToCode(this, 'REGEX', Blockly.SPARQL.ORDER_FUNCTION_CALL);
  code += ', ';
  code += Blockly.SPARQL.valueToCode(this, 'FLAGS', Blockly.SPARQL.ORDER_FUNCTION_CALL);
  code += ')';
  return [code, Blockly.SPARQL.ORDER_FUNCTION_CALL];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_operation'] = function() {
  var op = this.getFieldValue('OP') === 'AND' ? '&&' : '||';
  var identity = this.getFieldValue('OP') === 'AND' ? 'true' : 'false';
  var order = this.getFieldValue('OP') === 'AND' ?
    Blockly.SPARQL.ORDER_AND : Blockly.SPARQL.ORDER_OR;
  var arg0 = Blockly.SPARQL.valueToCode(this, 'A', order);
  var arg1 = Blockly.SPARQL.valueToCode(this, 'B', order);
  var code = '';
  if (arg0) {
    code += arg0[0];
  } else {
    code += identity;
  }
  code += ' ' + op + ' ';
  if (arg1) {
    code += arg1[0];
  } else {
    code += identity;
  }
  return code;
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_or'] = function() {
  var arg0 = Blockly.SPARQL.valueToCode(this, 'A', Blockly.SPARQL.ORDER_OR);
  var arg1 = Blockly.SPARQL.valueToCode(this, 'B', Blockly.SPARQL.ORDER_OR);
  var code = '';
  if (arg0) {
    code += arg0[0];
  } else {
    code += 'false';
  }
  code += ' || ';
  if (arg1) {
    code += arg1[0];
  } else {
    code += 'false';
  }
  return [code, Blockly.SPARQL.ORDER_OR];
}

/**
 * @this Blockly.BlockSvg
 * @returns {string}
 */
Blockly.SPARQL['logic_triple_pattern'] = function() {
  var subject = Blockly.SPARQL.valueToCode(this, 'SUBJECT', Blockly.SPARQL.ORDER_NONE) || ['<>'];
  var predicate = Blockly.SPARQL.valueToCode(this, 'PREDICATE', Blockly.SPARQL.ORDER_NONE) || ['a'];
  var object = Blockly.SPARQL.valueToCode(this, 'OBJECT', Blockly.SPARQL.ORDER_NONE) || ['<>'];
  return subject + ' ' + predicate + ' ' + object + ' .';
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_rdf_type'] = function() {
  return ['a', Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['math_compare'] = function() {
  var op = this.getFieldValue('OP') || 'EQ';
  var arg0 = Blockly.SPARQL.valueToCode(this, 'A', Blockly.SPARQL.ORDER_RELATIONAL) || '0';
  var arg1 = Blockly.SPARQL.valueToCode(this, 'B', Blockly.SPARQL.ORDER_RELATIONAL) || '0';
  return [arg0 + ' ' + Blockly.SPARQL['math_compare'].OPERATORS[op] + ' ' + arg1,
    Blockly.SPARQL.ORDER_RELATIONAL];
}

Blockly.SPARQL['math_compare'].OPERATORS = {
  'EQ': '=',
  'NEQ': '!=',
  'LT': '<',
  'LTE': '<=',
  'GT': '>',
  'GTE': '>='
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['math_add'] = function() {
  var code = '';
  var separator = '';
  for (var i = 0; i < this.itemCount_; i++) {
    code += separator;
    var arg = Blockly.SPARQL.valueToCode(this, 'NUM' + i, Blockly.SPARQL.ORDER_ADDITION) || '0';
    code += arg;
    separator = ' + ';
  }
  return [code, Blockly.SPARQL.ORDER_ADDITION];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['math_subtract'] = function() {
  var arg0 = Blockly.SPARQL.valueToCode(this, 'A', Blockly.SPARQL.ORDER_ADDITION);
  var arg1 = Blockly.SPARQL.valueToCode(this, 'B', Blockly.SPARQL.ORDER_ADDITION);
  return [arg0 + ' - ' + arg1, Blockly.SPARQL.ORDER_ADDITION];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['math_multiply'] = function() {
  var code = '';
  var separator = '';
  for (var i = 0; i < this.itemCount_; i++) {
    code += separator;
    var arg = Blockly.SPARQL.valueToCode(this, 'NUM' + i, Blockly.SPARQL.ORDER_MULTIPLY) || '1';
    code += arg;
    separator = ' * ';
  }
  return [code, Blockly.SPARQL.ORDER_MULTIPLY];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['math_divide'] = function() {
  var arg0 = Blockly.SPARQL.valueToCode(this, 'A', Blockly.SPARQL.ORDER_MULTIPLY) || '1';
  var arg1 = Blockly.SPARQL.valueToCode(this, 'B', Blockly.SPARQL.ORDER_MULTIPLY) || '1';
  return [arg0 + ' / '+ arg1, Blockly.SPARQL.ORDER_MULTIPLY];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_compare'] = function() {
  return Blockly.SPARQL['math_compare'].call(this);
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_binding'] = function() {
  return ['?' + this.getFieldValue('VARNAME'), Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_uri'] = function() {
  return ['<' + this.getFieldValue('URI') + '>', Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_qname'] = function() {
  return ['<' + this.getFieldValue('NAMESPACE') + this.getFieldValue('LOCALNAME') + '>',
     Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_qname_select'] = function() {
  return ['<' + this.getFieldValue('URI') + '>',
     Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['logic_negate'] = function() {
  var code = '!';
  var arg = Blockly.SPARQL.valueToCode(this, 'BOOL', Blockly.SPARQL.ORDER_UNARY);
  return [code + arg, Blockly.SPARQL.ORDER_UNARY];
}

/**
 * Convert component getters into SPARQL.
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['component_set_get'] = function() {
  Blockly.SPARQL.yailBlocks++;
  var code = '```yail(sparql-quote ';
  code += Blockly.Yail.blockToCode(this)[0];
  code += ')```';
  return [code, Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 * Convert component blocks to their default value.
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['component_component_block'] = function() {
  Blockly.SPARQL.yailBlocks++;
  var code = '```yail';
  code += Blockly.Yail.YAIL_GET_PROPERTY;
  code += Blockly.Yail.YAIL_QUOTE;
  code += this.getFieldValue('COMPONENT_SELECTOR');
  code += Blockly.Yail.YAIL_SPACER;
  code += Blockly.Yail.YAIL_QUOTE;
  code += 'Value';
  code += Blockly.Yail.YAIL_CLOSE_COMBINATION;
  code += '```';
  return [code, Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 * Convert method component calls into SPARQL.
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['component_method'] = function() {
  Blockly.SPARQL.yailBlocks++;
  var code = '```yail(sparql-quote ';
  code += Blockly.Yail.blockToCode(this)[0];
  code += ')```';
  return [code, Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 * Convert procedure call results into SPARQL.
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['procedures_callreturn'] = function() {
  Blockly.SPARQL.yailBlocks++;
  var code = '```yail';
  code += Blockly.Yail.blockToCode(this)[0];
  code += '```';
  return [code, Blockly.SPARQL.ORDER_ATOMIC];
}

/**
 * Convert variable getters into SPARQL.
 *
 * @this Blockly.BlockSvg
 * @returns {[string, number]}
 */
Blockly.SPARQL['lexical_variable_get'] = function() {
  Blockly.SPARQL.yailBlocks++;
  var code = '```yail';
  code += Blockly.Yail.blockToCode(this)[0];
  code += '```';
  return [code, Blockly.SPARQL.ORDER_ATOMIC];
}


text:
<?php

namespace Pvra\tests\testFiles;

use Symfony\Component\Finder\Finder;

class ExtendedFinder extends Finder
{

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Domain.Events
{
    public class AddedToCatalogEvent
    {
        public int Id { get; set; }
        public int IntId { get; set; }
        public string Name { get; set; }
    }
}


text:
namespace aura {
class WindowTreeHost;
}

// A button that is internally mapped as a status icon if the underlaying
// platform supports that kind of windows. Otherwise, calls
// OnImplInitializationFailed.
class StatusIconButtonLinux : public views::StatusIconLinux,
                              public views::Button,
                              public views::ContextMenuController,
                              public views::ButtonListener {
 public:
  StatusIconButtonLinux();
  ~StatusIconButtonLinux() override;

  // views::StatusIcon:
  void SetIcon(const gfx::ImageSkia& image) override;
  void SetToolTip(const base::string16& tool_tip) override;
  void UpdatePlatformContextMenu(ui::MenuModel* model) override;
  void OnSetDelegate() override;

  // views::ContextMenuController:
  void ShowContextMenuForViewImpl(View* source,
                                  const gfx::Point& point,
                                  ui::MenuSourceType source_type) override;

  // views::ButtonListener:
  void ButtonPressed(Button* sender, const ui::Event& event) override;

  // views::Button:
  void PaintButtonContents(gfx::Canvas* canvas) override;

 private:
  std::unique_ptr<views::Widget> widget_;

  aura::WindowTreeHost* host_ = nullptr;

  std::unique_ptr<views::MenuRunner> menu_runner_;

  DISALLOW_COPY_AND_ASSIGN(StatusIconButtonLinux);
};

#endif  // CHROME_BROWSER_UI_VIEWS_STATUS_ICONS_STATUS_ICON_BUTTON_LINUX_H_


text:
<?php

namespace Cpt\BlogBundle\Interfaces\Entity;

use Cpt\BlogBundle\Permalink\PermalinkInterface;

interface BlogInterface
{
    /**
     * @return string
     */
    public function getTitle();

    /**
     * @return string
     */
    public function getLink();

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @param string $title
     */
    public function setTitle($title);

    /**
     * @param string $link
     */
    public function setLink($link);

    /**
     * @param string $description
     */
    public function setDescription($description);

    /**
     * @return \Cpt\BlogBundle\Permalink\PermalinkInterface
     */
    public function getPermalinkGenerator();
}


text:
package name.reidmiller.timeofemissions.model.test;

import static org.junit.Assert.assertEquals;
import name.reidmiller.aesoreports.model.GeneratorType;
import name.reidmiller.iesoreports.client.GeneratorOutputCapabilityClient.FuelType;
import name.reidmiller.timeofemissions.model.CommonFuelType;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.misoenergy.ria.binding.FuelCategory;

public class CommonFuelTypeTest {
	private Logger logger = LogManager.getLogger(this.getClass());

	@Test
	public void testValueOfFuelType() {
		CommonFuelType commonFuelType = CommonFuelType
				.valueOfFuelType(FuelType.COAL);
		assertEquals("FuelType not parsed into CommonFuelType properly",
				CommonFuelType.COAL, commonFuelType);
	}

	@Test
	public void testValueOfFuelCategory() {
		CommonFuelType commonFuelType = CommonFuelType
				.valueOfFuelCategory(FuelCategory.COAL);
		assertEquals("FuelCategory not parsed into CommonFuelType properly",
				CommonFuelType.COAL, commonFuelType);
	}

	@Test
	public void testValueOfGeneratorType() {
		CommonFuelType commonFuelType = CommonFuelType
				.valueOfGeneratorType(GeneratorType.COAL);
		assertEquals("GeneratorType not parsed into CommonFuelType properly",
				CommonFuelType.COAL, commonFuelType);
	}

	@Test
	public void testGetGraphColor() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(commonFuelType + " graph color not set properly.",
				"#000000", commonFuelType.getGraphColor());
	}

	@Test
	public void testGetGramsCarbonDioxidePerKWHe() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(commonFuelType
				+ " grams CO2 per kWhe ratio not set properly.", 1001,
				commonFuelType.getGramsCarbonDioxidePerKWHe(), 0);
	}

	@Test
	public void testGetGramsCarbonDioxideForKWHeValue() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(
				commonFuelType
						+ " emissions for grams CO2 / kWhe value did not evaluate properly.",
				100100, commonFuelType.getGramsCarbonDioxideForKWHeValue(100),
				0);
	}

	@Test
	public void testGetKilogramsCarbonDioxidePerKWHe() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(commonFuelType
				+ " kg CO2 per kWhe ratio not set properly.", 1.001,
				commonFuelType.getKilogramsCarbonDioxidePerKWHe(), 0);
	}

	@Test
	public void testGetKilogramsCarbonDioxideForKWHeValue() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(
				commonFuelType
						+ " emissions for kg CO2 / kWhe value did not evaluate properly.",
				100.1,
				commonFuelType.getKilogramsCarbonDioxideForKWHeValue(100), 0);
	}

	@Test
	public void testGetKilogramsCarbonDioxidePerMWHe() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(commonFuelType
				+ " kg CO2 per MWhe ratio not set properly.", 1001,
				commonFuelType.getKilogramsCarbonDioxidePerMWHe(), 0);
	}

	@Test
	public void testGetKilogramsCarbonDioxideForMWHeValue() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(
				commonFuelType
						+ " emissions for kg CO2 / MWhe value did not evaluate properly.",
				100100,
				commonFuelType.getKilogramsCarbonDioxideForMWHeValue(100), 0);
	}

	@Test
	public void testGetMetricTonnesCarbonDioxidePerMWHe() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(commonFuelType
				+ " tonnes CO2 per MWhe ratio not set properly.", 1.001,
				commonFuelType.getMetricTonnesCarbonDioxidePerMWHe(), 0);
	}

	@Test
	public void testGetMetricTonnesCarbonDioxideForMWHeValue() {
		CommonFuelType commonFuelType = CommonFuelType.COAL;
		assertEquals(
				commonFuelType
						+ " emissions for tonnes CO2 / MWhe value did not evaluate properly.",
				100.1,
				commonFuelType.getMetricTonnesCarbonDioxideForMWHeValue(100), 0);
	}

}


text:
require "redis"

module RedisHelpers
  def redis
    @redis ||= ::Redis.new
  end

  def remove_keys(template)
    keys = redis.keys(template)
    redis.del(*keys) if keys.any?
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2005-2014 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util-3.0.xsd">

  <bean id="TransactionView" parent="Uif-FormView" p:footer.render="false">
    <property name="title" value="Student Transaction Overview"/>
    <property name="headerText" value="Transaction Overview"/>
    <property name="formClass" value="org.kuali.rice.krad.labs.transaction.TransactionForm"/>
    <property name="entryPageId" value="RollUpTransactions"/>
    <property name="items">
      <list merge="true">
        <bean parent="Uif-Page" p:id="RollUpTransactions" p:title="View Transactions">
          <property name="items">
            <list>
              <bean parent="Uif-InputField-LabelTop" p:label="Type to refresh" p:propertyName="testField"/>
              <bean parent="Uif-VerticalBoxSection" p:title="Section">
                <property name="refreshWhenChangedPropertyNames" value="testField"/>
                <property name="items">
                  <list>
                    <ref bean="rollupList"/>
                  </list>
                </property>
              </bean>

            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>

  <bean id="rollupList" parent="Uif-TableCollectionSection" p:headerText="Roll-Up"
        p:layoutManager.numberOfColumns="2" p:propertyName="rollupTransactions"
        p:collectionObjectClass="org.kuali.rice.krad.labs.transaction.TransactionModel">
    <property name="layoutManager.sequencePropertyName" value="id"/>
    <property name="layoutManager.renderSequenceField" value="false"/>
    <property name="renderAddLine" value="false"/>
    <property name="layoutManager.applyDefaultCellWidths" value="false"/>
    <property name="layoutManager.ajaxDetailsRetrieval" value="true"/>

    <property name="layoutManager.richTable.templateOptions">
      <map merge="true">
        <entry key="bPaginate" value="false"/>
        <entry key="bInfo" value="false"/>
        <entry key="bFilter" value="false"/>
      </map>
    </property>

    <property name="layoutManager.columnCalculations">
      <list>
        <bean parent="Uif-ColumnCalculationInfo-Sum" p:propertyName="chargeAmount"/>
      </list>
    </property>

    <property name="items">
      <list>
        <bean parent="Uif-InputField" p:propertyName="chargeAmount" p:label="Charges" p:labelPlacement="TOP"/>
      </list>
    </property>

    <property name="layoutManager.expandDetailsActionPrototype">
      <bean parent="Uif-ExpandDetailsImageAction"/>
    </property>

    <property name="layoutManager.rowDetailsGroup">
      <bean parent="Uif-VerticalBoxGroup">
        <property name="items">
          <list>
            <bean parent="Uif-InputField" p:propertyName="chargeAmount" p:label="Charges"/>
            <ref bean="rollupTransactionList"/>
          </list>
        </property>
      </bean>
    </property>
  </bean>

  <bean id="rollupTransactionList" parent="Uif-TableSubCollection-WithinSection" p:layoutManager.numberOfColumns="2">
    <property name="headerText" value="Transactions"/>
    <property name="collectionObjectClass" value="org.kuali.rice.krad.labs.transaction.TransactionModel"/>
    <property name="propertyName" value="subTransactions"/>
    <property name="layoutManager.sequencePropertyName" value="id"/>
    <property name="layoutManager.richTable.render" value="true"/>
    <property name="layoutManager.renderSequenceField" value="false"/>
    <property name="refreshWhenChangedPropertyNames" value="#lp.chargeAmount"/>
    <property name="renderAddLine" value="false"/>
    <property name="style" value="width: 100%;"/>
    <property name="layoutManager.richTable.templateOptions">
      <map merge="true">
        <entry key="bPaginate" value="false"/>
        <entry key="bInfo" value="false"/>
        <entry key="bFilter" value="false"/>
      </map>
    </property>
    <property name="items">
      <list>
        <bean parent="Uif-HorizontalFieldGroup" p:label="Description" p:style="width: 40%;">
          <property name="items">
            <list>
              <bean parent="Uif-LinkField" p:href="javascript:void(0)"
                    p:onClickScript="showLightboxComponent('transactionDetailLightbox@{#lineSuffix}');"
                    p:linkText="Transaction Detail"/>

              <bean id="transactionDetailLightbox" parent="Uif-VerticalBoxSection">
                <property name="retrieveViaAjax" value="true"/>
                <property name="items">
                  <list>
                    <ref bean="transactionDetail"/>
                  </list>
                </property>
              </bean>
            </list>
          </property>
        </bean>

        <bean parent="Uif-InputField" p:propertyName="chargeAmount" p:label="Charges">
          <property name="suggest">
            <bean parent="Uif-Suggest" p:render="true" p:retrieveAllSuggestions="true">
              <property name="suggestOptions">
                <list>
                  <value>TypeA</value>
                  <value>TypeB</value>
                </list>
              </property>
              <property name="templateOptions">
                <map>
                  <entry key="minLength" value="0"/>
                  <entry key="delay" value="0"/>
                </map>
              </property>
            </bean>
          </property>
        </bean>
      </list>
    </property>
  </bean>

  <bean id="transactionDetail" parent="Uif-VerticalBoxSection" p:headerText="Transaction Details">
    <property name="items">
      <list>
        <ref bean="transactionDetailFields"/>
      </list>
    </property>
  </bean>

  <bean id="transactionDetailFields" parent="Uif-HorizontalBoxGroup">
    <property name="items">
      <list>
        <bean parent="Uif-GridSection" p:style="width: 40%;">
          <property name="items">
            <list>
              <bean parent="Uif-InputField" p:propertyName="transactionDisplayType" p:label="Transaction Type">
                <property name="control">
                  <bean parent="Uif-TextAreaControl" p:rows="5" p:cols="40"
                        p:style="resize:none;"/>
                </property>
              </bean>
            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>

</beans>


text:
Sheets is a way to manage stylesheets and scripts from your existing page tree. With Sheets, you'll create new types of pages: JavascriptPage and StylesheetPage.

Pages of these types are Sheets.

## Features

The basic features:

* provide a separate interface for editing CSS and Javascript content
* set a longer expire time for Sheet content with `sheet_cache_timeout` (similar to the typical `cache_timeout` set for pages)
* hide the JavascriptPage and StylesheetPage nodes from the standard Page index view
* provide Radius tags to output content as it is, as a link to content, and as an HTML element containing the content
* append a timestamp to sheet content URLs so that the cache need not be cleared with the same frequency for updates to typical pages

## Differences with other solutions and the benefit of using Sheets

Some standard site templates provided by Radiant include stylesheet content in a typical page. This requires a custom layout merely to set the content type, and displays content unintended for editing by typical users. This makes for a cluttered page index view and cluttered layout index view.

A popular solution to these problems is the [SNS extension](http://ext.radiantcms.org/extensions/53-sns). SNS separates the editing interfaces for these types of content, but the problem is that it makes too much of a separation. With SNS, stylesheet and javascript content is stored in a separate table and is generated by models completely unrelated to the Page model. This means that other extensions are *required* to do extra work to provide features and Radius tags to SNS content, and as a result many extensions do not do this work. This situation makes for a confusing introduction to Radiant for new users and developers alike.

You can get around this SNS limitation by using the [SNS Page Hook extension](http://ext.radiantcms.org/extensions/232-sns-page-hook) but even this solution will lead to unpredictable results because it merely copies modules from the Page model to the TextAsset model and tricks the included methods into believing they are operating on a Page. But this is not a good long-term solution.

Sheets keeps this content in the same location as all other content: Pages. Doing it this way allows any chosen URL or Page slug to be protected properly with newly created pages. Even more importantly, this allows user and developer expectations about the behavior of Radius tags to make sense. With Sheets, extensions which add Radius tags to the Page model add them to stylesheets and javascripts too; there is no extra work to be done.

Not only does it do all this, but the standard Page model provides a `headers` method which Sheets overrides to alter the mime-type for the returned content. Sheets uses the built-in ways to serve content, rather than generating yet another way to serve content like SNS.

## Thanks

Special thanks goes to Chris Parrish for creating the SNS extension in the first place. And thanks to Dane Harrigan for some early bug checking.

Built by [Saturn Flyer](http://www.saturnflyer.com)


text:
/* @test
 * @summary Unit test for socket-channel adaptors
 * @library ..
 */

import java.io.*;
import java.net.*;
import java.nio.channels.*;

public class AdaptSocket {

    static java.io.PrintStream out = System.out;

    static void test(TestServers.DayTimeServer dayTimeServer,
                     int timeout,
                     boolean shouldTimeout)
        throws Exception
    {
        out.println();

        InetSocketAddress isa
            = new InetSocketAddress(dayTimeServer.getAddress(),
                                    dayTimeServer.getPort());
        SocketChannel sc = SocketChannel.open();
        Socket so = sc.socket();
        out.println("opened: " + so);
        out.println("        " + sc);

        //out.println("opts:   " + sc.options());
        so.setTcpNoDelay(true);
        //so.setTrafficClass(SocketOpts.IP.TOS_THROUGHPUT);
        so.setKeepAlive(true);
        so.setSoLinger(true, 42);
        so.setOOBInline(true);
        so.setReceiveBufferSize(512);
        so.setSendBufferSize(512);
        //out.println("        " + sc.options());

        if (timeout == 0)
            so.connect(isa);
        else {
            try {
                so.connect(isa, timeout);
            } catch (SocketTimeoutException x) {
                if (shouldTimeout) {
                    out.println("Connection timed out, as expected");
                    return;
                } else {
                    throw x;
                }
            }
        }
        out.println("connected: " + so);
        out.println("           " + sc);
        byte[] bb = new byte[100];
        int n = so.getInputStream().read(bb);
        String s = new String(bb, 0, n - 2, "US-ASCII");
        out.println(isa + " says: \"" + s + "\"");
        so.shutdownInput();
        out.println("ishut: " + sc);
        so.shutdownOutput();
        out.println("oshut: " + sc);
        so.close();
        out.println("closed: " + so);
        out.println("        " + sc);
    }

    static String dataString = "foo\r\n";

    static void testRead(Socket so, boolean shouldTimeout)
        throws Exception
    {
        String data = "foo\r\n";
        so.getOutputStream().write(dataString.getBytes("US-ASCII"));
        InputStream is = so.getInputStream();
        try {
            byte[] b = new byte[100];
            int n = is.read(b);
            if (n != 5)
                throw new Exception("Incorrect number of bytes read: " + n);
            if (!dataString.equals(new String(b, 0, n, "US-ASCII")))
                throw new Exception("Incorrect data read: " + n);
        } catch (SocketTimeoutException x) {
            if (shouldTimeout) {
                out.println("Read timed out, as expected");
                return;
            }
            throw x;
        }
    }

    static void testRead(TestServers.EchoServer echoServer,
                         int timeout,
                         boolean shouldTimeout)
        throws Exception
    {
        out.println();

        InetSocketAddress isa
            = new InetSocketAddress(echoServer.getAddress(),
                                    echoServer.getPort());
        SocketChannel sc = SocketChannel.open();
        sc.connect(isa);
        Socket so = sc.socket();
        out.println("connected: " + so);
        out.println("           " + sc);

        if (timeout > 0)
            so.setSoTimeout(timeout);
        out.println("timeout: " + so.getSoTimeout());

        testRead(so, shouldTimeout);
        for (int i = 0; i < 4; i++) {
            testRead(so, shouldTimeout);
        }

        sc.close();
    }

    public static void main(String[] args) throws Exception {

        try (TestServers.DayTimeServer dayTimeServer
                = TestServers.DayTimeServer.startNewServer()) {
            test(dayTimeServer, 0, false);
            test(dayTimeServer, 1000, false);
        }

        try (TestServers.DayTimeServer lingerDayTimeServer
                = TestServers.DayTimeServer.startNewServer(100)) {
            // this test no longer really test the connection timeout
            // since there is no way to prevent the server from eagerly
            // accepting connection...
            test(lingerDayTimeServer, 10, true);
        }

        try (TestServers.EchoServer echoServer
                = TestServers.EchoServer.startNewServer()) {
            testRead(echoServer, 0, false);
            testRead(echoServer, 8000, false);
        }

        try (TestServers.EchoServer lingerEchoServer
                = TestServers.EchoServer.startNewServer(100)) {
            testRead(lingerEchoServer, 10, true);
        }
    }
}


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

<title>org.opencv.video</title>
<meta name="date" content="2017-10-24">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.opencv.video

Classes

BackgroundSubtractor

BackgroundSubtractorKNN

BackgroundSubtractorMOG2

DenseOpticalFlow

DualTVL1OpticalFlow

FarnebackOpticalFlow

KalmanFilter

SparseOpticalFlow

SparsePyrLKOpticalFlow

Video


text:
package antlr.debug;

public class NewLineEvent extends Event {
	private int line;

	public NewLineEvent(Object source) {
		super(source);
	}
	public NewLineEvent(Object source, int line) {
		super(source);
		setValues(line);
	}
	public int getLine() {
		return line;
	}
	void setLine(int line) {
		this.line = line;
	}
	/** This should NOT be called from anyone other than ParserEventSupport! */
	void setValues(int line) {
		setLine(line);
	}
	public String toString() {
		return "NewLineEvent [" + line + "]";
	}
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GoogleQuestions;

namespace GoogleQuestionTest
{
    [TestClass]
    public class GoogleQuestionTest
    {
        [TestMethod]
        public void Test_001_SortString()
        {
            _001_SortString target = new _001_SortString();
            string s1 = "house";
            string s2 = "soup";
            char[] actual;
            actual = target.SortStringBaseOnString(s1, s2);
            Assert.AreEqual('s', actual[0]);
            Assert.AreEqual('o', actual[1]);
            Assert.AreEqual('u', actual[2]);
        }

        [TestMethod]
        public void Test_002_QualityDivide()
        {
            _002_QualityDivide target = new _002_QualityDivide();
            char[] input = { '1', '2', '3', '3', '2', '3' };
            string actual = target.FindBestDivdor(input);
        }

        [TestMethod]
        public void Test_003_MixArray()
        {
            _003_MixArray target = new _003_MixArray();
            int[] input = {1,3,5,7,9,11,2,4,6,8,10,12};
            target.MixArray(input);
            for (int i = 1; i < input.Length; i++)
            {
                Assert.AreEqual(1, input[i] - input[i - 1]);
            }
        }
        [TestMethod]
        public void Test_005_2DWater()
        {
            _005_2DWater target = new _005_2DWater();
            point[,] input = { {new point(){Height = 3}, new point(){Height = 3}, new point(){Height = 3}, new point(){Height = 3}},
                                 {new point(){Height = 3}, new point(){Height = 0}, new point(){Height = 0}, new point(){Height = 3}},
                                 {new point(){Height = 3}, new point(){Height = 1}, new point(){Height = 3}, new point(){Height = 3}},
                                 {new point(){Height = 3}, new point(){Height = 1}, new point(){Height = 3}, new point(){Height = 3}}};

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    input[i, j].i = i;
                    input[i, j].j = j;
                }
            }

            int actual = target.FindCapacity(input, 4);
        }

        [TestMethod]
        public void Test_006_PartitionArray()
        {
            PartitionArray target = new PartitionArray();
            int[] input = { 1, 4, 9, 16 };
            int actual = target.EquallyPartitionArray(input);
            Assert.AreEqual(4, actual);

            int[] input2 = { 1, 4, 7, 16 };
            actual = target.EquallyPartitionArray(input2);
            Assert.AreEqual(6, actual);

            int[] input3 = { 1, 4, 6, 7, 8, 16 };
            actual = target.EquallyPartitionArray(input3);
            Assert.AreEqual(0, actual);
        }
    }
}


text:
package org.apache.flink.graph;

import org.apache.flink.api.common.functions.Function;
import org.apache.flink.api.java.DataSet;

import java.io.Serializable;

/**
 * Interface to be implemented by the transformation function applied in {@link
 * Graph#joinWithEdges(DataSet, EdgeJoinFunction)}, {@link Graph#joinWithEdgesOnSource(DataSet,
 * EdgeJoinFunction)}, and {@link Graph#joinWithEdgesOnTarget(DataSet, EdgeJoinFunction)} methods.
 *
 * @param <EV> the edge value type
 * @param <T> the input value type
 */
public interface EdgeJoinFunction<EV, T> extends Function, Serializable {

    /**
     * Applies a transformation on the current edge value and the value of the matched tuple of the
     * input DataSet.
     *
     * @param edgeValue the current edge value
     * @param inputValue the value of the matched Tuple2 input
     * @return the new edge value
     */
    EV edgeJoin(EV edgeValue, T inputValue) throws Exception;
}


text:
package rpc

import (
	"io"
	"net/rpc"
	"net/rpc/jsonrpc"

	"github.com/weaveworks/flux"
	"github.com/weaveworks/flux/job"
	"github.com/weaveworks/flux/remote"
	"github.com/weaveworks/flux/update"
)

// Server takes a platform and makes it available over RPC.
type Server struct {
	server *rpc.Server
}

// NewServer instantiates a new RPC server, handling requests on the
// conn by invoking methods on the underlying (assumed local)
// platform.
func NewServer(p remote.Platform) (*Server, error) {
	server := rpc.NewServer()
	if err := server.Register(&RPCServer{p}); err != nil {
		return nil, err
	}
	return &Server{server: server}, nil
}

func (c *Server) ServeConn(conn io.ReadWriteCloser) {
	c.server.ServeCodec(jsonrpc.NewServerCodec(conn))
}

type RPCServer struct {
	p remote.Platform
}

func (p *RPCServer) Ping(_ struct{}, _ *struct{}) error {
	return p.p.Ping()
}

func (p *RPCServer) Version(_ struct{}, resp *string) error {
	v, err := p.p.Version()
	*resp = v
	return err
}

func (p *RPCServer) Export(_ struct{}, resp *[]byte) error {
	v, err := p.p.Export()
	*resp = v
	return err
}

func (p *RPCServer) ListServices(namespace string, resp *[]flux.ServiceStatus) error {
	v, err := p.p.ListServices(namespace)
	*resp = v
	return err
}

func (p *RPCServer) ListImages(spec update.ServiceSpec, resp *[]flux.ImageStatus) error {
	v, err := p.p.ListImages(spec)
	*resp = v
	return err
}

func (p *RPCServer) UpdateManifests(spec update.Spec, resp *job.ID) error {
	v, err := p.p.UpdateManifests(spec)
	*resp = v
	return err
}

func (p *RPCServer) SyncNotify(_ struct{}, _ *struct{}) error {
	return p.p.SyncNotify()
}

func (p *RPCServer) JobStatus(jobID job.ID, resp *job.Status) error {
	v, err := p.p.JobStatus(jobID)
	*resp = v
	return err
}

func (p *RPCServer) SyncStatus(cursor string, resp *[]string) error {
	v, err := p.p.SyncStatus(cursor)
	*resp = v
	return err
}

func (p *RPCServer) GitRepoConfig(regenerate bool, resp *flux.GitConfig) error {
	v, err := p.p.GitRepoConfig(regenerate)
	*resp = v
	return err
}


text:
package nl.jansipke.pvdisplay.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import nl.jansipke.pvdisplay.PvDataService;
import nl.jansipke.pvdisplay.R;
import nl.jansipke.pvdisplay.data.RecordPvDatum;
import nl.jansipke.pvdisplay.data.StatisticPvDatum;
import nl.jansipke.pvdisplay.data.SystemPvDatum;
import nl.jansipke.pvdisplay.database.PvDataOperations;
import nl.jansipke.pvdisplay.utils.DateTimeUtils;
import nl.jansipke.pvdisplay.utils.FormatUtils;

public class SystemFragment extends Fragment {

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

    private View fragmentView;
    private PvDataOperations pvDataOperations;

    private void callPvDataService() {
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
                if (intent.getBooleanExtra("success", true)) {
                    updateScreen();
                } else {
                    Toast.makeText(context, intent.getStringExtra("message"),
                            Toast.LENGTH_LONG).show();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter(PvDataService.class.getName());
        LocalBroadcastManager.getInstance(getContext())
                .registerReceiver(broadcastReceiver, intentFilter);

        PvDataService.callStatistic(getContext());
        PvDataService.callSystem(getContext());
    }

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

        setHasOptionsMenu(true);

        pvDataOperations = new PvDataOperations(getContext());
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_system, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater,
                             @Nullable final ViewGroup container,
                             @Nullable final Bundle savedInstanceState) {

        fragmentView = inflater.inflate(R.layout.fragment_system, container, false);
        updateScreen();
        return fragmentView;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_refresh:
                Log.d(TAG, "Clicked refresh");
                callPvDataService();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void updateScreen() {
        Log.d(TAG, "Updating screen with statistic and system PV data");

        StatisticPvDatum statisticPvDatum = pvDataOperations.loadStatistic();
        final SystemPvDatum systemPvDatum = pvDataOperations.loadSystem();
        if (statisticPvDatum == null || systemPvDatum == null) {
            Log.d(TAG, "No statistic or system PV data");
            callPvDataService();
            return;
        }

        if (isAdded() && getActivity() != null) {
            TextView nameTextView = (TextView) fragmentView.findViewById(R.id.system);
            nameTextView.setText(systemPvDatum.getSystemName());
            nameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Uri uri = Uri.parse("geo:" +
                            systemPvDatum.getLatitude() + "," +
                            systemPvDatum.getLongitude() + "?z=14");
                    Log.d(TAG, "Opening Google Maps for URI: " + uri);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    intent.setPackage("com.google.android.apps.maps");
                    startActivity(intent);
                }
            });

            TextView panelsTextView = (TextView) fragmentView.findViewById(R.id.panels);
            panelsTextView.setText(
                    systemPvDatum.getPanelBrand() + "\n" +
                            getResources().getString(R.string.value_panels,
                                    systemPvDatum.getNumberOfPanels(),
                                    systemPvDatum.getPanelPower(),
                                    systemPvDatum.getSystemSize()));
            panelsTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String uri = "http://www.google.com/#q=" + systemPvDatum.getPanelBrand();
                    intent.setData(Uri.parse(uri));
                    startActivity(intent);
                }
            });

            TextView inverterTextView = (TextView) fragmentView.findViewById(R.id.inverter);
            inverterTextView.setText(
                    systemPvDatum.getInverterBrand() + "\n" +
                            getResources().getString(R.string.value_inverter,
                                    systemPvDatum.getInverterPower()));
            inverterTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String uri = "http://www.google.com/#q=" + systemPvDatum.getInverterBrand();
                    intent.setData(Uri.parse(uri));
                    startActivity(intent);
                }
            });

            TextView statisticsTextView = (TextView) fragmentView.findViewById(R.id.statistics);
            statisticsTextView.setText(
                    getResources().getString(R.string.value_statistics_total,
                            FormatUtils.ENERGY_FORMAT.format(
                                    statisticPvDatum.getEnergyGenerated() / 1000),
                            statisticPvDatum.getOutputs()) + "\n" +
                            getResources().getString(R.string.value_statistics_average,
                                    FormatUtils.ENERGY_FORMAT.format(
                                            statisticPvDatum.getAverageGeneration() / 1000)) + "\n" +
                            getResources().getString(R.string.value_statistics_record,
                                    FormatUtils.ENERGY_FORMAT.format(
                                            statisticPvDatum.getMaximumGeneration() / 1000),
                                    DateTimeUtils.formatYearMonthDay(
                                            statisticPvDatum.getRecordDateYear(),
                                            statisticPvDatum.getRecordDateMonth(),
                                            statisticPvDatum.getRecordDateDay(), true)) + "\n");
            statisticsTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Context context = getContext();
                    if (context != null) {
                        PvDataOperations pvDataOperations = new PvDataOperations(context);
                        RecordPvDatum recordPvDatum = pvDataOperations.loadRecord();
                        String text =
                                "Live power: " + getResources().getString(R.string.value_w,
                                        FormatUtils.POWER_FORMAT.format(
                                                recordPvDatum.getLivePowerGeneration())) +
                                "\nDaily energy: " + getResources().getString(R.string.value_kwh,
                                        FormatUtils.ENERGY_FORMAT.format(
                                                recordPvDatum.getDailyEnergyGenerated() / 1000)) +
                                "\nMonthly energy: " + getResources().getString(R.string.value_kwh,
                                        FormatUtils.ENERGY_FORMAT.format(
                                                recordPvDatum.getMonthlyEnergyGenerated() / 1000)) +
                                "\nYearly energy: " + getResources().getString(R.string.value_kwh,
                                        FormatUtils.ENERGY_FORMAT.format(
                                                recordPvDatum.getYearlyEnergyGenerated() / 1000));

                        Toast.makeText(context, text,
                                Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    }
}


text:
"""
A simple vtkTkRenderWidget for Tkinter.

Created by David Gobbi, April 1999

May ??, 1999  - Modifications peformed by Heather Drury,
                to rewrite _pan to match method in TkInteractor.tcl
May 11, 1999  - Major rewrite by David Gobbi to make the
                interactor bindings identical to the TkInteractor.tcl
                bindings.
July 14, 1999 - Added modification by Ken Martin for VTK 2.4, to
                use vtk widgets instead of Togl.
Aug 29, 1999  - Renamed file to vtkRenderWidget.py
Nov 14, 1999  - Added support for keyword 'rw'
Mar 23, 2000  - Extensive but backwards compatible changes,
                improved documentation
"""

"""
A few important notes:

This class is meant to be used as a base-class widget for
doing VTK rendering in Python.

In VTK (and C++) there is a very important distinction between
public ivars (attributes in pythonspeak), protected ivars, and
private ivars.  When you write a python class that you want
to 'look and feel' like a VTK class, you should follow these rules.

1) Attributes should never be public.  Attributes should always be
   either protected (prefixed with a single underscore) or private
   (prefixed with a double underscore).  You can provide access to
   attributes through public Set/Get methods (same as VTK).

2) Use a single underscore to denote a protected attribute, e.g.
   self._RenderWindow is protected (can be accessed from this
   class or a derived class).

3) Use a double underscore to denote a private attribute, e.g.
   self.__InExpose cannot be accessed outside of this class.

All attributes should be 'declared' in the __init__() function
i.e. set to some initial value.  Don't forget that 'None' means
'NULL' - the python/vtk wrappers guarantee their equivalence.
"""

import Tkinter
import math, os, sys
import vtk

from vtkLoadPythonTkWidgets import vtkLoadPythonTkWidgets

class vtkTkRenderWidget(Tkinter.Widget):
    """
    A vtkTkRenderWidget for Python.

    Use GetRenderWindow() to get the vtkRenderWindow.

    Create with the keyword stereo=1 in order to generate a
    stereo-capable window.

    Create with the keyword focus_on_enter=1 to enable
    focus-follows-mouse.  The default is for a click-to-focus mode.
    """
    def __init__(self, master, cnf={}, **kw):
        """
        Constructor.

        Keyword arguments:

          rw -- Use passed render window instead of creating a new one.

          stereo -- If True, generate a stereo-capable window.
          Defaults to False.

          focus_on_enter -- If True, use a focus-follows-mouse mode.
          Defaults to False where the widget will use a click-to-focus
          mode.
        """
        # load the necessary extensions into tk
        vtkLoadPythonTkWidgets(master.tk)

        try: # check to see if a render window was specified
            renderWindow = kw['rw']
        except KeyError:
            renderWindow = vtk.vtkRenderWindow()

        try:  # was a stereo rendering context requested?
            if kw['stereo']:
	       renderWindow.StereoCapableWindowOn()
               del kw['stereo']
	except KeyError:
            pass

        # check if focus should follow mouse
        if kw.get('focus_on_enter'):
            self._FocusOnEnter = 1
            del kw['focus_on_enter']
        else:
            self._FocusOnEnter = 0

        kw['rw'] = renderWindow.GetAddressAsString("vtkRenderWindow")
        Tkinter.Widget.__init__(self, master, 'vtkTkRenderWidget', cnf, kw)

        self._CurrentRenderer = None
        self._CurrentCamera = None
        self._CurrentZoom = 1.0
        self._CurrentLight = None

        self._ViewportCenterX = 0
        self._ViewportCenterY = 0

        self._Picker = vtk.vtkCellPicker()
        self._PickedAssembly = None
        self._PickedProperty = vtk.vtkProperty()
        self._PickedProperty.SetColor(1,0,0)
        self._PrePickedProperty = None

        self._OldFocus = None

        # used by the LOD actors
        self._DesiredUpdateRate = 15
        self._StillUpdateRate = 0.0001

        # these record the previous mouse position
        self._LastX = 0
        self._LastY = 0

        # private attributes
        self.__InExpose = 0

        # create the Tk bindings
        self.BindTkRenderWidget()

    def __getattr__(self,attr):
        # because the tk part of vtkTkRenderWidget must have
        # the only remaining reference to the RenderWindow when
        # it is destroyed, we can't actually store the RenderWindow
        # as an attribute but instead have to get it from the tk-side
        if attr == '_RenderWindow':
            return self.GetRenderWindow()
        raise AttributeError, self.__class__.__name__ + \
              " has no attribute named " + attr

    def BindTkRenderWidget(self):
        """
        Bind some default actions.
        """
        self.bind("<ButtonPress>",
                  lambda e,s=self: s.StartMotion(e.x,e.y))
        self.bind("<ButtonRelease>",
                  lambda e,s=self: s.EndMotion(e.x,e.y))
        self.bind("<B1-Motion>",
                  lambda e,s=self: s.Rotate(e.x,e.y))
        self.bind("<B2-Motion>",
                  lambda e,s=self: s.Pan(e.x,e.y))
        self.bind("<B3-Motion>",
                  lambda e,s=self: s.Zoom(e.x,e.y))
        self.bind("<Shift-B1-Motion>",
                  lambda e,s=self: s.Pan(e.x,e.y))
        self.bind("<KeyPress-r>",
                  lambda e,s=self: s.Reset(e.x,e.y))
        self.bind("<KeyPress-u>",
                  lambda e,s=self: s.deiconify())
        self.bind("<KeyPress-w>",
                  lambda e,s=self: s.Wireframe())
        self.bind("<KeyPress-s>",
                  lambda e,s=self: s.Surface())
        self.bind("<KeyPress-p>",
                  lambda e,s=self: s.PickActor(e.x,e.y))
        if self._FocusOnEnter:
            self.bind("<Enter>",
                      lambda e,s=self: s.Enter(e.x,e.y))
            self.bind("<Leave>",
                      lambda e,s=self: s.Leave(e.x,e.y))
        else:
            self.bind("<ButtonPress>",
                      lambda e,s=self: s.Enter(e.x,e.y))
        self.bind("<Expose>",
                  lambda e,s=self: s.Expose())

    def GetZoomFactor(self):
        return self._CurrentZoom

    def SetDesiredUpdateRate(self, rate):
        """Mirrors the method with the same name in
        vtkRenderWindowInteractor."""
        self._DesiredUpdateRate = rate

    def GetDesiredUpdateRate(self):
        """Mirrors the method with the same name in
        vtkRenderWindowInteractor."""
        return self._DesiredUpdateRate

    def SetStillUpdateRate(self, rate):
        """Mirrors the method with the same name in
        vtkRenderWindowInteractor."""
        self._StillUpdateRate = rate

    def GetStillUpdateRate(self):
        """Mirrors the method with the same name in
        vtkRenderWindowInteractor."""
        return self._StillUpdateRate

    def GetRenderWindow(self):
        addr = self.tk.call(self._w, 'GetRenderWindow')[5:]
        return vtk.vtkRenderWindow('_%s_vtkRenderWindow_p' % addr)

    def GetPicker(self):
        return self._Picker

    def Expose(self):
        if (not self.__InExpose):
            self.__InExpose = 1
            if (not self._RenderWindow.IsA('vtkCocoaRenderWindow')):
                self.update()
            self._RenderWindow.Render()
            self.__InExpose = 0

    def Render(self):
        if (self._CurrentLight):
            light = self._CurrentLight
            light.SetPosition(self._CurrentCamera.GetPosition())
            light.SetFocalPoint(self._CurrentCamera.GetFocalPoint())

        self._RenderWindow.Render()

    def UpdateRenderer(self,x,y):
        """
        UpdateRenderer will identify the renderer under the mouse and set
        up _CurrentRenderer, _CurrentCamera, and _CurrentLight.
        """
        windowX = self.winfo_width()
        windowY = self.winfo_height()

        renderers = self._RenderWindow.GetRenderers()
        numRenderers = renderers.GetNumberOfItems()

        self._CurrentRenderer = None
        renderers.InitTraversal()
        for i in range(0,numRenderers):
            renderer = renderers.GetNextItem()
            vx,vy = (0,0)
            if (windowX > 1):
                vx = float(x)/(windowX-1)
            if (windowY > 1):
                vy = (windowY-float(y)-1)/(windowY-1)
            (vpxmin,vpymin,vpxmax,vpymax) = renderer.GetViewport()

            if (vx >= vpxmin and vx <= vpxmax and
                vy >= vpymin and vy <= vpymax):
                self._CurrentRenderer = renderer
                self._ViewportCenterX = float(windowX)*(vpxmax-vpxmin)/2.0\
                                        +vpxmin
                self._ViewportCenterY = float(windowY)*(vpymax-vpymin)/2.0\
                                        +vpymin
                self._CurrentCamera = self._CurrentRenderer.GetActiveCamera()
                lights = self._CurrentRenderer.GetLights()
                lights.InitTraversal()
                self._CurrentLight = lights.GetNextItem()
                break

        self._LastX = x
        self._LastY = y

    def GetCurrentRenderer(self):
        return self._CurrentRenderer

    def Enter(self,x,y):
        self._OldFocus=self.focus_get()
        self.focus()
        self.StartMotion(x, y)

    def Leave(self,x,y):
        if (self._OldFocus != None):
            self._OldFocus.focus()

    def StartMotion(self,x,y):
        self.GetRenderWindow().SetDesiredUpdateRate(self._DesiredUpdateRate)
        self.UpdateRenderer(x,y)

    def EndMotion(self,x,y):
        self.GetRenderWindow().SetDesiredUpdateRate(self._StillUpdateRate)
        if self._CurrentRenderer:
            self.Render()

    def Rotate(self,x,y):
        if self._CurrentRenderer:

            self._CurrentCamera.Azimuth(self._LastX - x)
            self._CurrentCamera.Elevation(y - self._LastY)
            self._CurrentCamera.OrthogonalizeViewUp()

            self._LastX = x
            self._LastY = y

            self._CurrentRenderer.ResetCameraClippingRange()
            self.Render()

    def Pan(self,x,y):
        if self._CurrentRenderer:

            renderer = self._CurrentRenderer
            camera = self._CurrentCamera
            (pPoint0,pPoint1,pPoint2) = camera.GetPosition()
            (fPoint0,fPoint1,fPoint2) = camera.GetFocalPoint()

            if (camera.GetParallelProjection()):
                renderer.SetWorldPoint(fPoint0,fPoint1,fPoint2,1.0)
                renderer.WorldToDisplay()
                fx,fy,fz = renderer.GetDisplayPoint()
                renderer.SetDisplayPoint(fx-x+self._LastX,
                                         fy+y-self._LastY,
                                         fz)
                renderer.DisplayToWorld()
                fx,fy,fz,fw = renderer.GetWorldPoint()
                camera.SetFocalPoint(fx,fy,fz)

                renderer.SetWorldPoint(pPoint0,pPoint1,pPoint2,1.0)
                renderer.WorldToDisplay()
                fx,fy,fz = renderer.GetDisplayPoint()
                renderer.SetDisplayPoint(fx-x+self._LastX,
                                         fy+y-self._LastY,
                                         fz)
                renderer.DisplayToWorld()
                fx,fy,fz,fw = renderer.GetWorldPoint()
                camera.SetPosition(fx,fy,fz)

            else:
                (fPoint0,fPoint1,fPoint2) = camera.GetFocalPoint()
                # Specify a point location in world coordinates
                renderer.SetWorldPoint(fPoint0,fPoint1,fPoint2,1.0)
                renderer.WorldToDisplay()
                # Convert world point coordinates to display coordinates
                dPoint = renderer.GetDisplayPoint()
                focalDepth = dPoint[2]

                aPoint0 = self._ViewportCenterX + (x - self._LastX)
                aPoint1 = self._ViewportCenterY - (y - self._LastY)

                renderer.SetDisplayPoint(aPoint0,aPoint1,focalDepth)
                renderer.DisplayToWorld()

                (rPoint0,rPoint1,rPoint2,rPoint3) = renderer.GetWorldPoint()
                if (rPoint3 != 0.0):
                    rPoint0 = rPoint0/rPoint3
                    rPoint1 = rPoint1/rPoint3
                    rPoint2 = rPoint2/rPoint3

                camera.SetFocalPoint((fPoint0 - rPoint0) + fPoint0,
                                     (fPoint1 - rPoint1) + fPoint1,
                                     (fPoint2 - rPoint2) + fPoint2)

                camera.SetPosition((fPoint0 - rPoint0) + pPoint0,
                                   (fPoint1 - rPoint1) + pPoint1,
                                   (fPoint2 - rPoint2) + pPoint2)

            self._LastX = x
            self._LastY = y

            self.Render()

    def Zoom(self,x,y):
        if self._CurrentRenderer:

            renderer = self._CurrentRenderer
            camera = self._CurrentCamera

            zoomFactor = math.pow(1.02,(0.5*(self._LastY - y)))
            self._CurrentZoom = self._CurrentZoom * zoomFactor

            if camera.GetParallelProjection():
                parallelScale = camera.GetParallelScale()/zoomFactor
                camera.SetParallelScale(parallelScale)
            else:
                camera.Dolly(zoomFactor)
                renderer.ResetCameraClippingRange()

            self._LastX = x
            self._LastY = y

            self.Render()

    def Reset(self,x,y):
        if self._CurrentRenderer:
            self._CurrentRenderer.ResetCamera()

        self.Render()

    def Wireframe(self):
        actors = self._CurrentRenderer.GetActors()
        numActors = actors.GetNumberOfItems()
        actors.InitTraversal()
        for i in range(0,numActors):
            actor = actors.GetNextItem()
            actor.GetProperty().SetRepresentationToWireframe()

        self.Render()

    def Surface(self):
        actors = self._CurrentRenderer.GetActors()
        numActors = actors.GetNumberOfItems()
        actors.InitTraversal()
        for i in range(0,numActors):
            actor = actors.GetNextItem()
            actor.GetProperty().SetRepresentationToSurface()

        self.Render()

    def PickActor(self,x,y):
        if self._CurrentRenderer:

            renderer = self._CurrentRenderer
            picker = self._Picker

            windowY = self.winfo_height()
            picker.Pick(x,(windowY - y - 1),0.0,renderer)
            assembly = picker.GetAssembly()

            if (self._PickedAssembly != None and
                self._PrePickedProperty != None):
                self._PickedAssembly.SetProperty(self._PrePickedProperty)
                # release hold of the property
                self._PrePickedProperty.UnRegister(self._PrePickedProperty)
                self._PrePickedProperty = None

            if (assembly != None):
                self._PickedAssembly = assembly
                self._PrePickedProperty = self._PickedAssembly.GetProperty()
                # hold onto the property
                self._PrePickedProperty.Register(self._PrePickedProperty)
                self._PickedAssembly.SetProperty(self._PickedProperty)

            self.Render()

#----------------------------------------------------------------------------
def vtkRenderWidgetConeExample():
    """Like it says, just a simple example
    """
    # create root window
    root = Tkinter.Tk()

    # create vtkTkRenderWidget
    pane = vtkTkRenderWidget(root,width=300,height=300)

    ren = vtk.vtkRenderer()
    pane.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # pack the pane into the tk root
    pane.pack()

    # start the tk mainloop
    root.mainloop()

if __name__ == "__main__":
    vtkRenderWidgetConeExample()


text:
class Player < ActiveRecord::Base

  has_many :player_stats, class_name: "Measurable"
  has_many :seasons, through: :player_stats
  has_many :rankings
  has_many :sheets, through: :rankings

  # def self.search(search_term)
  #   where('lower(name) LIKE ?', "%#{search_term.downcase}%").where.not(team: nil)
  # end

  def stats_for(year)
    season_id = Season.find_by(season: year)
    self.player_stats.where(season_id: season_id)[0]
  end

  def player_rank(sheet)
    self.rankings.find_by(sheet_id: sheet.id).player_rank
  end

  def total_points(sheet, year)
    stats = self.stats_for(year)
    (stats[:pass_yards] * sheet.pass_yard_pts) + (stats[:pass_tds] * sheet.pass_td_pts) + (stats[:rush_yards] * sheet.rush_yard_pts) + (stats[:interceptions] * sheet.int_pts) + (stats[:rush_tds] * sheet.rush_td_pts) + (stats[:receptions] * sheet.rec_pts) + (stats[:receive_yards] * sheet.rec_yard_pts) + (stats[:receive_tds] * sheet.rec_td_pts)
  end

  def adj_proj(sheet, year)
    pos_data = {
      "QB" => {correlation_str: 0.60, avg_proj: sheet.avg_qb_proj},
      "RB" => {correlation_str: 0.48, avg_proj: sheet.avg_rb_proj},
      "WR" => {correlation_str: 0.42, avg_proj: sheet.avg_wr_proj},
      "TE" => {correlation_str: 0.62, avg_proj: sheet.avg_te_proj},
    }

    points = self.total_points(sheet, year)

    if self.player_stats.where(season: year) && points != 0
      (pos_data[self.position][:correlation_str] * (points - pos_data[self.position][:avg_proj])) + pos_data[self.position][:avg_proj]
    else
      0
    end
  end

  def draft_status(sheet)
    status = self.rankings.find_by(sheet_id: sheet.id).status
    if status == 0
      return "available"
    elsif status == 1
      return "targeted"
    elsif status == 2
      return "drafted"
    elsif status == 3
      return "unavailable"
    end
  end

end


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('shelves', '0012_auto_20160615_1404'),
    ]

    operations = [
        migrations.CreateModel(
            name='BookGenre',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(blank=True, max_length=200)),
                ('slug', models.SlugField(default='', max_length=200, unique=True)),
            ],
        ),
        migrations.AddField(
            model_name='book',
            name='genre',
            field=models.ManyToManyField(blank=True, to='shelves.BookGenre'),
        ),
    ]


text:
package pro.foundev.ingest;

import com.datastax.driver.core.*;
import com.github.javafaker.Faker;
import com.google.common.net.InetAddresses;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;

import static pro.foundev.Configuration.getKeyspace;
import static pro.foundev.Configuration.getTable;

public class Loader {

    private static Logger logger = Logger.getLogger(Loader.class.toString());
    private final String contactHost;
    private final Random random;

    public Loader(String contactHost) {

        this.contactHost = contactHost;
        this.random = new Random();
    }
    private String createIpAddress() {
        //silly and naive but quick and should only generate valid addresses
        int oct = 253;
        return String.format("%d.%d.%d.%d", random.nextInt(oct) +1, random.nextInt(oct) + 1,
                random.nextInt(oct)+1, random.nextInt(oct)+1);
    }
    public void create(long recordsToCreate) {

        Faker faker = new Faker();
        Cluster cluster = Cluster.builder().addContactPoint(contactHost).build();
        Session session = cluster.newSession();
        new SchemaCreation(session).createSchema();
        PreparedStatement st = session.prepare("INSERT INTO " + getKeyspace() +
                "." + getTable()  + " (id, origin_state, " +
                "ip_address, urls) values ( ?, ?, ?, ?)");
        long tickInterval = recordsToCreate/100;
        int ticksCompleted=0;
        for (long i = 0; i < recordsToCreate; i++) {
            List<ResultSetFuture> futures = new ArrayList<>();
            InetAddress fakeIp = InetAddresses.forString(createIpAddress());
            String fakeState = faker.address().stateAbbr();
            List<String> urls = new ArrayList<>();
            int seed = random.nextInt(10000);
            for (int j = 0; j < seed; j++) {
               urls.add(faker.internet().url());
            }
            BoundStatement bs = st.bind(i, fakeState, fakeIp, urls);
            //      setLong(0, i).
            //        setString(1, fakeState).
            //        setInet(2, fakeIp ).
            //        setList(3, urls);
            //
            futures.add(session.executeAsync(bs));
            if(i % 100==0){
                for (ResultSetFuture future:futures){
                    try {
                        future.getUninterruptibly(2, TimeUnit.SECONDS);
                    } catch (TimeoutException e) {
                        logger.warning(e.getMessage());
                        logger.warning("retrying");
                    }
                }
            }
            if(i!=0 && i % tickInterval==0){
                ticksCompleted ++;
                StringBuilder builder = new StringBuilder();
                for (int j = 0; j < ticksCompleted ; j++) {
                    builder.append("=");
                }
                long ticksLeft = 100 - ticksCompleted;
                if(ticksLeft<0){
                    throw new RuntimeException("ticks left is " + ticksLeft + " and I is " + i);
                }
                for (int j = 0; j < ticksLeft; j++) {
                   builder.append(" ");
                }

               System.out.println("["+ builder.toString() + "]\r");
            }
        }
    }
}


text:
using System;
using System.IO;
using System.Collections.Generic;

namespace AutoTest.Messages
{
	public class TestResult : ICustomBinarySerializable
	{
        private TestRunner _runner;
		private TestRunStatus _status;
        private string _name = "";
        private string _displayName = null;
        private string _message = "";
        private IStackLine[] _stackTrace;
        private static readonly TestResult _passResult;

        public TimeSpan TimeSpent = new TimeSpan();

        /// <summary>
        /// Factory method to return passed message
        /// </summary>
        /// <returns>Passed test result with no message</returns>
        public static TestResult Pass()
        {
            return _passResult;
        }

        /// <summary>
        /// Factory method to return failed result
        /// </summary>
        /// <param name="message">The failure message</param>
        /// <returns>A failed result</returns>
        public static TestResult Fail(string message)
        {
            return new TestResult(TestRunner.Any, TestRunStatus.Failed, message);
        }

        public TestResult(TestRunner runner, TestRunStatus status, string name)
        {
            _runner = runner;
            _name = name;
            _status = status;
            _stackTrace = new IStackLine[] { };
        }

        public TestResult(TestRunner runner, TestRunStatus status, string name, string message)
        {
            _runner = runner;
            _status = status;
            _name = name;
            _message = message;
            _stackTrace = new IStackLine[] { };
        }

        public TestResult(TestRunner runner, TestRunStatus status, string name, string message, IStackLine[] stackTrace)
        {
            _runner = runner;
            _status = status;
            _name = name;
            _message = message;
            _stackTrace = stackTrace;
        }

        public TestResult(TestRunner runner, TestRunStatus status, string name, string message, IStackLine[] stackTrace, double milliseconds)
        {
            _runner = runner;
            _status = status;
            _name = name;
            _message = message;
            _stackTrace = stackTrace;
            TimeSpent = TimeSpan.FromMilliseconds(milliseconds);
        }

        static TestResult()
        {
            _passResult = new TestResult(TestRunner.Any, TestRunStatus.Passed, string.Empty);
        }

        public TestRunner Runner
        {
            get { return _runner; }
        }

        public TestRunStatus Status
        {
            get { return _status; }
        }

        public string Name
        {
            get { return _name; }
        }

        public string DisplayName
        {
            get
            {
                if (_displayName == null)
                    return _name;
                return _displayName;
            }
        }

        public string Message
        {
            get { return _message; } set { _message = value; }
        }

        public IStackLine[] StackTrace
        {
            get { return _stackTrace; } set { _stackTrace = value; }
        }

        public TestResult SetDisplayName(string name)
        {
            _displayName = name;
            return this;
        }

        public override bool Equals(object obj)
        {
            var other = (TestResult) obj;
            return GetHashCode().Equals(other.GetHashCode());
        }

        public override int GetHashCode()
        {
            // Overflow is fine, just wrap
            unchecked
            {
                int hash = 17;
                hash = hash * 23 + _runner.GetHashCode();
                hash = hash * 23 + (_name == null ? 0 : _name.GetHashCode());
                hash = hash * 23 + (_message == null ? 0 : _message.GetHashCode());
                foreach (var line in _stackTrace)
                {
                    hash = hash * 23 + (line.File == null ? 0 : line.File.GetHashCode());
                    hash = hash * 23 + (line.Method == null ? 0 : line.Method.GetHashCode());
                    hash = hash * 23 + line.LineNumber.GetHashCode();
                }
                return hash;
            }
        }

		public void WriteDataTo(BinaryWriter writer)
		{
            writer.Write((int)_runner);
			writer.Write((int) _status);

            if (_name == null)
                writer.Write("");
            else
                writer.Write(_name);

            if (_displayName == null)
                writer.Write("");
            else
                writer.Write(_displayName);

            if (_message == null)
                writer.Write("");
            else
			    writer.Write((string) _message);

            writer.Write((double)TimeSpent.Ticks);
            writer.Write((int)_stackTrace.Length);
			foreach (var line in _stackTrace)
			{
                if (line.Method == null)
                    writer.Write("");
                else
				    writer.Write((string) line.Method);

                if (line.File == null)
                    writer.Write("");
                else
				    writer.Write((string) line.File);

				writer.Write((int) line.LineNumber);
			}
		}

		public void SetDataFrom(BinaryReader reader)
		{
			var stackTrace = new List<IStackLine>();
            _runner = (TestRunner)reader.ReadInt32();
			_status = (TestRunStatus) reader.ReadInt32();
			_name = reader.ReadString();
            _displayName = reader.ReadString();
            if (_displayName == "")
                _displayName = null;
			_message = reader.ReadString();
            TimeSpent = new TimeSpan((long)reader.ReadDouble());
			var count = reader.ReadInt32();
			for (int i = 0; i < count; i++)
			{
				var method = reader.ReadString();
				var file = reader.ReadString();
				var lineNumber = reader.ReadInt32();
				var line = new StackLineMessage(method, file, lineNumber);
				stackTrace.Add(line);
			}
			_stackTrace = stackTrace.ToArray();
		}
    }
}


text:
#import <AppKit/NSPanel.h>

@class NSImageView,NSTextField;

@interface NSSystemInfoPanel : NSObject
{
   IBOutlet NSImageView  *appIconView;
   IBOutlet NSTextField  *appNameField;
   IBOutlet NSScrollView *creditScrollView;
   IBOutlet NSTextView   *creditView;
   IBOutlet NSPanel      *infoPanel;
   IBOutlet NSTextField  *legalTextField;
   IBOutlet NSTextField  *versionField;
}

+ (NSSystemInfoPanel *)standardAboutPanel;
- (IBAction)showInfoPanel:(id)sender;
- (void)showInfoPanel:(id)sender withOptions:(NSDictionary*)options;

- (void)_resetInfoPanel;
@end


text:
<!DOCTYPE html>

  <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="format-detection" content="telephone=no" />
  <meta http-equiv="x-ua-compatible" content="IE=edge" />
  <link rel="stylesheet" href="/pingid/assets/css/main-v21.190.css" media="screen" title="no title" charset="utf-8" />
  <link rel="stylesheet" media="screen" type="text/css" href="/pingid/assets/css/jsdisabled.css" />

    <!DOCTYPE html>

      <title></title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <meta name="format-detection" content="telephone=no">
      <link rel="stylesheet" href="/pingid/assets/css/jsdisabled.css" media="screen" title="no title" charset="utf-8">

              Important

                PingID requires Javascript to be enabled. If the problem persists, please contact your administrator.

            Copyright © 2003-2019 Ping Identity Corporation. All rights reserved.

    <form method="post" action="https://authenticator.pingone.com/pingid/ppm/auth" id="start-form">
      <input type="hidden" name="isWebAuthnSupportedByBrowser" />
    </form>


text:
<!DOCTYPE HTML>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>macchina.io - Sensors & Devices</title>
    <link rel="stylesheet" href="/css/macchina.css" type="text/css"/>
    <link rel="stylesheet" href="/css/font-awesome.min.css" type="text/css"/>
    <link rel="icon" href="/images/favicon.ico">

          MQTT Clients

              {{session.username}}

              Sign out

           <form method="post" name="logout" action="/">
             <input type="hidden" name="action" value="logout">
           </form>

            No MQTT clients configured.

{{client.id}}
            →
            ↛
            {{client.serverURI}}

              No subscriptions

 0">

Subscriptions

                    Topic
                    QoS

                    {{sub.topic}}
                    {{sub.qos}}

 0" style="margin-top: 20px">

Received Messages

                    Topic
                    # Messages

                    {{topic.topic}}
                    {{topic.messageCount}}

 0" style="margin-top: 20px">

Published Messages

                    Topic
                    # Messages

                    {{topic.topic}}
                    {{topic.messageCount}}


text:
.. _configure-hardware:

Configure hardware
==================

Follow the instructions for your hardware
to configure your hardware:

- Connect the NICs on the Fuel Master and node servers to the switches.
- Connect the IPMI cards on the Fuel Master and node servers
  to the out-of-band management network.
- Configure access to the node servers through IPMI.
- Prepare the proper physical network configuration
  (configure switches, routers, and so forth).
- Connect the OpenStack networks
  to the server Ethernet port on each server.


text:
'use strict'

let convert = require('convert-source-map')
let debug = require('debug')('mako-uglify')
let minify = require('uglify-js').minify
let utils = require('mako-utils')

module.exports = function () {
  debug('initialize')

  return function (mako) {
    mako.prewrite('js', function uglify (file, build) {
      let relative = utils.relative(file.path)
      debug('minifying %s', relative)

      try {
        let before = utils.size(file.contents, true)
        let results = minify(file.contents.toString(), {
          fromString: true,
          inSourceMap: file.sourceMap,
          outSourceMap: !!file.sourceMap
        })

        file.contents = Buffer.from(results.code)
        if (results.map) {
          let map = convert.fromJSON(results.map)
          map.setProperty('sourcesContent', file.sourceMap.sourcesContent)
          file.sourceMap = map.toObject()
        }

        let after = utils.size(file.contents, true)
        debug('minified %s %s', relative, utils.sizeDiff(before, after))
      } catch (err) {
        err.message += ` - ${file.relative} [${err.line}:${err.col}]`
        throw err
      }
    })
  }
}


text:
package com.zengularity.cordova.hockeyapp;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;

import net.hockeyapp.android.FeedbackManager;
import net.hockeyapp.android.UpdateManager;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.CrashManagerListener;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.lang.RuntimeException;
import java.lang.Runnable;
import java.lang.Thread;

public class HockeyApp extends CordovaPlugin {

    public static boolean initialized = false;
    public static String token;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
        if (action.equals("start")) {
            token = args.optString(0);
            String autoSend = args.optString(1);
            FeedbackManager.register(cordova.getActivity(), token, null);
            if (autoSend.equals("true")) {
                CrashManager.register(cordova.getActivity(), token, new CrashManagerListener() {
                    public boolean shouldAutoUploadCrashes() {
                        return true;
                    }
                });
            } else {
                CrashManager.register(cordova.getActivity(), token);
            }

            initialized = true;
            callbackContext.success();
            return true;
        }
        else if(action.equals("checkForUpdate")) {
            UpdateManager.register(cordova.getActivity(), token);
            callbackContext.success();
            return true;
        }
        else if(action.equals("feedback")) {
            if(initialized) {
                cordova.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        FeedbackManager.showFeedbackActivity(cordova.getActivity());
                    }
                });
                callbackContext.success();
                return true;
            }
            else {
                callbackContext.error("cordova hockeyapp plugin not initialized, call start() first");
                return false;
            }
        } else if(action.equals("forceCrash")) {
            if(initialized) {
                new Thread(new Runnable() {
                    public void run() {
                        Calendar c = Calendar.getInstance();
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        throw new RuntimeException("Test crash at " + df.format(c.getTime()));
                    }
                }).start();
                return true;
            } else {
                callbackContext.error("cordova hockeyapp plugin not initialized, call start() first");
                return false;
            }
        }
        else {
            return false;
        }
    }

}


text:
import React from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';

import {
    MEDIA_TYPE,
    toggleCameraFacingMode
} from '../../base/media';
import { Container } from '../../base/react';
import { ColorPalette } from '../../base/styles';

import {
    AbstractToolbar,
    mapStateToProps
} from './AbstractToolbar';
import { styles } from './styles';
import ToolbarButton from './ToolbarButton';

/**
 * Implements the conference toolbar on React Native.
 *
 * @extends AbstractToolbar
 */
class Toolbar extends AbstractToolbar {
    /**
     * Initializes a new Toolbar instance.
     *
     * @param {Object} props - The read-only React Component props with which
     * the new instance is to be initialized.
     */
    constructor(props) {
        super(props);

        // Bind event handlers so they are only bound once for every instance.
        this._onCameraFacingModeToggle
            = this._onCameraFacingModeToggle.bind(this);
    }

    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const audioButtonStyles = this._getMuteButtonStyles(MEDIA_TYPE.AUDIO);
        const videoButtonStyles = this._getMuteButtonStyles(MEDIA_TYPE.VIDEO);
        const underlayColor = ColorPalette.buttonUnderlay;

        // TODO Use correct Jitsi icon for camera switch button when available.

        /* eslint-disable react/jsx-handler-names */

        return (
            <Container
                style = { styles.toolbarContainer }
                visible = { this.props.visible }>

                <View style = { styles.toggleCameraFacingModeContainer }>
                    <ToolbarButton
                        iconName = 'reload'
                        iconstyle = { styles.whiteIcon }
                        onClick = { this._onCameraFacingModeToggle }
                        style = { styles.toggleCameraFacingModeButton }
                        underlayColor = 'transparent' />
                </View>
                <View style = { styles.toolbarButtonsContainer }>
                    <ToolbarButton
                        iconName = { audioButtonStyles.iconName }
                        iconStyle = { audioButtonStyles.iconStyle }
                        onClick = { this._toggleAudio }
                        style = { audioButtonStyles.buttonStyle } />
                    <ToolbarButton
                        iconName = 'hangup'
                        iconStyle = { styles.whiteIcon }
                        onClick = { this._onHangup }
                        style = {{
                            ...styles.toolbarButton,
                            backgroundColor: ColorPalette.jitsiRed
                        }}
                        underlayColor = { underlayColor } />
                    <ToolbarButton
                        iconName = { videoButtonStyles.iconName }
                        iconStyle = { videoButtonStyles.iconStyle }
                        onClick = { this._toggleVideo }
                        style = { videoButtonStyles.buttonStyle } />
                </View>
            </Container>
        );

        /* eslint-enable react/jsx-handler-names */
    }

    /**
     * Switches between the front/user-facing and rear/environment-facing
     * cameras.
     *
     * @private
     * @returns {void}
     */
    _onCameraFacingModeToggle() {
        this.props.dispatch(toggleCameraFacingMode());
    }
}

/**
 * Additional properties for various icons, which are now platform-dependent.
 * This is done to have common logic of generating styles for web and native.
 * TODO As soon as we have common font sets for web and native, this will no
 * longer be required.
 */
Object.assign(Toolbar.prototype, {
    audioIcon: 'microphone',
    audioMutedIcon: 'mic-disabled',
    videoIcon: 'webCam',
    videoMutedIcon: 'camera-disabled'
});

/**
 * Toolbar component's property types.
 *
 * @static
 */
Toolbar.propTypes = AbstractToolbar.propTypes;

export default connect(mapStateToProps)(Toolbar);