text:
// PLUGIN: Code

(function ( Popcorn ) {

  /**
   * Code Popcorn Plug-in
   *
   * Adds the ability to run arbitrary code (JavaScript functions) according to video timing.
   *
   * @param {Object} options
   *
   * Required parameters: start, end, template, data, and target.
   * Optional parameter: static.
   *
   *   start: the time in seconds when the mustache template should be rendered
   *          in the target div.
   *
   *   end: the time in seconds when the rendered mustache template should be
   *        removed from the target div.
   *
   *   onStart: the function to be run when the start time is reached.
   *
   *   onFrame: [optional] a function to be run on each paint call
   *            (e.g., called ~60 times per second) between the start and end times.
   *
   *   onEnd: [optional] a function to be run when the end time is reached.
   *
   * Example:
     var p = Popcorn('#video')

        // onStart function only
        .code({
          start: 1,
          end: 4,
          onStart: function( options ) {
            // called on start
          }
        })

        // onStart + onEnd only
        .code({
          start: 6,
          end: 8,
          onStart: function( options ) {
            // called on start
          },
          onEnd: function ( options ) {
            // called on end
          }
        })

        // onStart, onEnd, onFrame
        .code({
          start: 10,
          end: 14,
          onStart: function( options ) {
            // called on start
          },
          onFrame: function ( options ) {
            // called on every paint frame between start and end.
            // uses mozRequestAnimationFrame, webkitRequestAnimationFrame,
            // or setTimeout with 16ms window.
          },
          onEnd: function ( options ) {
            // called on end
          }
        });
  *
  */

  Popcorn.plugin( "code" , function( options ) {
    var running = false,
        instance = this;

    // Setup a proper frame interval function (60fps), favouring paint events.
    var step = (function() {

      var buildFrameRunner = function( runner ) {
        return function( f, options ) {

          var _f = function() {
            running && f.call( instance, options );
            running && runner( _f );
          };

          _f();
        };
      };

      // Figure out which level of browser support we have for this
      if ( window.webkitRequestAnimationFrame ) {
        return buildFrameRunner( window.webkitRequestAnimationFrame );
      } else if ( window.mozRequestAnimationFrame ) {
        return buildFrameRunner( window.mozRequestAnimationFrame );
      } else {
        return buildFrameRunner( function( f ) {
          window.setTimeout( f, 16 );
        });
      }

    })();

    if ( !options.onStart || typeof options.onStart !== "function" ) {

      options.onStart = Popcorn.nop;
    }

    if ( options.onEnd && typeof options.onEnd !== "function" ) {

      options.onEnd = undefined;
    }

    if ( options.onFrame && typeof options.onFrame !== "function" ) {

      options.onFrame = undefined;
    }

    return {
      start: function( event, options ) {
        options.onStart.call( instance, options );

        if ( options.onFrame ) {
          running = true;
          step( options.onFrame, options );
        }
      },

      end: function( event, options ) {
        if ( options.onFrame ) {
          running = false;
        }

        if ( options.onEnd ) {
          options.onEnd.call( instance, options );
        }
      }
    };
  },
  {
    about: {
      name: "Popcorn Code Plugin",
      version: "0.1",
      author: "David Humphrey (@humphd)",
      website: "http://vocamus.net/dave"
    },
    options: {
      start: {
       elem: "input",
       type: "number",
       label: "Start"
      },
      end: {
        elem: "input",
        type: "number",
        label: "End"
      },
      onStart: {
        elem: "input",
        type: "function",
        label: "onStart"
      },
      onFrame: {
        elem: "input",
        type: "function",
        label: "onFrame",
        optional: true
      },
      onEnd: {
        elem: "input",
        type: "function",
        label: "onEnd"
      }
    }
  });
})( Popcorn );


text:
'use strict';

angular.module('rotory')
.controller('navCtrl', function($scope, dataService){

    dataService.getLayers(function(response){
        var config = response.data;
        $scope.layers =  config.layers;
    });

    dataService.getPartials(function(response){
        var partials = response.data;
        // // console.log(partials);
        $scope.partials = partials;
    });

    $scope.addPartial = function(layer, name){
        $scope.partials[layer].partials.unshift(name);
        // create files via ajax request to file which creates them
    };

    $scope.removePartial = function(layer, name){
        $scope.partials[layer].partials.pop(name);
        // remove files via ajax request to file which removes them
    };

});

redpajama_set_name: RedPajamaGithub


text:
define([
  'jquery',
  'underscore',
  'html!./template.html',
  'markdown'
],
function( $, _, template, markdown ){

  // Remove the content template and cache it
  var contentElement = template.querySelector( '#company' );
  if( contentElement && contentElement.parentNode ){
    contentElement.parentNode.removeChild( contentElement );
  }

  // Remove the description element
  var rmEl = contentElement.querySelector( '#description' );
  if( rmEl && rmEl.parentNode ){
    rmEl.parentNode.removeChild( rmEl );
  }

  function Component( data ){

    // Expose fragment
    this.fragment = document.createElement( 'div' );

    $( this.fragment )
      .addClass( 'container-fluid' )
      .append( template.cloneNode( true ) );

    this.addCompany = function( data ){
      if( !data.job ) return;

      var el = contentElement.cloneNode( true );

      var products = data.products || [];
      var lastTask = products[0];
      var firstTask = products[ products.length - 1 ];

      // Job, start - end
      var text = '**' + data.job + '**, ' + firstTask.dateStart + ' - ' + lastTask.dateEnd;
      $( el ).find( '#job' ).html( markdown.toHTML( text ) );

      // Company, city, state, country
      var fields = [];
      if( data.name ) fields.push( '**' + data.name + '**' );
      if( data.city ) fields.push( data.city );
      if( data.state ) fields.push( data.state );
      if( data.country ) fields.push( data.country );
      text = fields.join(', ');
      $( el ).find( '#office' ).html( markdown.toHTML( text ) );

      var tags = [];

      // Add resume of each project
      products.forEach( function( product ){
        if( !product.resume ) return;
        var resume = markdown.toHTML( product.resume );
        $( resume ).addClass( 'lead text ' ).appendTo( el );

        tags = _( tags ).union( product.tags || [] );
      });

      tags = _( tags ).map( function( item ){
        return '' + item + '';
      });

      text = tags.join(', ');

      $( '
' + text + '
' ).addClass( 'text' ).appendTo( el );

      $( el ).appendTo( this.fragment );
    };

    this.set = function( name, content ){
      switch( name ){
        case 'title':
          var el = this.fragment.querySelector('#title');
          $( el ).text( content );
          break;
        case 'companies':
          content.forEach( this.addCompany.bind( this ) );
          break;
      }
    }

    for( var prop in data ){
      if( !data.hasOwnProperty( prop ) ){
        continue;
      }
      var content = data[prop];

      this.set( prop, content );
    }
  }

  return Component;
});


text:
#region << 版 本 注 释 >>

#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Dos.Common;
using Dos.WeChat.Common;
using Dos.WeChat.Model;
using Newtonsoft.Json;

namespace Dos.WeChat
{
    public class MediaApi
    {
        /// <summary>
        ///
        /// </summary>
        public static RemoteMedia Upload(LocalMedia media)
        {
            var checkRet = Check(media);
            if (!checkRet.IsSuccess)
                throw new WxException(-9999, checkRet.ErrMsg);

            var param = new HttpParam
            {
                {"access_token", Token.GetAccessToken(media)},
                {"type", media.MediaType}
            };
            var rs = HttpHelper.Upload(ApiList.MediaUploadUrl, param, media.MediaPath);
            var result = JsonConvert.DeserializeObject<RemoteMedia>(rs);
            if (string.IsNullOrEmpty(result.MediaID))
            {
                var ex = JsonConvert.DeserializeObject<WeChatResult>(rs);
                throw new WxException(ex);
            }
            return result;
        }

        /// <summary>
        ///     检测上传的媒体是否满足基本要求
        /// </summary>
        private static WeChatResult Check(LocalMedia media)
        {
            var sizes = new Dictionary<string, long>
            {
                {Media.Image, 128*1024},
                {Media.Voice, 256*1024},
                {Media.Video, 1*1024*1024},
                {Media.Thumb, 64*1024},
            };

            if (media == null)
                return WeChatResult.GetFailed("缺少媒体参数");
            if (!File.Exists(media.MediaPath))
                return WeChatResult.GetFailed("指定的媒体文件不存在");
            if (string.IsNullOrEmpty(media.MediaType))
                return WeChatResult.GetFailed("未指定媒体类型");
            if (new FileInfo(media.MediaPath).Length > sizes[media.MediaType])
                return WeChatResult.GetFailed(string.Format("指定的媒体文件超过限制大小{0}K", sizes[media.MediaPath] / 1024));

            return WeChatResult.GetSuccess();
        }

        /// <summary>
        /// 传入MediaID,WeChatPublic
        /// </summary>
        public static WeChatResult Download(MediaParam mediaParam)
        {
            var param = new HttpParam
            {
                {"access_token", Token.GetAccessToken(mediaParam)},
                {"media_id", mediaParam.MediaID}
            };
            var url = string.Format("{0}?{1}", ApiList.MediaGet, param.Format());
            var request = HttpHelper.CreateRequest(url);
            var response = request.GetResponse();
            using (var stream = response.GetResponseStream())
            {
                var disposition = response.Headers["Content-disposition"];
                if (string.IsNullOrEmpty(disposition))
                {
                    var s = new StreamReader(stream, Encoding.UTF8).ReadToEnd();
                    return JsonConvert.DeserializeObject<WeChatResult>(s);
                }
                var fs = new FileStream(mediaParam.FilePath, FileMode.OpenOrCreate);
                try
                {
                    var buffer = new byte[128 * 1024]; //128K
                    int i;
                    while ((i = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, i);
                    }

                    return WeChatResult.GetSuccess(mediaParam.FilePath);
                }
                finally
                {
                    fs.Close();
                }
            }
        }
    }
    /// <summary>
    ///
    /// </summary>
    public class MediaParam : WeChatParam
    {
        /// <summary>
        ///     媒体文件上传后,获取时的唯一标识
        /// </summary>
        [JsonProperty(PropertyName = "media_id")]
        public string MediaID { get; set; }
        public string FilePath { get; set; }
    }
    /// <summary>
    ///
    /// </summary>
    public class Media : WeChatParam
    {
        /// <summary>
        ///     图片(image): 128K,支持JPG格式
        /// </summary>
        public const string Image = "image";

        /// <summary>
        ///     语音(voice):256K,播放长度不超过60s,支持AMR\MP3格式
        /// </summary>
        public const string Voice = "voice";

        /// <summary>
        ///     视频(video):1MB,支持MP4格式
        /// </summary>
        public const string Video = "video";

        /// <summary>
        ///     缩略图(thumb):64KB,支持JPG格式
        /// </summary>
        public const string Thumb = "thumb";

        /// <summary>
        ///     常量中描述的媒体类型
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string MediaType { get; set; }
    }

    /// <summary>
    ///     本地媒体
    /// </summary>
    public class LocalMedia : Media
    {
        /// <summary>
        ///     本地全路径
        /// </summary>
        public string MediaPath { get; set; }
    }

    /// <summary>
    /// 远程媒体。指保存在微信服务器上的媒体。
    /// </summary>
    public class RemoteMedia : Media
    {
        /// <summary>
        /// 媒体文件上传后,获取时的唯一标识
        /// </summary>
        [JsonProperty(PropertyName = "media_id")]
        public string MediaID { get; set; }

        /// <summary>
        ///     媒体文件上传时间戳
        /// </summary>
        [JsonProperty(PropertyName = "created_at")]
        public int Timestamp { get; set; }
    }
}


text:
case ${PHARO_DEP_MGMT:-zeroconf} in
    zeroconf)
	curl http://get.pharo.org/travis | bash ;;
    ubuntu)
	sudo apt-get update

	sudo apt-get install \
	    libasound2:i386 \
	    libc6:i386 \
	    libfreetype6:i386 \
	    libgl1-mesa-glx:i386 \
	    libssl1.0.0:i386 \
	    libx11-6:i386
	;;
    *)
	echo "Invalid dependency resolution: ${PHARO_DEP_MGMT}"
	echo "Set PHARO_DEP_MGMT to one of the following:"
	echo "  - zeroconf, use Pharo ZeroConf scripts to resolve and install"
	echo "    all dependencies. This is the default value."
        echo "  - ubuntu, assume system is Ubuntu 12.04; the set packages to"
	echo "    install is hardcoded in this script."

	exit 64 # EX_USAGE, see sysexits(3)
esac


text:
/**
 * Export `mini-react-router`
 */

exports = module.exports = require('./lib/route');
exports.go = require('./lib/go');


text:
<?php

namespace axibase\atsdPHP;
require_once(dirname(__FILE__) . '/../AtsdClient.php');

class Properties  extends AtsdClient{
    const URI = '/properties/query';
    protected $queryUri;

    function find($jsonRequest) {
        $this->queryUri = Properties::URI ;
        $this->postParams = json_decode($jsonRequest);
        return $this->query($this->queryUri);
    }

}


text:
module Data.String.Strip (strip)  where

import Data.Char

strip :: String -> String
strip = dropWhile isSpace . reverse . dropWhile isSpace . reverse


text:
class userInterface extends Phaser.Sprite {
    constructor(game) {
        super(game);
        game.add.existing(this);
        game.physics.arcade.enable(this);
        this.anchor.setTo(0.5);
        console.log('interface Loaded!');
        //this.body.bounce.set(1, 0);
        this._loadDepthMeter();
        this._loadCourseSelector();
        this._loadStatusBar();
        this.depthArrowMoving = false;
        this.courseArrowMoving = false;
        this.events.deepChanger = new Phaser.Signal();
        this.events.courseChanger = new Phaser.Signal();
        this.course = 0;
        this.horizontalCoordinate = 190;
        this.depthLogger = 34;
        this.markerLocation = 546;
        this.body.velocity.x = 30;
    }

    _loadDepthMeter() {
        this.depthMeter = this.game.add.image(2, 36, 'depthMeter');
        this.depthMeter.fixedToCamera = true;
        this.depthArrow = this.game.add.sprite(0, 58, 'depthArrow');
        this.depthArrow.inputEnabled = true;
        this.depthArrow.fixedToCamera = true;
        this.depthArrow.events.onInputDown.add(this._setDepth, this);
        this.depthArrow.events.onInputUp.add(this._disableDepth, this);
    }
    _setDepth() {
        this.depthArrowMoving = true;
    }
    _disableDepth() {
        this.depthArrowMoving = false;
        this.events.deepChanger.dispatch(this.horizontalCoordinate);
    }

    _loadCourseSelector() {
        this.courseSelector = this.game.add.image(440, 338, 'courseSelector');
        this.courseArrow = this.game.add.image(546, 348, 'courseArrow');
        this.courseArrow.anchor.setTo(0.5);
        this.courseArrow.inputEnabled = true;
        this.courseArrow.events.onInputDown.add(this._setCourse, this);
        this.courseArrow.events.onInputUp.add(this._disableCourse, this);
        this.courseSelector.fixedToCamera = true;
     this.courseArrow.fixedToCamera = true;
    }

    _setCourse() {
        this.courseArrowMoving = true;

    }

    _disableCourse() {
        this.courseArrowMoving = false;
        this.events.courseChanger.dispatch(this.course);
    }

    _loadStatusBar() {
        this.statusBar = this.game.add.image(442, 4, 'statusBar');
        this.statusBar.fixedToCamera = true;
    }

    _depthUpdater() {
        if (this.depthArrowMoving === true) {
            if (this.game.input.worldY > this.y + 36 && this.game.input.worldY < this.y + 316) {
                this.depthLogger = this.game.input.y;
                this.horizontalLogger = this.depthLogger - 35;
                this.horizontalCoordinate = this.horizontalLogger / 280 * 290 + 165;

                this.depthArrow.cameraOffset.y = this.game.input.y;

            }
        }
    }

    _courseUpdater() {
        if (this.courseArrowMoving === true) {
                        if (this.game.input.x > 438 + 4 && this.game.input.x < 526 + 4 || this.game.input.x > 540 + 4 && this.game.input.x < 628 + 4) {
                            if (this.game.input.x > 443 && this.game.input.x < 529) {
                                this.courseArrow.cameraOffset.x = this.game.input.x;
                                this.course = this.game.input.x - 443;
                                this.course = (85 + 0) - this.course;
                                this.course = - Math.abs(this.course);

            //
                            }
                            if (this.game.input.x > 545 && this.game.input.x < 640) {
                                this.courseArrow.cameraOffset.x = this.game.input.x;
                                this.course = this.game.input.x - 386 - 160;

                            }
//                            if(this.course < 5){
//                                this.course = 0;
//                            }
//
                        }
                    }

        }

    update() {
        this._depthUpdater();
        this._courseUpdater();

    }
}


text:
package org.tinymediamanager.scraper.moviemeternl.model;

import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Myron Boyle
 */
public class FilmJson {

  @JsonProperty
  private int            id;
  @JsonProperty
  private String         url;
  @JsonProperty
  private int            year;
  @JsonProperty
  private String         imdb;
  @JsonProperty
  private String         title;
  @JsonProperty
  private String         display_title;
  @JsonProperty
  private String         alternative_title;
  @JsonProperty
  private String         plot;
  @JsonProperty
  private double         duration;
  @JsonProperty
  private int            votes_count;
  @JsonProperty
  private String         average;
  @JsonProperty
  private MMPosters      posters;
  @JsonProperty
  private List<String>   countries;
  @JsonProperty
  private List<String>   genres;
  @JsonProperty
  private List<MMActors> actors;
  @JsonProperty
  private List<String>   directors;

  public static class MMPosters {
    @JsonProperty
    private String thumb;
    @JsonProperty
    private String small;
    @JsonProperty
    private String regular;
    @JsonProperty
    private String large;

    public String getThumb() {
      return thumb;
    }

    public String getSmall() {
      return small;
    }

    public String getRegular() {
      return regular;
    }

    public String getLarge() {
      return large;
    }
  }

  public static class MMActors {
    @JsonProperty
    private String name;
    @JsonProperty
    private String voice;

    public String getName() {
      return name;
    }

    public String getVoice() {
      return voice;
    }
  }

  public int getId() {
    return id;
  }

  public String getUrl() {
    return url;
  }

  public int getYear() {
    return year;
  }

  public String getImdb() {
    return imdb;
  }

  public String getTitle() {
    return title;
  }

  public String getDisplay_title() {
    return display_title;
  }

  public String getAlternative_title() {
    return alternative_title;
  }

  public String getPlot() {
    return plot;
  }

  public double getDuration() {
    return duration;
  }

  public int getVotes_count() {
    return votes_count;
  }

  public String getAverage() {
    return average;
  }

  public MMPosters getPosters() {
    return posters;
  }

  public List<String> getCountries() {
    return countries;
  }

  public List<String> getGenres() {
    return genres;
  }

  public List<MMActors> getActors() {
    return actors;
  }

  public List<String> getDirectors() {
    return directors;
  }

  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
  }
}


text: apic(${api} TEMPLATE api.proto.tmpl OUTPUTS api.proto)


text:
// Mock property item objects
var item1 = {
		id:"c1",
		title:"c1",
		value:"vc1"
	},
	item2 = {
		id:"c2",
		title:"c2",
		value:"vc2",
		refToView: "refToView2"
	};

var propItem1, propItem2, propItem3, propItem1Dupl;

// Mock property object
var prop1 = {
		id: "id1",
		equals: function(p) {return p==prop1}
	},
	prop2 = {
		id: "id2",
		equals: function(p) {return p==prop2}
	};

function setUp() {
	propItem1 = new ORYX.Core.StencilSet.PropertyItem(item1, "testNS", prop1);
	propItem2 = new ORYX.Core.StencilSet.PropertyItem(item2, "testNS", prop1);
	propItem3 = new ORYX.Core.StencilSet.PropertyItem(item1, "testNS", prop2);
	propItem1Dupl = new ORYX.Core.StencilSet.PropertyItem(item1, "testNS", prop1);
}

/*
 * Test constructor function
 */
function testConstruct() {
	assertEquals("vc1", propItem1.value());
	assertEquals("id1", propItem1.property().id);
	assertEquals("testNS", propItem1.namespace());

	assertEquals("vc2", propItem2.value());
	assertEquals("id1", propItem2.property().id);
	assertEquals("testNS", propItem2.namespace());
	assertEquals("refToView2", propItem2.refToView()[0]);
	assertEquals(1, propItem2.refToView().length)

	assertEquals("id2", propItem3.property().id);
}

/*
 * Test equals function
 */
function testEquals() {
	assertTrue(propItem1.equals(propItem1));
	assertTrue(propItem1.equals(propItem1Dupl));
	assertFalse(propItem1.equals(propItem2));
	assertFalse(propItem1.equals(propItem3));
}

function tearDown() {
	delete propItem1;
	delete propItem2;
	delete propItem3;
	delete propItem1Dupl;
}


text:
[Normalize.css](https://github.com/necolas/normalize.css) is a customisable CSS file that makes browsers render all elements more consistently and in line with modern standards.

[Normalize.json](https://github.com/dwighthouse/normalize.json) is Normalize.css converted to json for use with [JSS](https://github.com/jsstyles/jss).

For details of support, the styles, and how these styles work, please visit the [repository for Normalize.css](https://github.com/necolas/normalize.css);

## Install

* [npm](http://npmjs.org/): `npm install --save normalize.json`

Because `No other styles should come before Normalize.css.`, be sure that the your usage within JSS ensures that the styles in Normalize.json are the first added to the page.


text:
package com.example.android.apis.app;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.android.apis.R;

/**
 * This is an example of implementing an application service that runs locally
 * in the same process as the application.  The {@link Controller}
 * class shows how to interact with the service.
 *
 *
Notice the use of the {@link NotificationManager} when interesting things
 * happen in the service.  This is generally how background services should
 * interact with the user, rather than doing something more disruptive such as
 * calling startActivity().
 *
 *
For applications targeting Android 1.5 or beyond, you may want consider
 * using the {@link android.app.IntentService} class, which takes care of all the
 * work of creating the extra thread and dispatching commands to it.
 */
public class ServiceStartArguments extends org.bbs.apklauncher.api.Base_Service {
    private NotificationManager mNM;
    private Intent mInvokeIntent;
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            Bundle arguments = (Bundle)msg.obj;

            String txt = arguments.getString("name");

            Log.i("ServiceStartArguments", "Message: " + msg + ", "
                    + arguments.getString("name"));

            if ((msg.arg2&Service.START_FLAG_REDELIVERY) == 0) {
                txt = "New cmd #" + msg.arg1 + ": " + txt;
            } else {
                txt = "Re-delivered #" + msg.arg1 + ": " + txt;
            }

            showNotification(txt);

            // Normally we would do some work here...  for our sample, we will
            // just sleep for 5 seconds.
            long endTime = System.currentTimeMillis() + 5*1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }

            hideNotification();

            Log.i("ServiceStartArguments", "Done with #" + msg.arg1);
            stopSelf(msg.arg1);
        }

    };

    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        Toast.makeText(this, R.string.service_created,
                Toast.LENGTH_SHORT).show();

        // This is who should be launched if the user selects our persistent
        // notification.
        mInvokeIntent = new org.bbs.apklauncher.emb.IntentHelper(this, Controller.class);

        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.  We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("ServiceStartArguments",
                "Starting #" + startId + ": " + intent.getExtras());
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.arg2 = flags;
        msg.obj = intent.getExtras();
        mServiceHandler.sendMessage(msg);
        Log.i("ServiceStartArguments", "Sending: " + msg);

        // For the start fail button, we will simulate the process dying
        // for some reason in onStartCommand().
        if (intent.getBooleanExtra("fail", false)) {
            // Don't do this if we are in a retry... the system will
            // eventually give up if we keep crashing.
            if ((flags&START_FLAG_RETRY) == 0) {
                // Since the process hasn't finished handling the command,
                // it will be restarted with the command again, regardless of
                // whether we return START_REDELIVER_INTENT.
                Process.killProcess(Process.myPid());
            }
        }

        // Normally we would consistently return one kind of result...
        // however, here we will select between these two, so you can see
        // how they impact the behavior.  Try killing the process while it
        // is in the middle of executing the different commands.
        return intent.getBooleanExtra("redeliver", false)
                ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();

        hideNotification();

        // Tell the user we stopped.
        Toast.makeText(ServiceStartArguments.this, R.string.service_destroyed,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * Show a notification while this service is running.
     */
    private void showNotification(String text) {
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(getHostIdentifier("demo_notification", "image", null), text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = org.bbs.apklauncher.emb.PendingIntentHelper.getActivity(this, 0,
                new org.bbs.apklauncher.emb.IntentHelper(this, Controller.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_start_arguments_label),
                       text, contentIntent);

        // We show this for as long as our service is processing a command.
        notification.flags |= Notification.FLAG_ONGOING_EVENT;

        // Send the notification.
        // We use a string id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.service_created, notification);
    }

    private void hideNotification() {
        mNM.cancel(R.string.service_created);
    }

    // ----------------------------------------------------------------------

    /**
     * Example of explicitly starting the {@link ServiceStartArguments}.
     *
     *
Note that this is implemented as an inner class only keep the sample
     * all together; typically this code would appear in some separate class.
     */
    public static class Controller extends org.bbs.apklauncher.api.Base_Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.service_start_arguments_controller);

            // Watch for button clicks.
            Button button = (Button)findViewById(R.id.start1);
            button.setOnClickListener(mStart1Listener);
            button = (Button)findViewById(R.id.start2);
            button.setOnClickListener(mStart2Listener);
            button = (Button)findViewById(R.id.start3);
            button.setOnClickListener(mStart3Listener);
            button = (Button)findViewById(R.id.startfail);
            button.setOnClickListener(mStartFailListener);
            button = (Button)findViewById(R.id.kill);
            button.setOnClickListener(mKillListener);
        }

        private OnClickListener mStart1Listener = new OnClickListener() {
            public void onClick(View v) {
                startService(new org.bbs.apklauncher.emb.IntentHelper(Controller.this,
                        ServiceStartArguments.class)
                                .putExtra("name", "One"));
            }
        };

        private OnClickListener mStart2Listener = new OnClickListener() {
            public void onClick(View v) {
                startService(new org.bbs.apklauncher.emb.IntentHelper(Controller.this,
                        ServiceStartArguments.class)
                                .putExtra("name", "Two"));
            }
        };

        private OnClickListener mStart3Listener = new OnClickListener() {
            public void onClick(View v) {
                startService(new org.bbs.apklauncher.emb.IntentHelper(Controller.this,
                        ServiceStartArguments.class)
                                .putExtra("name", "Three")
                                .putExtra("redeliver", true));
            }
        };

        private OnClickListener mStartFailListener = new OnClickListener() {
            public void onClick(View v) {
                startService(new org.bbs.apklauncher.emb.IntentHelper(Controller.this,
                        ServiceStartArguments.class)
                                .putExtra("name", "Failure")
                                .putExtra("fail", true));
            }
        };

        private OnClickListener mKillListener = new OnClickListener() {
            public void onClick(View v) {
                // This is to simulate the service being killed while it is
                // running in the background.
                Process.killProcess(Process.myPid());
            }
        };
    }
}


text:
package hudson.search;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import hudson.model.FreeStyleProject;
import hudson.model.ListView;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.MockFolder;

import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;

/**
 * @author Kohsuke Kawaguchi
 */
public class SearchTest {

    @Rule public JenkinsRule j = new JenkinsRule();

    /**
     * No exact match should result in a failure status code.
     */
    @Test
    public void testFailure() throws Exception {
        try {
            j.search("no-such-thing");
            fail("404 expected");
        } catch (FailingHttpStatusCodeException e) {
            assertEquals(404,e.getResponse().getStatusCode());
        }
    }

    /**
     * Makes sure the script doesn't execute.
     */
    @Bug(3415)
    @Test
    public void testXSS() throws Exception {
        try {
            WebClient wc = j.createWebClient();
            wc.setAlertHandler(new AlertHandler() {
                public void handleAlert(Page page, String message) {
                    throw new AssertionError();
                }
            });
            wc.search("<script>alert('script');</script>");
            fail("404 expected");
        } catch (FailingHttpStatusCodeException e) {
            assertEquals(404,e.getResponse().getStatusCode());
        }
    }

    @Test
    public void testSearchByProjectName() throws Exception {
        final String projectName = "testSearchByProjectName";

        j.createFreeStyleProject(projectName);

        Page result = j.search(projectName);
        Assert.assertNotNull(result);
        j.assertGoodStatus(result);

        // make sure we've fetched the testSearchByDisplayName project page
        String contents = result.getWebResponse().getContentAsString();
        Assert.assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", projectName)));
    }

    @Test
    public void testSearchByDisplayName() throws Exception {
        final String displayName = "displayName9999999";

        FreeStyleProject project = j.createFreeStyleProject("testSearchByDisplayName");
        project.setDisplayName(displayName);

        Page result = j.search(displayName);
        Assert.assertNotNull(result);
        j.assertGoodStatus(result);

        // make sure we've fetched the testSearchByDisplayName project page
        String contents = result.getWebResponse().getContentAsString();
        Assert.assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", displayName)));
    }

    @Test
    public void testSearch2ProjectsWithSameDisplayName() throws Exception {
        // create 2 freestyle projects with the same display name
        final String projectName1 = "projectName1";
        final String projectName2 = "projectName2";
        final String projectName3 = "projectName3";
        final String displayName = "displayNameFoo";
        final String otherDisplayName = "otherDisplayName";

        FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
        project1.setDisplayName(displayName);
        FreeStyleProject project2 = j.createFreeStyleProject(projectName2);
        project2.setDisplayName(displayName);
        FreeStyleProject project3 = j.createFreeStyleProject(projectName3);
        project3.setDisplayName(otherDisplayName);

        // make sure that on search we get back one of the projects, it doesn't
        // matter which one as long as the one that is returned has displayName
        // as the display name
        Page result = j.search(displayName);
        Assert.assertNotNull(result);
        j.assertGoodStatus(result);

        // make sure we've fetched the testSearchByDisplayName project page
        String contents = result.getWebResponse().getContentAsString();
        Assert.assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", displayName)));
        Assert.assertFalse(contents.contains(otherDisplayName));
    }

    @Test
    public void testProjectNamePrecedesDisplayName() throws Exception {
        final String project1Name = "foo";
        final String project1DisplayName = "project1DisplayName";
        final String project2Name = "project2Name";
        final String project2DisplayName = project1Name;
        final String project3Name = "project3Name";
        final String project3DisplayName = "project3DisplayName";

        // create 1 freestyle project with the name foo
        FreeStyleProject project1 = j.createFreeStyleProject(project1Name);
        project1.setDisplayName(project1DisplayName);

        // create another with the display name foo
        FreeStyleProject project2 = j.createFreeStyleProject(project2Name);
        project2.setDisplayName(project2DisplayName);

        // create a third project and make sure it's not picked up by search
        FreeStyleProject project3 = j.createFreeStyleProject(project3Name);
        project3.setDisplayName(project3DisplayName);

        // search for foo
        Page result = j.search(project1Name);
        Assert.assertNotNull(result);
        j.assertGoodStatus(result);

        // make sure we get the project with the name foo
        String contents = result.getWebResponse().getContentAsString();
        Assert.assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", project1DisplayName)));
        // make sure projects 2 and 3 were not picked up
        Assert.assertFalse(contents.contains(project2Name));
        Assert.assertFalse(contents.contains(project3Name));
        Assert.assertFalse(contents.contains(project3DisplayName));
    }

    @Test
    public void testGetSuggestionsHasBothNamesAndDisplayNames() throws Exception {
        final String projectName = "project name";
        final String displayName = "display name";

        FreeStyleProject project1 = j.createFreeStyleProject(projectName);
        project1.setDisplayName(displayName);

        WebClient wc = j.createWebClient();
        Page result = wc.goTo("search/suggest?query=name", "application/json");
        Assert.assertNotNull(result);
        j.assertGoodStatus(result);

        String content = result.getWebResponse().getContentAsString();
        System.out.println(content);
        JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
        Assert.assertNotNull(jsonContent);
        JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
        Assert.assertNotNull(jsonArray);

        Assert.assertEquals(2, jsonArray.size());

        boolean foundProjectName = false;
        boolean foundDispayName = false;
        for(Object suggestion : jsonArray) {
            JSONObject jsonSuggestion = (JSONObject)suggestion;

            String name = (String)jsonSuggestion.get("name");
            if(projectName.equals(name)) {
                foundProjectName = true;
            }
            else if(displayName.equals(name)) {
                foundDispayName = true;
            }
        }

        Assert.assertTrue(foundProjectName);
        Assert.assertTrue(foundDispayName);
    }

    /**
     * Disable/enable status shouldn't affect the search
     */
    @Bug(13148)
    @Test
    public void testDisabledJobShouldBeSearchable() throws Exception {
        FreeStyleProject p = j.createFreeStyleProject("foo-bar");
        assertTrue(suggest(j.jenkins.getSearchIndex(), "foo").contains(p));

        p.disable();
        assertTrue(suggest(j.jenkins.getSearchIndex(), "foo").contains(p));
    }

    /**
     * All top-level jobs should be searchable, not just jobs in the current view.
     */
    @Bug(13148)
    @Test
    public void testCompletionOutsideView() throws Exception {
        FreeStyleProject p = j.createFreeStyleProject("foo-bar");
        ListView v = new ListView("empty1",j.jenkins);
        ListView w = new ListView("empty2",j.jenkins);
        j.jenkins.addView(v);
        j.jenkins.addView(w);
        j.jenkins.setPrimaryView(w);

        // new view should be empty
        assertFalse(v.contains(p));
        assertFalse(w.contains(p));
        assertFalse(j.jenkins.getPrimaryView().contains(p));

        assertTrue(suggest(j.jenkins.getSearchIndex(),"foo").contains(p));
    }

    @Test
    public void testSearchWithinFolders() throws Exception {
        MockFolder folder1 = j.createFolder("folder1");
        FreeStyleProject p1 = folder1.createProject(FreeStyleProject.class, "myjob");
        MockFolder folder2 = j.createFolder("folder2");
        FreeStyleProject p2 = folder2.createProject(FreeStyleProject.class, "myjob");
        List<SearchItem> suggest = suggest(j.jenkins.getSearchIndex(), "myjob");
        assertTrue(suggest.contains(p1));
        assertTrue(suggest.contains(p2));
    }

    private List<SearchItem> suggest(SearchIndex index, String term) {
        List<SearchItem> result = new ArrayList<SearchItem>();
        index.suggest(term, result);
        return result;
    }
}


text:
import * as _ from "../index";
declare module "../index" {
    interface LoDashStatic {
        /**
         * Sets the value at path of object. If a portion of path doesn't exist it's created. Arrays are created for
         * missing index properties while objects are created for all other missing properties. Use _.setWith to
         * customize path creation.
         *
         * @param object The object to modify.
         * @param path The path of the property to set.
         * @param value The value to set.
         * @return Returns object.
         */
        set<T extends object>(
            object: T,
            path: PropertyPath,
            value: any
        ): T;

        /**
         * @see _.set
         */
        set<TResult>(
            object: object,
            path: PropertyPath,
            value: any
        ): TResult;
    }

    interface LoDashImplicitWrapper<TValue> {
        /**
         * @see _.set
         */
        set(
            path: PropertyPath,
            value: any
        ): this;

        /**
         * @see _.set
         */
        set<TResult>(
            path: PropertyPath,
            value: any
        ): LoDashImplicitWrapper<TResult>;
    }

    interface LoDashExplicitWrapper<TValue> {
        /**
         * @see _.set
         */
        set(
            path: PropertyPath,
            value: any
        ): this;

        /**
         * @see _.set
         */
        set<TResult>(
            path: PropertyPath,
            value: any
        ): LoDashExplicitWrapper<TResult>;
    }
}


text:
"""
:copyright: (c) 2014 Building Energy Inc
:license: see LICENSE for more details.
"""
import os
import sys
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BE.settings.main")
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)


text:
package com.feilong.core.util.equator;

import java.io.Serializable;

import org.apache.commons.collections4.Equator;
import org.apache.commons.lang3.StringUtils;

/**
 * 忽视大小写的实现.
 *
 * @author feilong
 * @see org.apache.commons.collections4.functors.DefaultEquator
 * @since 1.10.1
 */
public class IgnoreCaseEquator implements Equator<String>,Serializable{

    /** The Constant serialVersionUID. */
    private static final long             serialVersionUID = 5700113137952086493L;

    /** Static instance. */
    // the static instance works for all types
    public static final IgnoreCaseEquator INSTANCE         = new IgnoreCaseEquator();

    //---------------------------------------------------------------

    /**
     * Restricted constructor.
     */
    private IgnoreCaseEquator(){
        super();
    }

    //---------------------------------------------------------------

    /*
     * (non-Javadoc)
     *
     * @see org.apache.commons.collections4.Equator#equate(java.lang.Object, java.lang.Object)
     */
    @Override
    public boolean equate(final String s1,final String s2){
        return StringUtils.equalsIgnoreCase(s1, s2);
    }

    //---------------------------------------------------------------

    /**
     * {@inheritDoc}
     *
     * @return s.hashCode() if s is non-null, else -1.
     */
    @Override
    public int hash(final String s){
        return s == null ? -1 : s.hashCode();
    }

}


text:
@interface OAAppDelegate : UIResponder <UIApplicationDelegate>

@property(strong, readonly, nonatomic) OARootViewController* rootViewController;

@end


text:
<?php

namespace LegalThings\DataEnricher\Processor;

use LegalThings\DataEnricher\Node;
use LegalThings\DataEnricher\Processor;

/**
 * @covers LegalThings\DataEnricher\Processor\Evaluate
 */
class EvaluateTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Processor\Reference;
     */
    protected $processor;

    public function setUp()
    {
        $this->processor = new Processor\Evaluate('<eval>');
    }

    public function instructionProvider()
    {
        return [
            [
                "foo.bar == 'test'",
                (object)['foo' => (object)['bar' => 'test']],
                true
            ],
            [
                "foo.bar == 'test' && baz.zoo[0] == 'rest'",
                (object)[
                    'foo' => (object)['bar' => 'test'],
                    'baz' => (object)['zoo' => ['rest']]
                ],
                true
            ],
            [
                "foo.bar == 'test' || baz.zoo[0] == 'rest'",
                (object)[
                    'foo' => (object)['bar' => 'test'],
                    'baz' => (object)['zoo' => [null]]
                ],
                true
            ],
            [
                "foo.bar == null",
                (object)['foo' => (object)['bar' => null]],
                true
            ],
            [
                "foo.bar == 'tests'",
                (object)['foo' => (object)['bar' => 'test']],
                false
            ],
            [
                "foo.bar == 'test' && baz.zoo[0] == 'rest'",
                (object)[
                    'foo' => (object)['bar' => 'test'],
                    'baz' => (object)['zoo' => ['rests']]
                ],
                false
            ],
        ];
    }

    /**
     * @dataProvider instructionProvider
     *
     * @param string|object|array $instruction
     * @param object              $source
     * @param string|object|array $result
     */
    public function testApplyToNode($instruction, $source, $result)
    {
        $processor = $this->processor->withSourceAndTarget($source, []);

        $node = $this->createMock(Node::class);

        $node->expects($this->atLeastOnce())
            ->method('getInstruction')
            ->with($processor)
            ->willReturn($instruction);

        $node->expects($this->atLeastOnce())
            ->method('setResult')
            ->with($result);

        $processor->applyToNode($node);
    }
}


text:
class APIVersion

  def initialize(options)
    @version = options[:version]
    @default = options[:current]
  end

  def matches?(request)
    @default || check_headers(request.headers)
  end

  private
    def check_headers(headers)
      accept = headers['Accept']
      accept && accept.include?("application/gfwc-v#{@version}+json")
    end

end


text:
package com.navercorp.pinpoint.profiler.context;

/**
 * @author emeroad
 */
public class SpanEventStackFrame implements StackFrame {
    private final SpanEvent spanEvent;
    private int stackId;
    private Object frameObject;

    public SpanEventStackFrame(SpanEvent spanEvent) {
        if (spanEvent == null) {
            throw new NullPointerException("spanEvent must not be null");
        }
        this.spanEvent = spanEvent;
    }

    @Override
    public int getStackFrameId() {
        return stackId;
    }

    @Override
    public void setStackFrameId(int stackId) {
        this.stackId = stackId;
    }

    @Override
    public void markBeforeTime() {
        spanEvent.markStartTime();
    }

    @Override
    public long getBeforeTime() {
        return spanEvent.getStartTime();
    }

    @Override
    public void markAfterTime() {
        spanEvent.markAfterTime();
    }

    @Override
    public long getAfterTime() {
        return spanEvent.getAfterTime();
    }

    @Override
    public int getElapsedTime() {
        return spanEvent.getEndElapsed();
    }

    public void setSequence(short sequence) {
        spanEvent.setSequence(sequence);
    }

    public SpanEvent getSpanEvent() {
        return spanEvent;
    }

    @Override
    public void setEndPoint(String endPoint) {
        this.spanEvent.setEndPoint(endPoint);
    }

    @Override
    public void setRpc(String rpc) {
        this.spanEvent.setRpc(rpc);
    }

    @Override
    public void setApiId(int apiId) {
        this.spanEvent.setApiId(apiId);
    }

    @Override
    public void setExceptionInfo(int exceptionId, String exceptionMessage) {
        this.spanEvent.setExceptionInfo(exceptionId, exceptionMessage);
    }

    @Override
    public void setServiceType(short serviceType) {
        spanEvent.setServiceType(serviceType);
    }

    @Override
    public void addAnnotation(Annotation annotation) {
        this.spanEvent.addAnnotation(annotation);
    }

    public void setDestinationId(String destinationId) {
        this.spanEvent.setDestinationId(destinationId);
    }

    public void setNextSpanId(long nextSpanId) {
        this.spanEvent.setNextSpanId(nextSpanId);
    }

    @Override
    public Object attachFrameObject(Object frameObject) {
        Object copy = this.frameObject;
        this.frameObject = frameObject;
        return copy;
    }

    @Override
    public Object getFrameObject() {
        return this.frameObject;
    }

    @Override
    public Object detachFrameObject() {
        Object copy = this.frameObject;
        this.frameObject = null;
        return copy;
    }

    @Override
    public short getServiceType() {
        return spanEvent.getServiceType();
    }

    public void setAsyncId(int asyncId) {
        this.spanEvent.setAsyncId(asyncId);
    }

    public void setNextAsyncId(int asyncId) {
        this.spanEvent.setNextAsyncId(asyncId);
    }

    public void setAsyncSequence(short asyncSequence) {
        this.spanEvent.setAsyncSequence(asyncSequence);
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@class ALButtonViewModel;

@interface ALButton : UIButton <ALMenuItem>

@property (nullable, nonatomic, readonly) UIBezierPath *scaledMaskPath;
@property (nonatomic, readonly) ALButtonViewModel *viewModel;

- (instancetype)initWithViewModel:(ALButtonViewModel *)viewModel NS_DESIGNATED_INITIALIZER;

@end

NS_ASSUME_NONNULL_END


text:
echo "Setting up environment"
set sodiumBuild=Debug
call "%VS120COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64

echo "Building PoSH-Sodium"
MSBuild ..\PoSH-Sodium.sln /p:Configuration=Debug /p:Platform="Any CPU"

echo "Running tests"
cmd /c ..\PesterFork\bin\pester.bat

echo "Generating report"
IF NOT EXIST "..\Nunit-HTML-Report-Generator\NUnit HTML Report Generator\bin\Debug\NUnitHTMLReportGenerator.exe" MSBuild "..\Nunit-HTML-Report-Generator\NUnit HTML Report Generator.sln" /p:Configuration=Debug /p:Platform="Any CPU"
del LastTestResults.html
call "..\Nunit-HTML-Report-Generator\NUnit HTML Report Generator\bin\Debug\NUnitHTMLReportGenerator.exe" Test.xml LastTestResults.html
pause


text:
<?php

namespace Eloquent\Typhax\Type;

/**
 * Represents a float type.
 *
 * @api
 */
class FloatType implements Type
{
    /**
     * Accept a visitor.
     *
     * @api
     *
     * @param TypeVisitor $visitor The visitor.
     *
     * @return mixed The result of visitation.
     */
    public function accept(TypeVisitor $visitor)
    {
        return $visitor->visitFloatType($this);
    }
}


text:
Article 1812
----
Le preneur ne peut disposer d'aucune bête du troupeau, soit du fonds, soit du
croît, sans le consentement du bailleur, qui ne peut lui-même en disposer sans
le consentement du preneur.


text:
package video;

import java.io.File;
import java.io.IOException;

import org.jcodec.api.SequenceEncoder8Bit;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.model.Rational;

import video.animation.AnimatorQueue;

public class VideoEncoder {

	private SequenceEncoder8Bit encoder;

	private int framesPerSecond;
	private int numberOfFrames;
	private int currentFrameNumber;

	private String directory;

	private AnimatorQueue animatorQueue;

	public VideoEncoder(int framesPerSecond, int numberOfFrames, String directory) {

		this.framesPerSecond = framesPerSecond;
		this.numberOfFrames = numberOfFrames;
		this.directory = directory;

	}

	public void initialize() {

		initEncoder();
		animatorQueue.initAnimators(framesPerSecond, numberOfFrames, numberOfFrames);

	}

	public boolean initEncoder() {

		try {

			encoder = new SequenceEncoder8Bit(NIOUtils.writableChannel(new File(directory + "test.mp4")),
					Rational.R(framesPerSecond, 1));

		} catch (IOException e) {

			e.printStackTrace();
			return false;

		}

		return true;

	}

	public void updateAnimators() {

		animatorQueue.update(currentFrameNumber);

	}

}


text:
title: RDO blog roundup, week of October 12
author: rbowen
date: 2015-10-12 13:50:45 UTC
tags: blog, roundup, 2015
comments: true
published: true
---

Here's what RDO enthusiasts have been writing about over the past week.

If you're writing about RDO, or about OpenStack on CentOS, Fedora or RHEL, and you're not on my list, please let me know!

**Scheduled! Scale or Fail:  Containers on OpenStack with OpenShift 3 – #vBrownBag TechTalk at OpenStack Summit Tokyo** by Diane Mueller

> Come join us for lunch on Wednesday at noon  in the Wakashiba room! We will also be live streaming (conference Internet willing). The session will be recorded and will be posted to our YouTube channel. The link below will turn into direct links to the videos.

... read more at [http://tm3.org/2x](http://tm3.org/2x)

**What's new in OpenStack Liberty: webinar recap** by Steve Gordon and Sean Cohen

> OpenStack "Liberty," due for imminent release, represents the 12th release of the open source computing platform for public and private clouds. Recent OpenStack releases have focused on improving stability and enhancing the operator experience. This is still the case with Liberty, but there are still new features to consider.

... read more at [http://tm3.org/2y](http://tm3.org/2y)

**Minimum Viable Cluster** by Andrew Beekhof

> In the past there was a clear distinction between high performance (HP) clustering and high availability (HA) clustering, however the lines have been bluring for some time. People have scaled HA clusters upwards and HP inspired clusters have been used to provide availability through redundancy.

... read more at [http://tm3.org/2z](http://tm3.org/2z)

**Delorean: OpenStack packages from the future** by  Frederic Lepied

> I have been doing some patches on Delorean lately so I thought it could be a good idea to describe it in this article as it is not a well known tool.

... read more at [http://tm3.org/2-](http://tm3.org/2-)

**Scheduling and disabling Cells** by  Belmiro Moreira

> In order to scale OpenStack Cloud Infrastructure at CERN, we were early to embrace an architecture that uses Cells. Cells is a Nova functionality that allows the partition a Cloud Infrastructure into smaller groups with independent control planes.

... read more at [http://tm3.org/30](http://tm3.org/30)

**Running NTP in a Container** Lars Kellogg-Stedman

> Someone asked on IRC about running ntpd in a container on Atomic, so I've put together a small example. We'll start with a very simple Dockerfile:

... read more at [http://tm3.org/31](http://tm3.org/31)

**Multiple external networks with a single L3 agent testing on RDO Liberty per Lars Kellogg-Stedman** by Boris Derzhavets

> Following bellow is supposed to test in multi node environment
Multiple external networks with a single L3 agent by Lars Kellogg-Stedman.  However, current post contains an attempt to analyze and understand how traffic to/from external network flows through br-int when provider external networks has been involved

... read more at [http://tm3.org/33](http://tm3.org/33)

**RDO Liberty (RC2) DVR Neutron workflow on CentOS 7.1** by Boris Derzhavets

> Per http://specs.openstack.org/openstack/neutron-specs/specs/juno/neutron-ovs-dvr.html
DVR is supposed to address following problems which has traditional 3 Node
deployment schema:-

... read more at [http://tm3.org/34](http://tm3.org/34)


text:
Add some welcoming text here. A table of contents will be placed below this.

Also math works:
$$\int x^2 dx = \tfrac{1}{3}x^3 + C$$


text:
package com.androidhive.imagefromurl;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidLoadImageFromURLActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Loader image - will be shown before loading image
        int loader = R.drawable.loader;

        // Imageview to show
        ImageView image = (ImageView) findViewById(R.id.image);

        // Image url
        String image_url = "http://api.androidhive.info/images/sample.jpg";

        // ImageLoader class instance
        ImageLoader imgLoader = new ImageLoader(getApplicationContext());

        // whenever you want to load an image from url
        // call DisplayImage function
        // url - image url to load
        // loader - loader image, will be displayed before getting image
        // image - ImageView
        imgLoader.DisplayImage(image_url, loader, image);
    }
}


text:
import { DEBUG } from '@glimmer/env';

import { assert } from '../index';
import { HandlerCallback, invoke, registerHandler as genericRegisterHandler } from './handlers';

export interface WarnOptions {
  id: string;
}

export type RegisterHandlerFunc = (handler: HandlerCallback) => void;
export type WarnFunc = (message: string, test?: boolean, options?: WarnOptions) => void;

let registerHandler: RegisterHandlerFunc = () => {};
let warn: WarnFunc = () => {};
let missingOptionsDeprecation: string;
let missingOptionsIdDeprecation: string;

/**
@module @ember/debug
*/

if (DEBUG) {
  /**
    Allows for runtime registration of handler functions that override the default warning behavior.
    Warnings are invoked by calls made to [@ember/debug/warn](https://emberjs.com/api/ember/release/classes/@ember%2Fdebug/methods/warn?anchor=warn).
    The following example demonstrates its usage by registering a handler that does nothing overriding Ember's
    default warning behavior.

    ```javascript
    import { registerWarnHandler } from '@ember/debug';

    // next is not called, so no warnings get the default behavior
    registerWarnHandler(() => {});
    ```

    The handler function takes the following arguments:

 message - The message received from the warn call.

 options - An object passed in with the warn call containing additional information including:

 id - An id of the warning in the form of package-name.specific-warning.

 next - A function that calls into the previously registered handler.

    @public
    @static
    @method registerWarnHandler
    @for @ember/debug
    @param handler {Function} A function to handle warnings.
    @since 2.1.0
  */
  registerHandler = function registerHandler(handler) {
    genericRegisterHandler('warn', handler);
  };

  registerHandler(function logWarning(message) {
    /* eslint-disable no-console */
    console.warn(`WARNING: ${message}`);
    if (console.trace) {
      console.trace();
    }
    /* eslint-enable no-console */
  });

  missingOptionsDeprecation =
    'When calling `warn` you ' +
    'must provide an `options` hash as the third parameter.  ' +
    '`options` should include an `id` property.';
  missingOptionsIdDeprecation = 'When calling `warn` you must provide `id` in options.';

  /**
    Display a warning with the provided message.

    * In a production build, this method is defined as an empty function (NOP).
    Uses of this method in Ember itself are stripped from the ember.prod.js build.

    ```javascript
    import { warn } from '@ember/debug';
    import tomsterCount from './tomster-counter'; // a module in my project

    // Log a warning if we have more than 3 tomsters
    warn('Too many tomsters!', tomsterCount <= 3, {
      id: 'ember-debug.too-many-tomsters'
    });
    ```

    @method warn
    @for @ember/debug
    @static
    @param {String} message A warning to display.
    @param {Boolean} test An optional boolean. If falsy, the warning
      will be displayed.
    @param {Object} options An object that can be used to pass a unique
      `id` for this warning.  The `id` can be used by Ember debugging tools
      to change the behavior (raise, log, or silence) for that specific warning.
      The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"
    @public
    @since 1.0.0
  */
  warn = function warn(message, test, options) {
    if (arguments.length === 2 && typeof test === 'object') {
      options = test;
      test = false;
    }

    assert(missingOptionsDeprecation, !!options);
    assert(missingOptionsIdDeprecation, !!(options && options.id));

    invoke('warn', message, test, options);
  };
}

export default warn;
export { registerHandler, missingOptionsIdDeprecation, missingOptionsDeprecation };


text:
package net.nemerosa.ontrack.extension.vault;

import net.nemerosa.ontrack.model.support.OntrackConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.vault.authentication.ClientAuthentication;
import org.springframework.vault.authentication.TokenAuthentication;
import org.springframework.vault.client.VaultEndpoint;
import org.springframework.vault.config.AbstractVaultConfiguration;

import java.net.URI;

import static net.nemerosa.ontrack.extension.vault.VaultExtensionFeature.VAULT_KEY_STORE_PROPERTY;

@Configuration
@ConditionalOnProperty(name = OntrackConfigProperties.KEY_STORE, havingValue = VAULT_KEY_STORE_PROPERTY)
public class VaultConfig extends AbstractVaultConfiguration {

    private final VaultConfigProperties configProperties;

    @Autowired
    public VaultConfig(VaultConfigProperties configProperties) {
        this.configProperties = configProperties;
    }

    @Override
    public VaultEndpoint vaultEndpoint() {
        return VaultEndpoint.from(URI.create(configProperties.getUri()));
    }

    @Override
    public ClientAuthentication clientAuthentication() {
        return new TokenAuthentication(
                configProperties.getToken()
        );
    }
}


text:
using std::shared_ptr;
using std::vector;

namespace arrow {

std::shared_ptr<Column> column(const std::shared_ptr<Field>& field,
                               const std::vector<std::shared_ptr<Array>>& arrays) {
  return std::make_shared<Column>(field, arrays);
}

class TestChunkedArray : public TestBase {
 protected:
  virtual void Construct() {
    one_ = std::make_shared<ChunkedArray>(arrays_one_);
    another_ = std::make_shared<ChunkedArray>(arrays_another_);
  }

  ArrayVector arrays_one_;
  ArrayVector arrays_another_;

  std::shared_ptr<ChunkedArray> one_;
  std::shared_ptr<ChunkedArray> another_;
};

TEST_F(TestChunkedArray, BasicEquals) {
  std::vector<bool> null_bitmap(100, true);
  std::vector<int32_t> data(100, 1);
  std::shared_ptr<Array> array;
  ArrayFromVector<Int32Type, int32_t>(null_bitmap, data, &array);
  arrays_one_.push_back(array);
  arrays_another_.push_back(array);

  Construct();
  ASSERT_TRUE(one_->Equals(one_));
  ASSERT_FALSE(one_->Equals(nullptr));
  ASSERT_TRUE(one_->Equals(another_));
  ASSERT_TRUE(one_->Equals(*another_.get()));
}

TEST_F(TestChunkedArray, EqualsDifferingTypes) {
  std::vector<bool> null_bitmap(100, true);
  std::vector<int32_t> data32(100, 1);
  std::vector<int64_t> data64(100, 1);
  std::shared_ptr<Array> array;
  ArrayFromVector<Int32Type, int32_t>(null_bitmap, data32, &array);
  arrays_one_.push_back(array);
  ArrayFromVector<Int64Type, int64_t>(null_bitmap, data64, &array);
  arrays_another_.push_back(array);

  Construct();
  ASSERT_FALSE(one_->Equals(another_));
  ASSERT_FALSE(one_->Equals(*another_.get()));
}

TEST_F(TestChunkedArray, EqualsDifferingLengths) {
  std::vector<bool> null_bitmap100(100, true);
  std::vector<bool> null_bitmap101(101, true);
  std::vector<int32_t> data100(100, 1);
  std::vector<int32_t> data101(101, 1);
  std::shared_ptr<Array> array;
  ArrayFromVector<Int32Type, int32_t>(null_bitmap100, data100, &array);
  arrays_one_.push_back(array);
  ArrayFromVector<Int32Type, int32_t>(null_bitmap101, data101, &array);
  arrays_another_.push_back(array);

  Construct();
  ASSERT_FALSE(one_->Equals(another_));
  ASSERT_FALSE(one_->Equals(*another_.get()));

  std::vector<bool> null_bitmap1(1, true);
  std::vector<int32_t> data1(1, 1);
  ArrayFromVector<Int32Type, int32_t>(null_bitmap1, data1, &array);
  arrays_one_.push_back(array);

  Construct();
  ASSERT_TRUE(one_->Equals(another_));
  ASSERT_TRUE(one_->Equals(*another_.get()));
}

TEST_F(TestChunkedArray, SliceEquals) {
  arrays_one_.push_back(MakeRandomArray<Int32Array>(100));
  arrays_one_.push_back(MakeRandomArray<Int32Array>(50));
  arrays_one_.push_back(MakeRandomArray<Int32Array>(50));
  Construct();

  std::shared_ptr<ChunkedArray> slice = one_->Slice(125, 50);
  ASSERT_EQ(slice->length(), 50);
  test::AssertChunkedEqual(*one_->Slice(125, 50), *slice);

  std::shared_ptr<ChunkedArray> slice2 = one_->Slice(75)->Slice(25)->Slice(25, 50);
  ASSERT_EQ(slice2->length(), 50);
  test::AssertChunkedEqual(*slice, *slice2);
}

class TestColumn : public TestChunkedArray {
 protected:
  void Construct() override {
    TestChunkedArray::Construct();

    one_col_ = std::make_shared<Column>(one_field_, one_);
    another_col_ = std::make_shared<Column>(another_field_, another_);
  }

  std::shared_ptr<ChunkedArray> data_;
  std::unique_ptr<Column> column_;

  std::shared_ptr<Field> one_field_;
  std::shared_ptr<Field> another_field_;

  std::shared_ptr<Column> one_col_;
  std::shared_ptr<Column> another_col_;
};

TEST_F(TestColumn, BasicAPI) {
  ArrayVector arrays;
  arrays.push_back(MakeRandomArray<Int32Array>(100));
  arrays.push_back(MakeRandomArray<Int32Array>(100, 10));
  arrays.push_back(MakeRandomArray<Int32Array>(100, 20));

  auto f0 = field("c0", int32());
  column_.reset(new Column(f0, arrays));

  ASSERT_EQ("c0", column_->name());
  ASSERT_TRUE(column_->type()->Equals(int32()));
  ASSERT_EQ(300, column_->length());
  ASSERT_EQ(30, column_->null_count());
  ASSERT_EQ(3, column_->data()->num_chunks());
}

TEST_F(TestColumn, ChunksInhomogeneous) {
  ArrayVector arrays;
  arrays.push_back(MakeRandomArray<Int32Array>(100));
  arrays.push_back(MakeRandomArray<Int32Array>(100, 10));

  auto f0 = field("c0", int32());
  column_.reset(new Column(f0, arrays));

  ASSERT_OK(column_->ValidateData());

  arrays.push_back(MakeRandomArray<Int16Array>(100, 10));
  column_.reset(new Column(f0, arrays));
  ASSERT_RAISES(Invalid, column_->ValidateData());
}

TEST_F(TestColumn, SliceEquals) {
  arrays_one_.push_back(MakeRandomArray<Int32Array>(100));
  arrays_one_.push_back(MakeRandomArray<Int32Array>(50));
  arrays_one_.push_back(MakeRandomArray<Int32Array>(50));
  one_field_ = field("column", int32());
  Construct();

  std::shared_ptr<Column> slice = one_col_->Slice(125, 50);
  ASSERT_EQ(slice->length(), 50);
  ASSERT_TRUE(slice->Equals(one_col_->Slice(125, 50)));

  std::shared_ptr<Column> slice2 = one_col_->Slice(75)->Slice(25)->Slice(25, 50);
  ASSERT_EQ(slice2->length(), 50);
  ASSERT_TRUE(slice2->Equals(slice));
}

TEST_F(TestColumn, Equals) {
  std::vector<bool> null_bitmap(100, true);
  std::vector<int32_t> data(100, 1);
  std::shared_ptr<Array> array;
  ArrayFromVector<Int32Type, int32_t>(null_bitmap, data, &array);
  arrays_one_.push_back(array);
  arrays_another_.push_back(array);

  one_field_ = field("column", int32());
  another_field_ = field("column", int32());

  Construct();
  ASSERT_TRUE(one_col_->Equals(one_col_));
  ASSERT_FALSE(one_col_->Equals(nullptr));
  ASSERT_TRUE(one_col_->Equals(another_col_));
  ASSERT_TRUE(one_col_->Equals(*another_col_.get()));

  // Field is different
  another_field_ = field("two", int32());
  Construct();
  ASSERT_FALSE(one_col_->Equals(another_col_));
  ASSERT_FALSE(one_col_->Equals(*another_col_.get()));

  // ChunkedArray is different
  another_field_ = field("column", int32());
  arrays_another_.push_back(array);
  Construct();
  ASSERT_FALSE(one_col_->Equals(another_col_));
  ASSERT_FALSE(one_col_->Equals(*another_col_.get()));
}

class TestTable : public TestBase {
 public:
  void MakeExample1(int length) {
    auto f0 = field("f0", int32());
    auto f1 = field("f1", uint8());
    auto f2 = field("f2", int16());

    vector<shared_ptr<Field>> fields = {f0, f1, f2};
    schema_ = std::make_shared<Schema>(fields);

    arrays_ = {MakeRandomArray<Int32Array>(length), MakeRandomArray<UInt8Array>(length),
               MakeRandomArray<Int16Array>(length)};

    columns_ = {std::make_shared<Column>(schema_->field(0), arrays_[0]),
                std::make_shared<Column>(schema_->field(1), arrays_[1]),
                std::make_shared<Column>(schema_->field(2), arrays_[2])};
  }

 protected:
  std::shared_ptr<Table> table_;
  shared_ptr<Schema> schema_;

  std::vector<std::shared_ptr<Array>> arrays_;
  std::vector<std::shared_ptr<Column>> columns_;
};

TEST_F(TestTable, EmptySchema) {
  auto empty_schema = ::arrow::schema({});
  table_ = Table::Make(empty_schema, columns_);
  ASSERT_OK(table_->Validate());
  ASSERT_EQ(0, table_->num_rows());
  ASSERT_EQ(0, table_->num_columns());
}

TEST_F(TestTable, Ctors) {
  const int length = 100;
  MakeExample1(length);

  table_ = Table::Make(schema_, columns_);
  ASSERT_OK(table_->Validate());
  ASSERT_EQ(length, table_->num_rows());
  ASSERT_EQ(3, table_->num_columns());

  auto array_ctor = Table::Make(schema_, arrays_);
  ASSERT_TRUE(table_->Equals(*array_ctor));

  table_ = Table::Make(schema_, columns_, length);
  ASSERT_OK(table_->Validate());
  ASSERT_EQ(length, table_->num_rows());

  table_ = Table::Make(schema_, arrays_);
  ASSERT_OK(table_->Validate());
  ASSERT_EQ(length, table_->num_rows());
  ASSERT_EQ(3, table_->num_columns());
}

TEST_F(TestTable, Metadata) {
  const int length = 100;
  MakeExample1(length);

  table_ = Table::Make(schema_, columns_);

  ASSERT_TRUE(table_->schema()->Equals(*schema_));

  auto col = table_->column(0);
  ASSERT_EQ(schema_->field(0)->name(), col->name());
  ASSERT_EQ(schema_->field(0)->type(), col->type());
}

TEST_F(TestTable, InvalidColumns) {
  // Check that columns are all the same length
  const int length = 100;
  MakeExample1(length);

  table_ = Table::Make(schema_, columns_, length - 1);
  ASSERT_RAISES(Invalid, table_->Validate());

  columns_.clear();

  // Wrong number of columns
  table_ = Table::Make(schema_, columns_, length);
  ASSERT_RAISES(Invalid, table_->Validate());

  columns_ = {
      std::make_shared<Column>(schema_->field(0), MakeRandomArray<Int32Array>(length)),
      std::make_shared<Column>(schema_->field(1), MakeRandomArray<UInt8Array>(length)),
      std::make_shared<Column>(schema_->field(2),
                               MakeRandomArray<Int16Array>(length - 1))};

  table_ = Table::Make(schema_, columns_, length);
  ASSERT_RAISES(Invalid, table_->Validate());
}

TEST_F(TestTable, Equals) {
  const int length = 100;
  MakeExample1(length);

  table_ = Table::Make(schema_, columns_);

  ASSERT_TRUE(table_->Equals(*table_));
  // Differing schema
  auto f0 = field("f3", int32());
  auto f1 = field("f4", uint8());
  auto f2 = field("f5", int16());
  vector<shared_ptr<Field>> fields = {f0, f1, f2};
  auto other_schema = std::make_shared<Schema>(fields);
  auto other = Table::Make(other_schema, columns_);
  ASSERT_FALSE(table_->Equals(*other));
  // Differing columns
  std::vector<std::shared_ptr<Column>> other_columns = {
      std::make_shared<Column>(schema_->field(0),
                               MakeRandomArray<Int32Array>(length, 10)),
      std::make_shared<Column>(schema_->field(1),
                               MakeRandomArray<UInt8Array>(length, 10)),
      std::make_shared<Column>(schema_->field(2),
                               MakeRandomArray<Int16Array>(length, 10))};

  other = Table::Make(schema_, other_columns);
  ASSERT_FALSE(table_->Equals(*other));
}

TEST_F(TestTable, FromRecordBatches) {
  const int64_t length = 10;
  MakeExample1(length);

  auto batch1 = RecordBatch::Make(schema_, length, arrays_);

  std::shared_ptr<Table> result, expected;
  ASSERT_OK(Table::FromRecordBatches({batch1}, &result));

  expected = Table::Make(schema_, columns_);
  ASSERT_TRUE(result->Equals(*expected));

  std::vector<std::shared_ptr<Column>> other_columns;
  for (int i = 0; i < schema_->num_fields(); ++i) {
    std::vector<std::shared_ptr<Array>> col_arrays = {arrays_[i], arrays_[i]};
    other_columns.push_back(std::make_shared<Column>(schema_->field(i), col_arrays));
  }

  ASSERT_OK(Table::FromRecordBatches({batch1, batch1}, &result));
  expected = Table::Make(schema_, other_columns);
  ASSERT_TRUE(result->Equals(*expected));

  // Error states
  std::vector<std::shared_ptr<RecordBatch>> empty_batches;
  ASSERT_RAISES(Invalid, Table::FromRecordBatches(empty_batches, &result));

  auto other_schema = ::arrow::schema({schema_->field(0), schema_->field(1)});

  std::vector<std::shared_ptr<Array>> other_arrays = {arrays_[0], arrays_[1]};
  auto batch2 = RecordBatch::Make(other_schema, length, other_arrays);
  ASSERT_RAISES(Invalid, Table::FromRecordBatches({batch1, batch2}, &result));
}

TEST_F(TestTable, FromRecordBatchesZeroLength) {
  // ARROW-2307
  MakeExample1(10);

  std::shared_ptr<Table> result;
  ASSERT_OK(Table::FromRecordBatches(schema_, {}, &result));

  ASSERT_EQ(0, result->num_rows());
  ASSERT_TRUE(result->schema()->Equals(*schema_));
}

TEST_F(TestTable, ConcatenateTables) {
  const int64_t length = 10;

  MakeExample1(length);
  auto batch1 = RecordBatch::Make(schema_, length, arrays_);

  // generate different data
  MakeExample1(length);
  auto batch2 = RecordBatch::Make(schema_, length, arrays_);

  std::shared_ptr<Table> t1, t2, t3, result, expected;
  ASSERT_OK(Table::FromRecordBatches({batch1}, &t1));
  ASSERT_OK(Table::FromRecordBatches({batch2}, &t2));

  ASSERT_OK(ConcatenateTables({t1, t2}, &result));
  ASSERT_OK(Table::FromRecordBatches({batch1, batch2}, &expected));
  test::AssertTablesEqual(*expected, *result);

  // Error states
  std::vector<std::shared_ptr<Table>> empty_tables;
  ASSERT_RAISES(Invalid, ConcatenateTables(empty_tables, &result));

  auto other_schema = ::arrow::schema({schema_->field(0), schema_->field(1)});

  std::vector<std::shared_ptr<Array>> other_arrays = {arrays_[0], arrays_[1]};
  auto batch3 = RecordBatch::Make(other_schema, length, other_arrays);
  ASSERT_OK(Table::FromRecordBatches({batch3}, &t3));

  ASSERT_RAISES(Invalid, ConcatenateTables({t1, t3}, &result));
}

TEST_F(TestTable, RemoveColumn) {
  const int64_t length = 10;
  MakeExample1(length);

  auto table_sp = Table::Make(schema_, columns_);
  const Table& table = *table_sp;

  std::shared_ptr<Table> result;
  ASSERT_OK(table.RemoveColumn(0, &result));

  auto ex_schema = ::arrow::schema({schema_->field(1), schema_->field(2)});
  std::vector<std::shared_ptr<Column>> ex_columns = {table.column(1), table.column(2)};

  auto expected = Table::Make(ex_schema, ex_columns);
  ASSERT_TRUE(result->Equals(*expected));

  ASSERT_OK(table.RemoveColumn(1, &result));
  ex_schema = ::arrow::schema({schema_->field(0), schema_->field(2)});
  ex_columns = {table.column(0), table.column(2)};

  expected = Table::Make(ex_schema, ex_columns);
  ASSERT_TRUE(result->Equals(*expected));

  ASSERT_OK(table.RemoveColumn(2, &result));
  ex_schema = ::arrow::schema({schema_->field(0), schema_->field(1)});
  ex_columns = {table.column(0), table.column(1)};
  expected = Table::Make(ex_schema, ex_columns);
  ASSERT_TRUE(result->Equals(*expected));
}

TEST_F(TestTable, RemoveColumnEmpty) {
  // ARROW-1865
  const int64_t length = 10;

  auto f0 = field("f0", int32());
  auto schema = ::arrow::schema({f0});
  auto a0 = MakeRandomArray<Int32Array>(length);

  auto table = Table::Make(schema, {std::make_shared<Column>(f0, a0)});

  std::shared_ptr<Table> empty;
  ASSERT_OK(table->RemoveColumn(0, &empty));

  ASSERT_EQ(table->num_rows(), empty->num_rows());

  std::shared_ptr<Table> added;
  ASSERT_OK(empty->AddColumn(0, table->column(0), &added));
  ASSERT_EQ(table->num_rows(), added->num_rows());
}

TEST_F(TestTable, AddColumn) {
  const int64_t length = 10;
  MakeExample1(length);

  auto table_sp = Table::Make(schema_, columns_);
  const Table& table = *table_sp;

  std::shared_ptr<Table> result;
  // Some negative tests with invalid index
  Status status = table.AddColumn(10, columns_[0], &result);
  ASSERT_TRUE(status.IsInvalid());
  status = table.AddColumn(4, columns_[0], &result);
  ASSERT_TRUE(status.IsInvalid());
  status = table.AddColumn(-1, columns_[0], &result);
  ASSERT_TRUE(status.IsInvalid());

  // Add column with wrong length
  auto longer_col = std::make_shared<Column>(schema_->field(0),
                                             MakeRandomArray<Int32Array>(length + 1));
  status = table.AddColumn(0, longer_col, &result);
  ASSERT_TRUE(status.IsInvalid());

  // Add column 0 in different places
  ASSERT_OK(table.AddColumn(0, columns_[0], &result));
  auto ex_schema = ::arrow::schema(
      {schema_->field(0), schema_->field(0), schema_->field(1), schema_->field(2)});

  auto expected = Table::Make(
      ex_schema, {table.column(0), table.column(0), table.column(1), table.column(2)});
  ASSERT_TRUE(result->Equals(*expected));

  ASSERT_OK(table.AddColumn(1, columns_[0], &result));
  ex_schema = ::arrow::schema(
      {schema_->field(0), schema_->field(0), schema_->field(1), schema_->field(2)});

  expected = Table::Make(
      ex_schema, {table.column(0), table.column(0), table.column(1), table.column(2)});
  ASSERT_TRUE(result->Equals(*expected));

  ASSERT_OK(table.AddColumn(2, columns_[0], &result));
  ex_schema = ::arrow::schema(
      {schema_->field(0), schema_->field(1), schema_->field(0), schema_->field(2)});
  expected = Table::Make(
      ex_schema, {table.column(0), table.column(1), table.column(0), table.column(2)});
  ASSERT_TRUE(result->Equals(*expected));

  ASSERT_OK(table.AddColumn(3, columns_[0], &result));
  ex_schema = ::arrow::schema(
      {schema_->field(0), schema_->field(1), schema_->field(2), schema_->field(0)});
  expected = Table::Make(
      ex_schema, {table.column(0), table.column(1), table.column(2), table.column(0)});
  ASSERT_TRUE(result->Equals(*expected));
}

class TestRecordBatch : public TestBase {};

TEST_F(TestRecordBatch, Equals) {
  const int length = 10;

  auto f0 = field("f0", int32());
  auto f1 = field("f1", uint8());
  auto f2 = field("f2", int16());

  vector<shared_ptr<Field>> fields = {f0, f1, f2};
  auto schema = ::arrow::schema({f0, f1, f2});
  auto schema2 = ::arrow::schema({f0, f1});

  auto a0 = MakeRandomArray<Int32Array>(length);
  auto a1 = MakeRandomArray<UInt8Array>(length);
  auto a2 = MakeRandomArray<Int16Array>(length);

  auto b1 = RecordBatch::Make(schema, length, {a0, a1, a2});
  auto b3 = RecordBatch::Make(schema2, length, {a0, a1});
  auto b4 = RecordBatch::Make(schema, length, {a0, a1, a1});

  ASSERT_TRUE(b1->Equals(*b1));
  ASSERT_FALSE(b1->Equals(*b3));
  ASSERT_FALSE(b1->Equals(*b4));
}

TEST_F(TestRecordBatch, Validate) {
  const int length = 10;

  auto f0 = field("f0", int32());
  auto f1 = field("f1", uint8());
  auto f2 = field("f2", int16());

  auto schema = ::arrow::schema({f0, f1, f2});

  auto a0 = MakeRandomArray<Int32Array>(length);
  auto a1 = MakeRandomArray<UInt8Array>(length);
  auto a2 = MakeRandomArray<Int16Array>(length);
  auto a3 = MakeRandomArray<Int16Array>(5);

  auto b1 = RecordBatch::Make(schema, length, {a0, a1, a2});

  ASSERT_OK(b1->Validate());

  // Length mismatch
  auto b2 = RecordBatch::Make(schema, length, {a0, a1, a3});
  ASSERT_RAISES(Invalid, b2->Validate());

  // Type mismatch
  auto b3 = RecordBatch::Make(schema, length, {a0, a1, a0});
  ASSERT_RAISES(Invalid, b3->Validate());
}

TEST_F(TestRecordBatch, Slice) {
  const int length = 10;

  auto f0 = field("f0", int32());
  auto f1 = field("f1", uint8());

  vector<shared_ptr<Field>> fields = {f0, f1};
  auto schema = ::arrow::schema(fields);

  auto a0 = MakeRandomArray<Int32Array>(length);
  auto a1 = MakeRandomArray<UInt8Array>(length);

  auto batch = RecordBatch::Make(schema, length, {a0, a1});

  auto batch_slice = batch->Slice(2);
  auto batch_slice2 = batch->Slice(1, 5);

  ASSERT_EQ(batch_slice->num_rows(), batch->num_rows() - 2);

  for (int i = 0; i < batch->num_columns(); ++i) {
    ASSERT_EQ(2, batch_slice->column(i)->offset());
    ASSERT_EQ(length - 2, batch_slice->column(i)->length());

    ASSERT_EQ(1, batch_slice2->column(i)->offset());
    ASSERT_EQ(5, batch_slice2->column(i)->length());
  }
}

TEST_F(TestRecordBatch, AddColumn) {
  const int length = 10;

  auto field1 = field("f1", int32());
  auto field2 = field("f2", uint8());
  auto field3 = field("f3", int16());

  auto schema1 = ::arrow::schema({field1, field2});
  auto schema2 = ::arrow::schema({field2, field3});
  auto schema3 = ::arrow::schema({field2});

  auto array1 = MakeRandomArray<Int32Array>(length);
  auto array2 = MakeRandomArray<UInt8Array>(length);
  auto array3 = MakeRandomArray<Int16Array>(length);

  auto batch1 = RecordBatch::Make(schema1, length, {array1, array2});
  auto batch2 = RecordBatch::Make(schema2, length, {array2, array3});
  auto batch3 = RecordBatch::Make(schema3, length, {array2});

  const RecordBatch& batch = *batch3;
  std::shared_ptr<RecordBatch> result;

  // Negative tests with invalid index
  Status status = batch.AddColumn(5, field1, array1, &result);
  ASSERT_TRUE(status.IsInvalid());
  status = batch.AddColumn(2, field1, array1, &result);
  ASSERT_TRUE(status.IsInvalid());
  status = batch.AddColumn(-1, field1, array1, &result);
  ASSERT_TRUE(status.IsInvalid());

  // Negative test with wrong length
  auto longer_col = MakeRandomArray<Int32Array>(length + 1);
  status = batch.AddColumn(0, field1, longer_col, &result);
  ASSERT_TRUE(status.IsInvalid());

  // Negative test with mismatch type
  status = batch.AddColumn(0, field1, array2, &result);
  ASSERT_TRUE(status.IsInvalid());

  ASSERT_OK(batch.AddColumn(0, field1, array1, &result));
  ASSERT_TRUE(result->Equals(*batch1));

  ASSERT_OK(batch.AddColumn(1, field3, array3, &result));
  ASSERT_TRUE(result->Equals(*batch2));

  std::shared_ptr<RecordBatch> result2;
  ASSERT_OK(batch.AddColumn(1, "f3", array3, &result2));
  ASSERT_TRUE(result2->Equals(*result));

  ASSERT_TRUE(result2->schema()->field(1)->nullable());
}

TEST_F(TestRecordBatch, RemoveColumn) {
  const int length = 10;

  auto field1 = field("f1", int32());
  auto field2 = field("f2", uint8());
  auto field3 = field("f3", int16());

  auto schema1 = ::arrow::schema({field1, field2, field3});
  auto schema2 = ::arrow::schema({field2, field3});
  auto schema3 = ::arrow::schema({field1, field3});
  auto schema4 = ::arrow::schema({field1, field2});

  auto array1 = MakeRandomArray<Int32Array>(length);
  auto array2 = MakeRandomArray<UInt8Array>(length);
  auto array3 = MakeRandomArray<Int16Array>(length);

  auto batch1 = RecordBatch::Make(schema1, length, {array1, array2, array3});
  auto batch2 = RecordBatch::Make(schema2, length, {array2, array3});
  auto batch3 = RecordBatch::Make(schema3, length, {array1, array3});
  auto batch4 = RecordBatch::Make(schema4, length, {array1, array2});

  const RecordBatch& batch = *batch1;
  std::shared_ptr<RecordBatch> result;

  // Negative tests with invalid index
  Status status = batch.RemoveColumn(3, &result);
  ASSERT_TRUE(status.IsInvalid());
  status = batch.RemoveColumn(-1, &result);
  ASSERT_TRUE(status.IsInvalid());

  ASSERT_OK(batch.RemoveColumn(0, &result));
  ASSERT_TRUE(result->Equals(*batch2));

  ASSERT_OK(batch.RemoveColumn(1, &result));
  ASSERT_TRUE(result->Equals(*batch3));

  ASSERT_OK(batch.RemoveColumn(2, &result));
  ASSERT_TRUE(result->Equals(*batch4));
}

TEST_F(TestRecordBatch, RemoveColumnEmpty) {
  const int length = 10;

  auto field1 = field("f1", int32());
  auto schema1 = ::arrow::schema({field1});
  auto array1 = MakeRandomArray<Int32Array>(length);
  auto batch1 = RecordBatch::Make(schema1, length, {array1});

  std::shared_ptr<RecordBatch> empty;
  ASSERT_OK(batch1->RemoveColumn(0, &empty));
  ASSERT_EQ(batch1->num_rows(), empty->num_rows());

  std::shared_ptr<RecordBatch> added;
  ASSERT_OK(empty->AddColumn(0, field1, array1, &added));
  ASSERT_TRUE(added->Equals(*batch1));
}

class TestTableBatchReader : public TestBase {};

TEST_F(TestTableBatchReader, ReadNext) {
  ArrayVector c1, c2;

  auto a1 = MakeRandomArray<Int32Array>(10);
  auto a2 = MakeRandomArray<Int32Array>(20);
  auto a3 = MakeRandomArray<Int32Array>(30);
  auto a4 = MakeRandomArray<Int32Array>(10);

  auto sch1 = arrow::schema({field("f1", int32()), field("f2", int32())});

  std::vector<std::shared_ptr<Column>> columns;

  std::shared_ptr<RecordBatch> batch;

  columns = {column(sch1->field(0), {a1, a4, a2}), column(sch1->field(1), {a2, a2})};
  auto t1 = Table::Make(sch1, columns);

  TableBatchReader i1(*t1);

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_EQ(10, batch->num_rows());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_EQ(10, batch->num_rows());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_EQ(20, batch->num_rows());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_EQ(nullptr, batch);

  columns = {column(sch1->field(0), {a1}), column(sch1->field(1), {a4})};
  auto t2 = Table::Make(sch1, columns);

  TableBatchReader i2(*t2);

  ASSERT_OK(i2.ReadNext(&batch));
  ASSERT_EQ(10, batch->num_rows());

  // Ensure non-sliced
  ASSERT_EQ(a1->data().get(), batch->column_data(0).get());
  ASSERT_EQ(a4->data().get(), batch->column_data(1).get());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_EQ(nullptr, batch);
}

TEST_F(TestTableBatchReader, Chunksize) {
  auto a1 = MakeRandomArray<Int32Array>(10);
  auto a2 = MakeRandomArray<Int32Array>(20);
  auto a3 = MakeRandomArray<Int32Array>(10);

  auto sch1 = arrow::schema({field("f1", int32())});
  auto t1 = Table::Make(sch1, {column(sch1->field(0), {a1, a2, a3})});

  TableBatchReader i1(*t1);

  i1.set_chunksize(15);

  std::shared_ptr<RecordBatch> batch;
  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_OK(batch->Validate());
  ASSERT_EQ(10, batch->num_rows());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_OK(batch->Validate());
  ASSERT_EQ(15, batch->num_rows());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_OK(batch->Validate());
  ASSERT_EQ(5, batch->num_rows());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_OK(batch->Validate());
  ASSERT_EQ(10, batch->num_rows());

  ASSERT_OK(i1.ReadNext(&batch));
  ASSERT_EQ(nullptr, batch);
}

}  // namespace arrow


text:
layout: docwithnav-paas
title: FAQ
description: ThingsBoard FAQ

---

{% assign docsPrefix = "paas/" %}
{% include docs/faq.md %}


text:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <!-- Name Label -->

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#008cba"
        android:textSize="14sp" />

  	<TextView
        android:id="@+id/state"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#acacac"
        android:duplicateParentState='true' />

</LinearLayout>