text:
var app = {},file ={},util={},count= 1,seq=1;
var treeEditor=null,docEditor=null
//DONE save ctrl +s | time to save
//DONE drag the bar
//DONE save ok. tips
//DONE click not worked finxed it
//DONE click to display
//DONE change title you have to chage the file list display
//DONE delete json file
//TODO changed title ,but the jsonlist is not changed.
//...

var storage=null;
if (chrome.storage){
//if (window.localStorage){
    storage=chrome.storage.local;
    storage.setItem=function(k,value){
        var o={};
        o[k]=value;
        console.warn("set "+ k +":"+value);
        storage.set(o,function(){});
    }

    storage.removeItem=function(key){
        storage.remove(key)
    }
}else{
    storage=window.localStorage;
}

var TITLE_SEQ="json.title.seq";
var CURRENT_JSON_ID="json.current.id"
var JSON_ID_LIST="json.id.list"
util.getJsonId=function(){
    var now=new Date()
    var year=now.getFullYear();
    var month=now.getMonth()+1;
    var date=now.getDate();
    var hour=now.getHours();
    var minute=now.getMinutes();
    var second=now.getSeconds();
    return "file."+year+month+date+hour+minute+second+count++;

}

util.getSeq=function(){

    return  seq++;
}

util.showTips=function(msg){
    $("#tips").text(msg)
    $("#tips").show();
    $("#tips").fadeOut(3000);
}

util.getTitleID= function (id) {
    return id+".title";
}

util.subTitleID= function (id_title) {
    //return id+".title";
    return id_title.substr(0,id_title.length-".title".length);
}

util.getContentID= function (id) {
    return id+".content";
}

util.substr20= function (str) {
    if(str.length>20) {
        return str.substr(0, 20)+"...";
    }else{
        return str;
    }
}

app.docToTree=function (){
    var json= docEditor.get()
    treeEditor.set(json)

}

app.treeToDoc=function (){
    var json= treeEditor.get()
    docEditor.set(json)

}

app.clickItem= function (){

    $("#id_json_list").find("a").removeClass("active");
    $(this).addClass("active");

    var jsonid=$(this).attr("json-id");
    app.showCurrentJson(jsonid);
}

//init list
app.addInitASpanHtml2List= function (id, title) {
    $(""+util.substr20(title)+" x  ").appendTo($("#id_json_list"));
}

//add
app.addASpanHtml2List= function (id, title) {

    $(""+util.substr20(title)+"x ").prependTo($("#id_json_list"));
}

/**
 * fileNameList=  id;id;id
 * currentJsonId =  fileid
 *
 * file.id.title     = id
 * file.id.content =xxxxx
 * inited = false|true
 */
app.loadFileList=function(){
    if(!storage){
        alert("your web browse not support localStorage!");
        return;
    }

    //if(!storage.hasOwnProperty("inited")){
    //    file.myJsonEditorInit()
    //}

    storage.get(JSON_ID_LIST,function(ids){

        if(typeof(ids[JSON_ID_LIST])=="undefined"){
            file.myJsonEditorInit();
        }

        var idss = ids[JSON_ID_LIST].split(";");
        console.info("idss: "+ids[JSON_ID_LIST]);
        for( index in idss){
            var id = idss[index];
            storage.get(util.getTitleID(id), function (obj) {

                for(var o in obj){
                    var thisid=util.subTitleID(o);
                    var thisname=obj[o];
                    app.addInitASpanHtml2List(thisid,thisname);

                }

            })

        }
    })

    storage.get(CURRENT_JSON_ID,function(id){
        app.showCurrentJson(id[CURRENT_JSON_ID])
    })

}

//load current and save
app.showCurrentJson=function(jsonid){

    var jsonid_title=jsonid+".title";

    storage.get(jsonid_title,function(object){

        if(typeof(object[jsonid_title])=="undefined"){

            storage.get(JSON_ID_LIST,function(idslist){
                //console.debug(idslist);
                if(typeof(idslist[JSON_ID_LIST])=="undefined" || idslist[JSON_ID_LIST].length==0){

                        util.showTips("You delete All JSON File...");

                    }else{
                        app.showCurrentJson(idslist[JSON_ID_LIST].split(";")[0]);
                    }
            })

        }else{

            $("#json_title").val(object[jsonid_title]);
            storage.get(jsonid+".content",function(object){
                docEditor.set(JSON.parse(object[jsonid+".content"]));
            });

            storage.setItem(CURRENT_JSON_ID,jsonid);//set
        }
    })

}

app.save=function(){
    try{
        docEditor.get()
    }catch(e){
        util.showTips("Your json have errors. pls check..")
        return ;
    }

    storage.get(CURRENT_JSON_ID, function (id) {
        file.save(id[CURRENT_JSON_ID],$("#json_title").val(),docEditor.get());

        var list= $("#id_json_list").find("a").filter(function(a){return $(this).attr('json-id')==id[CURRENT_JSON_ID]});
        if(list.length==0){
            util.showTips("Not this Json Doc ,Not find this id .");
        }

        var alink=list[0];
        $(alink).find(".flag").text(util.substr20($("#json_title").val()));

        util.showTips("saved...");

    });

}

//init a json
file.myJsonEditorInit =function (){
    // set json
    var json = {
        "Array": [1, 2, 3],
        "Boolean": true,
        "Null": null,
        "Number": 123,
        "Object": {
            "a": "b",
            "c": "d"
        },
        "String": "Hello World"
    };

    docEditor.set(json)
    var fileid=util.getJsonId()
    storage.setItem("inited",true);
    storage.setItem(CURRENT_JSON_ID,fileid);
    storage.setItem(JSON_ID_LIST,fileid);
    storage.setItem(TITLE_SEQ,0);
    file.save(fileid,"test",json)
}

file.addJson=function(id,name,json){

    storage.get(JSON_ID_LIST, function (ids) {
        storage.setItem(JSON_ID_LIST,id+";"+ids[JSON_ID_LIST]);
        storage.setItem(CURRENT_JSON_ID,id);
        file.save(id,name,json);
    })

}

//to disk
file.save=function(id,title,json){

    storage.setItem(id+".title",title);
    storage.setItem(id+".content",JSON.stringify(json));

}

file.delete=function(id){
    //remove id from list
    storage.get(JSON_ID_LIST, function (ids) {

        var idlist = ids[JSON_ID_LIST];
        var arrIds =idlist.split(";").filter(function(e){if(e==id)return false ; else return true;})
        storage.setItem(JSON_ID_LIST,arrIds.join(";"))

        storage.removeItem(id+".title");
        storage.removeItem(id+".content");
    })

}

app.deleteJson=function(){
    var jsonid= $(this).attr("json-id");
    file.delete(jsonid);
    $(this).parent().remove();

    storage.get(CURRENT_JSON_ID, function (id) {
        app.showCurrentJson(id[CURRENT_JSON_ID]);
    })

}

app.addJson=function (){

    var json_id= util.getJsonId()
    $("#json_title").val("Title "+util.getSeq());

    file.addJson(json_id,$("#json_title").val(),{})
    app.addASpanHtml2List(json_id,$("#json_title").val());
    //

    docEditor.set();
    treeEditor.set();

    $("#json_title").focus();
}

app.bindingDrag=function(){

    var drag=$("#id_drag_button");

    x = 0;

    drag.mousedown(function(e){

        this.setCapture ? (

            this.setCapture(),

                this.onmousemove = function(ev) {
                    mouseMove(ev || event);
                },
                this.onmouseup = mouseUp
        ) : (

            $(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp)
        );

        e.preventDefault();
    })

    function mouseMove(e) {
        x = e.clientX - drag[0].offsetWidth - $("#docEditor").width() ;

        $("#docEditor").width( $("#docEditor").width() + x + 'px');
        $("#treeEditor").width( $("#treeEditor").width() - x + 'px');
    }

    function mouseUp() {
        this.releaseCapture ? (
            this.releaseCapture(),
                this.onmousemove = this.onmouseup = null
        ) : (
            $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp)
        );
    }

}

app.load=function() {
    var codeDoc = document.getElementById("docEditor");
    var codeoptions = {
        "mode": 'code',
        "search": true

    };

    docEditor = new JSONEditor(codeDoc, codeoptions);

    var viewoptions = {
        "mode": "tree",
        "search": true,
        modes: ['code', 'form', 'text', 'tree', 'view'],
        error: function (err) {
            alert(err.toString());
        }
    };

    var treeDoc = document.getElementById("treeEditor");
    treeEditor = new JSONEditor(treeDoc, viewoptions);

    $("#id_to_tree").on("click", app.docToTree);
    $("#id_to_doc").on("click", app.treeToDoc);
    $("#id_json_add_btn").on("click", app.addJson);
    $("#id_json_save").on("click", app.save);
    app.loadFileList();
    $("#id_json_list").on("click", "a", app.clickItem);
    $("#id_json_list").on("click", ".badge", app.deleteJson);

    document.onkeydown =  function(e){

        var t = e.which ? e.which : e.keyCode || 0;

        if (e.ctrlKey)switch (t) {
            case 83:
                app.save();
                return false;
                break;
        }}

    app.bindingDrag()

}

app.load();


text:
from __future__ import unicode_literals

from stackdio.api.environments import models
from stackdio.core.mixins import ParentRelatedMixin
from stackdio.core.permissions import StackdioPermissionsPermissions

class EnvironmentRelatedMixin(ParentRelatedMixin):
    parent_queryset = models.Environment.objects.all()
    parent_lookup_field = 'name'

    def get_environment(self):
        return self.get_parent_object()

class EnvironmentPermissionsMixin(EnvironmentRelatedMixin):
    permission_classes = (StackdioPermissionsPermissions,)

    def get_permissioned_object(self):
        return self.get_parent_object()

redpajama_set_name: RedPajamaGithub


text:
import sys
import unittest

from webkitpy.common.system import outputcapture
from webkitpy.common.system import stack_utils

def current_thread_id():
    thread_id, _ = sys._current_frames().items()[0]
    return thread_id

class Test(unittest.TestCase):
    def test_find_thread_stack_found(self):
        thread_id = current_thread_id()
        found_stack = stack_utils._find_thread_stack(thread_id)
        self.assertNotEqual(found_stack, None)

    def test_find_thread_stack_not_found(self):
        found_stack = stack_utils._find_thread_stack(0)
        self.assertEqual(found_stack, None)

    def test_log_thread_state(self):
        msgs = []

        def logger(msg):
            msgs.append(msg)

        thread_id = current_thread_id()
        stack_utils.log_thread_state(logger, "test-thread", thread_id,
                                     "is tested")
        self.assertTrue(msgs)

    def test_log_traceback(self):
        msgs = []

        def logger(msg):
            msgs.append(msg)

        try:
            raise ValueError
        except:
            stack_utils.log_traceback(logger, sys.exc_info()[2])
        self.assertTrue(msgs)

if __name__ == '__main__':
    unittest.main()


text:
<?php
global $post;

	// Revolution Slider if alias is provided and plugin is installed
	$rev_slider_alias = get_post_meta( $post->ID, 'REAL_HOMES_rev_slider_alias', true );
	if ( function_exists( 'putRevSlider' ) && ( ! empty( $rev_slider_alias ) ) ) {
		putRevSlider( $rev_slider_alias );
	} else {

    // Banner Image
    $banner_image_path = "";
    $banner_image_id = get_post_meta( $post->ID, 'REAL_HOMES_page_banner_image', true );
    if($banner_image_id){
        $banner_image_path = wp_get_attachment_url($banner_image_id);
    }else{
        $banner_image_path = get_default_banner();
    }

    // Banner Title
    $banner_title = get_post_meta( $post->ID, 'REAL_HOMES_banner_title', true );
    if(empty($banner_title)){
        $banner_title = get_the_title($post->ID);
    }

    // Banner Sub Title
    $banner_sub_title = get_post_meta( $post->ID, 'REAL_HOMES_banner_sub_title', true );

    ?>
    <div class="page-head" style="background-repeat: no-repeat;background-position: center top;background-image: url('<?php echo esc_url( $banner_image_path ); ?>'); background-size: cover; ">
        <?php if(!('true' == get_option('theme_banner_titles'))): ?>

<?php echo esc_html( $banner_title ); ?>

                <?php
                if ( $banner_sub_title ) {
                  ?>
<?php echo esc_html( $banner_sub_title ); ?>
<?php
                }
                ?>

        <?php endif; ?>

    <?php

    }
?>


text:
module Ransack
  module Helpers
    module FormHelper

      # +search_form_for+
      #
      #   <%= search_form_for(@q) do |f| %>
      #
      def search_form_for(record, options = {}, &proc)
        if record.is_a? Ransack::Search
          search = record
          options[:url] ||= polymorphic_path(
            search.klass, format: options.delete(:format)
            )
        elsif record.is_a?(Array) &&
        (search = record.detect { |o| o.is_a?(Ransack::Search) })
          options[:url] ||= polymorphic_path(
            options_for(record), format: options.delete(:format)
            )
        else
          raise ArgumentError,
          'No Ransack::Search object was provided to search_form_for!'
        end
        options[:html] ||= {}
        html_options = {
          class:  html_option_for(options[:class], search),
          id:     html_option_for(options[:id], search),
          method: :get
        }
        options[:as] ||= Ransack.options[:search_key]
        options[:html].reverse_merge!(html_options)
        options[:builder] ||= FormBuilder

        form_for(record, options, &proc)
      end

      # +sort_link+
      #
      #   <%= sort_link(@q, :name, [:name, 'kind ASC'], 'Player Name') %>
      #
      def sort_link(search_object, attribute, *args)
        search, routing_proxy = extract_search_and_routing_proxy(search_object)
        unless Search === search
          raise TypeError, 'First argument must be a Ransack::Search!'
        end
        s = SortLink.new(search, attribute, args, params)
        link_to(s.name, url(routing_proxy, s.url_options), s.html_options(args))
      end

      private

        def options_for(record)
          record.map { |r| parse_record(r) }
        end

        def parse_record(object)
          return object.klass if object.is_a?(Ransack::Search)
          object
        end

        def html_option_for(option, search)
          return option.to_s if option.present?
          "#{search.klass.to_s.underscore}_search"
        end

        def extract_search_and_routing_proxy(search)
          return [search[1], search[0]] if search.is_a?(Array)
          [search, nil]
        end

        def url(routing_proxy, options_for_url)
          if routing_proxy && respond_to?(routing_proxy)
            send(routing_proxy).url_for(options_for_url)
          else
            url_for(options_for_url)
          end
        end

      class SortLink
        def initialize(search, attribute, args, params)
          @search         = search
          @params         = parameters_hash(params)
          @field          = attribute.to_s
          @sort_fields    = extract_sort_fields_and_mutate_args!(args).compact
          @current_dir    = existing_sort_direction
          @label_text     = extract_label_and_mutate_args!(args)
          @options        = extract_options_and_mutate_args!(args)
          @hide_indicator = @options.delete(:hide_indicator) ||
                            Ransack.options[:hide_sort_order_indicators]
          @default_order  = @options.delete :default_order
        end

        def name
          [ERB::Util.h(@label_text), order_indicator]
          .compact
          .join(' '.freeze)
          .html_safe
        end

        def url_options
          @params.merge(
            @options.merge(
              @search.context.search_key => search_and_sort_params))
        end

        def html_options(args)
          html_options = extract_options_and_mutate_args!(args)
          html_options.merge(
            class: [['sort_link'.freeze, @current_dir], html_options[:class]]
                   .compact.join(' '.freeze)
          )
        end

        private

          def parameters_hash(params)
            return params unless params.instance_variable_defined?(:@parameters)
            params.instance_variable_get(:@parameters)
          end

          def extract_sort_fields_and_mutate_args!(args)
            return args.shift if args[0].is_a?(Array)
            [@field]
          end

          def extract_label_and_mutate_args!(args)
            return args.shift if args[0].is_a?(String)
            Translate.attribute(@field, context: @search.context)
          end

          def extract_options_and_mutate_args!(args)
            return args.shift.with_indifferent_access if args[0].is_a?(Hash)
            {}
          end

          def search_and_sort_params
            search_params.merge(s: sort_params)
          end

          def search_params
            parameters_hash(@params[@search.context.search_key]).presence || {}
          end

          def sort_params
            sort_array = recursive_sort_params_build(@sort_fields)
            return sort_array[0] if sort_array.length == 1
            sort_array
          end

          def recursive_sort_params_build(fields)
            return [] if fields.empty?
            [parse_sort(fields[0])] + recursive_sort_params_build(fields.drop 1)
          end

          def parse_sort(field)
            attr_name, new_dir = field.to_s.split(/\s+/)
            if no_sort_direction_specified?(new_dir)
              new_dir = detect_previous_sort_direction_and_invert_it(attr_name)
            end
            "#{attr_name} #{new_dir}"
          end

          def detect_previous_sort_direction_and_invert_it(attr_name)
            if sort_dir = existing_sort_direction(attr_name)
              direction_text(sort_dir)
            else
              default_sort_order(attr_name) || 'asc'.freeze
            end
          end

          def existing_sort_direction(f = @field)
            return unless sort = @search.sorts.detect { |s| s && s.name == f }
            sort.dir
          end

          def default_sort_order(attr_name)
            return @default_order[attr_name] if Hash === @default_order
            @default_order
          end

          def order_indicator
            return if @hide_indicator || no_sort_direction_specified?
            direction_arrow
          end

          def no_sort_direction_specified?(dir = @current_dir)
            !['asc'.freeze, 'desc'.freeze].freeze.include?(dir)
          end

          def direction_arrow
            return Constants::DESC_ARROW if @current_dir == 'desc'.freeze
            Constants::ASC_ARROW
          end

          def direction_text(dir)
            return 'asc'.freeze if dir == 'desc'.freeze
            'desc'.freeze
          end
      end
    end
  end
end


text:
struct my_node
{
   my_node(int i = 0)
      :  int_(i)
   {}
   my_node *parent_, *left_, *right_;
   int balance_;
   //other members
   int      int_;
};

//Define our own avltree_node_traits
struct my_avltree_node_traits
{
   typedef my_node                                    node;
   typedef my_node *                                  node_ptr;
   typedef const my_node *                            const_node_ptr;
   typedef int                                        balance;

   static node_ptr get_parent(const_node_ptr n)       {  return n->parent_;   }
   static void set_parent(node_ptr n, node_ptr parent){  n->parent_ = parent; }
   static node_ptr get_left(const_node_ptr n)         {  return n->left_;     }
   static void set_left(node_ptr n, node_ptr left)    {  n->left_ = left;     }
   static node_ptr get_right(const_node_ptr n)        {  return n->right_;    }
   static void set_right(node_ptr n, node_ptr right)  {  n->right_ = right;   }
   static balance get_balance(const_node_ptr n)       {  return n->balance_;  }
   static void set_balance(node_ptr n, balance b)     {  n->balance_ = b;     }
   static balance negative()                          {  return -1; }
   static balance zero()                              {  return 0;  }
   static balance positive()                          {  return 1;  }
};

struct node_ptr_compare
{
   bool operator()(const my_node *a, const my_node *b)
   {  return a->int_ < b->int_;  }
};

int main()
{
   typedef boost::intrusive::avltree_algorithms<my_avltree_node_traits> algo;
   my_node header, two(2), three(3);

   //Create an empty avltree container:
   //"header" will be the header node of the tree
   algo::init_header(&header);

   //Now insert node "two" in the tree using the sorting functor
   algo::insert_equal_upper_bound(&header, &two, node_ptr_compare());

   //Now insert node "three" in the tree using the sorting functor
   algo::insert_equal_lower_bound(&header, &three, node_ptr_compare());

   //Now take the first node (the left node of the header)
   my_node *n = header.left_;
   assert(n == &two);

   //Now go to the next node
   n = algo::next_node(n);
   assert(n == &three);

   //Erase a node just using a pointer to it
   algo::unlink(&two);

   //Erase a node using also the header (faster)
   algo::erase(&header, &three);
   return 0;
}

//]


text:
> Regular expression for matching the whitespace in a string.

## Install

Install with [npm](https://www.npmjs.com/)

```sh
$ npm i whitespace-regex --save
```

## Usage

```js
var regex = require('whitespace-regex')();

regex.test('      foo    ');
//=> false

regex.test('             ');
//=> true
```

## Other regex projects

* [copyright-regex](https://www.npmjs.com/package/copyright-regex): Regex for matching and parsing copyright statements. | [homepage](https://github.com/regexps/copyright-regex)
* [is-equal-regex](https://www.npmjs.com/package/is-equal-regex): Returns true if regular expression A is equal to regex B. Compares the expression and… [more](https://www.npmjs.com/package/is-equal-regex) | [homepage](https://github.com/jonschlinkert/is-equal-regex)
* [todo-regex](https://www.npmjs.com/package/todo-regex): Regular expression for matching TODO statements in a string. | [homepage](https://github.com/regexps/todo-regex)

## Running tests

Install dev dependencies:

```sh
$ npm i -d && npm test
```

## Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/regexps/whitespace-regex/issues/new).

## Author

**Jon Schlinkert**

+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)

## License

Copyright © 2015 Jon Schlinkert
Released under the MIT license.

***

_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on September 22, 2015._


text:
package plow.util;

import java.util.ArrayList;

import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;

public class ObservableMapValues<T> extends com.sun.javafx.collections.ObservableListWrapper<T> {

	public ObservableMapValues(final ObservableMap<?, T> map) {
		super(new ArrayList<>(map.values()));
		map.addListener(new MapChangeListener<Object, T>() {

			@Override
			public void onChanged(
					final javafx.collections.MapChangeListener.Change<? extends Object, ? extends T> change) {
				if (change.wasAdded()) {
					add(change.getValueAdded());
				}
				if (change.wasRemoved()) {
					remove(change.getValueRemoved());
				}
			}

		});
	}

}


text:
import {CSSModule} from '../index';

interface Props {
  caret?: boolean;
  className?: string;
  cssModule?: CSSModule;
  disabled?: boolean;
  onClick?: React.MouseEventHandler<any>;
  'data-toggle'?: string;
  'aria-haspopup'?: boolean;
  split?: boolean;
  tag?: React.ReactType;
  nav?: boolean;
  color?: string;
  size?: string;
}

declare var DropdownToggle: React.StatelessComponent<Props>;
export default DropdownToggle;


text:
package exnihilocreatio.tiles;

import exnihilocreatio.rotationalPower.CapabilityRotationalMember;
import exnihilocreatio.rotationalPower.IRotationalPowerMember;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraftforge.common.capabilities.Capability;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class TileStoneAxle extends BaseTileEntity implements ITickable, IRotationalPowerMember {
    public float rotationValue = 0;
    public float perTickEffective = 0F;

    public EnumFacing facing = EnumFacing.NORTH;

    private int counter = -1;

    @Override
    public void update() {
        counter++;

        if (counter > 0 && counter % 10 == 0) {
            float lastPerTickEffective = perTickEffective;
            perTickEffective = calcEffectivePerTickRotation(world, pos, facing);

            if (lastPerTickEffective != perTickEffective) {
                markDirty();
            }
            counter = 0;
        }

        if (world.isRemote) {
            rotationValue += perTickEffective;
        }
    }

    @Override
    @Nonnull
    public NBTTagCompound writeToNBT(NBTTagCompound tag) {
        if (facing != null)
            tag.setString("facing", facing.getName());
        tag.setFloat("rot", rotationValue);

        return super.writeToNBT(tag);
    }

    @Override
    public void readFromNBT(NBTTagCompound tag) {
        super.readFromNBT(tag);
        if (tag.hasKey("facing"))
            facing = EnumFacing.byName(tag.getString("facing"));
        if (tag.hasKey("rot"))
            rotationValue = tag.getFloat("rot");
    }

    @Override
    public float getOwnRotation() {
        return 0;
    }

    @Override
    public float getEffectivePerTickRotation(EnumFacing direction) {
        if (facing == direction) {
            return perTickEffective;
        } else {
            return 0;
        }
    }

    @Override
    public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
        return capability == CapabilityRotationalMember.ROTIONAL_MEMBER && facing == this.facing || super.hasCapability(capability, facing);
    }

    @Nullable
    @Override
    public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
        if (capability == CapabilityRotationalMember.ROTIONAL_MEMBER && facing == this.facing)
            return CapabilityRotationalMember.ROTIONAL_MEMBER.cast(this);
        return super.getCapability(capability, facing);
    }

    @Override
    public void setEffectivePerTickRotation(float rotation) {
        perTickEffective = rotation;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">

        <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="../includes/main.css" type="text/css">
        <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
        <title>Apache CloudStack | The Power Behind Your Cloud</title>

						Apache CloudStack 4.14.1.0-SNAPSHOT Root Admin API Reference

listZones

Lists zones

Request parameters

                                            Parameter Name	Description	Required

                                            available	true if you want to retrieve all available Zones. False if you only want to return the Zones from which you have at least one VM. Default is false.	false

                                            domainid	the ID of the domain associated with the zone	false

                                            id	the ID of the zone	false

                                            keyword	List by keyword	false

                                            name	the name of the zone	false

                                            networktype	the network type of the zone that the virtual machine belongs to	false

                                            page		false

                                            pagesize		false

                                            showcapacities	flag to display the capacity of the zones	false

                                            tags	List zones by resource tags (key/value pairs)	false

Response Tags

                                            Response Name	Description

                                            id	Zone id

                                            allocationstate	the allocation state of the cluster

                                            description	Zone description

                                            dhcpprovider	the dhcp Provider for the Zone

                                            displaytext	the display text of the zone

                                            dns1	the first DNS for the Zone

                                            dns2	the second DNS for the Zone

                                            domain	Network domain name for the networks in the zone

                                            domainid	the UUID of the containing domain, null for public zones

                                            domainname	the name of the containing domain, null for public zones

                                            guestcidraddress	the guest CIDR address for the Zone

                                            internaldns1	the first internal DNS for the Zone

                                            internaldns2	the second internal DNS for the Zone

                                            ip6dns1	the first IPv6 DNS for the Zone

                                            ip6dns2	the second IPv6 DNS for the Zone

                                            localstorageenabled	true if local storage offering enabled, false otherwise

                                            name	Zone name

                                            networktype	the network type of the zone; can be Basic or Advanced

                                            resourcedetails	Meta data associated with the zone (key/value pairs)

                                            securitygroupsenabled	true if security groups support is enabled, false otherwise

                                            zonetoken	Zone Token

                                            capacity(*)	the capacity of the Zone

                                                capacityallocated	the capacity currently in allocated

                                                capacitytotal	the total capacity available

                                                capacityused	the capacity currently in use

                                                clusterid	the Cluster ID

                                                clustername	the Cluster name

                                                name	the capacity name

                                                percentused	the percentage of capacity currently in use

                                                podid	the Pod ID

                                                podname	the Pod name

                                                type	the capacity type

                                                zoneid	the Zone ID

                                                zonename	the Zone name

                                            tags(*)	the list of resource tags associated with zone.

                                                account	the account associated with the tag

                                                customer	customer associated with the tag

                                                domain	the domain associated with the tag

                                                domainid	the ID of the domain associated with the tag

                                                key	tag key name

                                                project	the project name where tag belongs to

                                                projectid	the project id the tag belongs to

                                                resourceid	id of the resource

                                                resourcetype	resource type

                                                value	tag value

                            Copyright © 2015 The Apache Software Foundation, Licensed under the
                   Apache License, Version 2.0.

                                            Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo  and the Apache feather logo are trademarks of The Apache Software Foundation.


text:
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label

class SelectingDataSet(Screen):
    def __init__(self, **kwargs):
        super(SelectingDataSet, self).__init__(**kwargs)

        layout = FloatLayout(cols=3, row_force_default=True, row_default_height=40)

        # instantiate the buttons
        cafeButton = Button(text='CAFE', size_hint=(.2, .1), pos_hint={'x': .2, 'center_y': .6})
        pofaButton = Button(text='POFA', size_hint=(.2, .1), pos_hint={'center_x': .7, 'center_y': .6})
        loadButton = Button(text='Next', size_hint=(.25, .15), pos_hint={'x': .75, 'y': 0})

        # add buttons to the layout
        layout.add_widget(cafeButton)
        layout.add_widget(pofaButton)
        layout.add_widget(loadButton)

        # instantiate the labels
        title = Label(text="Select one of the data sets to load images", font_size=30,
                      pos_hint={'x': 0, 'center_y': .9})
        cafeDescription = Label(text="*CAFE Description Here*", font_size=15, pos_hint={'x': -.2, 'center_y': .5})
        pofaDescription = Label(text="*POFA Description Here*", font_size=15, pos_hint={'x': .2, 'center_y': .5})

        # add labels to the layout
        layout.add_widget(title)
        layout.add_widget(cafeDescription)
        layout.add_widget(pofaDescription)

        # binding the buttons to the clk method
        cafeButton.bind(on_press=self.clk)
        pofaButton.bind(on_press=self.clk)
        loadButton.bind(on_press=self.changer)

        self.add_widget(layout)

    def changer(self, *args):
        self.manager.current = 'screen2'

    def clk(self, obj):
        print("Hello World!")


text:
import pickle
import json
import os

pickle_filenames = [filename for filename in os.listdir('.') if filename.endswith('.pickle')]
for pickle_filename in pickle_filenames:
    with open(pickle_filename, 'r') as file:
        data = pickle.load(file)
    with open('{}.json'.format(pickle_filename.split('.pickle')[0]), 'w') as json_file:
        json_file.write(json.dumps(data, indent=4, default=str))


text:
<?php

declare(strict_types=1);

namespace Talesweaver\Domain;

use DateTimeImmutable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use DomainException;
use Ramsey\Uuid\UuidInterface;
use Talesweaver\Domain\Traits\CreatedByTrait;
use Talesweaver\Domain\Traits\PositionableTrait;
use Talesweaver\Domain\Traits\PublishableTrait;
use Talesweaver\Domain\Traits\TimestampableTrait;
use Talesweaver\Domain\Traits\TranslatableTrait;
use Talesweaver\Domain\ValueObject\LongText;
use Talesweaver\Domain\ValueObject\ShortText;

class Chapter implements Positionable
{
    use CreatedByTrait, PositionableTrait, PublishableTrait, TimestampableTrait, TranslatableTrait;

    /**
     * @var UuidInterface
     */
    private $id;

    /**
     * @var ShortText
     */
    private $title;

    /**
     * @var LongText|null
     */
    private $preface;

    /**
     * @var Book|null
     */
    private $book;

    /**
     * @var Collection<Scene>
     */
    private $scenes;

    public function __construct(UuidInterface $id, ShortText $title, ?LongText $preface, ?Book $book, Author $author)
    {
        $this->assertCorrectConstructorData($title, $author, $book);

        $this->id = $id;
        $this->title = $title;
        $this->preface = $preface;
        $this->book = $book;
        $this->position = 0;
        $this->scenes = new ArrayCollection();
        $this->translations = new ArrayCollection();
        $this->createdBy = $author;
        $this->createdAt = new DateTimeImmutable();
        $this->publications = new ArrayCollection();
    }

    public function __toString()
    {
        return (string) $this->title;
    }

    /**
     * @param ShortText $title
     * @param LongText|null $preface
     * @param Book|null $book
     * @return void
     */
    public function edit(ShortText $title, ?LongText $preface, ?Book $book): void
    {
        $this->assertCorrectEditionData($title, $book);

        $this->title = $title;
        $this->preface = $preface;
        $this->book = $book;

        $this->update();
    }

    public function getId(): UuidInterface
    {
        return $this->id;
    }

    public function getTitle(): ShortText
    {
        return $this->title;
    }

    public function getPreface(): ?LongText
    {
        return $this->preface;
    }

    public function getBook(): ?Book
    {
        return $this->book;
    }

    public function setBook(?Book $book): void
    {
        $this->book = $book;
    }

    public function getScenes(): array
    {
        return $this->scenes->toArray();
    }

    public function addScene(Scene $scene): void
    {
        if (true === $this->scenes->contains($scene)) {
            return;
        }

        $this->scenes->add($scene);
    }

    public function removeScene(Scene $scene): void
    {
        $this->scenes->removeElement($scene);
    }

    private function assertCorrectConstructorData(ShortText $title, Author $author, ?Book $book): void
    {
        if (null !== $book && $author->getId() !== $book->getCreatedBy()->getId()) {
            throw new DomainException(sprintf(
                'Chapter for user "%s" with title "%s" cannot be assigned to book "%s", whose author is "%s"',
                $author->getId()->toString(),
                $title,
                $book->getId()->toString(),
                $book->getCreatedBy()->getId()->toString()
            ));
        }
    }

    private function assertCorrectEditionData(ShortText $title, ?Book $book): void
    {
        if (null !== $book && $this->createdBy->getId() !== $book->getCreatedBy()->getId()) {
            throw new DomainException(sprintf(
                'Chapter for user "%s" with title "%s" cannot be assigned to book "%s", whose author is "%s"',
                $this->createdBy->getId()->toString(),
                $title,
                $book->getId()->toString(),
                $book->getCreatedBy()->getId()->toString()
            ));
        }
    }
}


text:
package net.kleinhaneveld.fn;

import net.kleinhaneveld.fn.annotations.Eager;

import javax.annotation.Nonnull;

public class CacheSupplier<T> extends Supplier<T> implements Registerable, Flushable {
    private final Supplier<T> delegate;
    private final Broadcaster broadcaster;
    private volatile T value;

    public CacheSupplier(@Nonnull Supplier<T> delegate) {
        this.delegate = delegate;
        broadcaster = new Broadcaster();
    }

    @Eager
    @Nonnull
    @Override
    public T get() {
        T result = value;
        if (result == null) {
            synchronized (this) {
                result = value;
                if (result == null) {
                    value = result = delegate.get();
                }
            }
        }
        return result;
    }

    @Override
    public void register(@Nonnull Runner runner) {
        broadcaster.register(runner);
    }

    @Override
    public void unregister(@Nonnull Runner runner) {
        broadcaster.unregister(runner);
    }

    @Override
    public void flush() {
        value = null;
        broadcaster.run();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Common.Exceptions;
using DataSources.Attributes;
using DataSources.DataSource;
using DataSources.Exceptions;

namespace DataSources
{
    /// <summary>
    /// Manages the associated Models for a Model.
    /// </summary>
    public sealed class Associations : IDisposable
    {
        /// <summary>
        /// A list of different association types.
        /// </summary>
        private enum AssocType
        {
            /// <summary>
            /// The Model that owns all the associated models.
            /// </summary>
            OWNER,
            /// <summary>
            /// Owner has many of these model records.
            /// </summary>
            HAS_MANY,
            /// <summary>
            /// Owner belongs to this model record.
            /// </summary>
            BELONGS_TO
        }

        /// <summary>
        /// Used to hold a reference to the model.
        /// </summary>
        private class ModelRef
        {
            /// <summary>
            /// The alias for this reference.
            /// </summary>
            private string _alias;

            /// <summary>
            /// The associations type.
            /// </summary>
            private AssocType _type;

            /// <summary>
            /// The model object.
            /// </summary>
            public readonly Model Model;

            /// <summary>
            /// Constructor
            /// </summary>
            public ModelRef(string pAlias, AssocType pAssocType, Model pModel)
            {
                _alias = pAlias;
                _type = pAssocType;
                Model = pModel;
            }
        }

        /// <summary>
        /// Uses to hold the different aliases for a Model
        /// </summary>
        private class Aliases : Dictionary<string, ModelRef>
        {
        }

        /// <summary>
        ///
        /// </summary>
        private class Models : Dictionary<Type, Aliases>
        {
            new public Aliases this[Type pType]
            {
                get
                {
                    if (!ContainsKey(pType))
                    {
                        base[pType] = new Aliases();
                    }
                    return base[pType];
                }
            }
        }

        /// <summary>
        /// The list of associated models, grouped by Type.
        /// </summary>
        private readonly Models _models;

        /// <summary>
        /// A list of all aliases used (they have to remain unique).
        /// </summary>
        private readonly HashSet<string> _aliases;

        /// <summary>
        /// Accesses an association by it's type, but only if that type is used once.
        /// Otherwise an exception is thrown, and you have to use the alias.
        /// </summary>
        public Model this[Type pType]
        {
            get
            {
                if (_models[pType].Count == 0)
                {
                    throw new ModelException(string.Format("Model {0} is not associated with this model.", pType.Name));
                }
                if (_models[pType].Count == 1)
                {
                    return _models[pType].First().Value.Model;
                }

                throw new ModelException(string.Format("Model {0} has more then one association to this model.", pType.Name));
            }
        }

        /// <summary>
        /// Finds an associated model by it's alias.
        /// </summary>
        public Model this[string pAlias]
        {
            get
            {
                if (!_aliases.Contains(pAlias))
                {
                    throw new ModelException(string.Format("Alias {0} is not associated with this model.", pAlias));
                }
                foreach (var y in _models.SelectMany(pX => pX.Value.Where(pY => pY.Key == pAlias)))
                {
                    return y.Value.Model;
                }

                throw new ModelException(string.Format("Alias {0} is not associated with this model.", pAlias));
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public Associations()
        {
            _models = new Models();
            _aliases = new HashSet<string>();
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public Associations(string pFirstAlias, Model pModel)
            : this()
        {
            Attach(pModel.GetType(), pFirstAlias, AssocType.OWNER, pModel);
        }

        /// <summary>
        /// Disposes of the object.
        /// </summary>
        public void Dispose()
        {
            _aliases.Clear();
            _models.Clear();
        }

        /// <summary>
        /// Attaches the model to the owner as an associated model.
        /// </summary>
        private void Attach(Type pType, string pAlias, AssocType pAssocType, Model pModel)
        {
            if (_aliases.Add(pAlias) == false)
            {
                throw new ModelException(string.Format("Alias {0} already used.", pAlias));
            }
            _models[pType][pAlias] = new ModelRef(pAlias, pAssocType, pModel);
        }

        /// <summary>
        /// Attaches a Model as a BelongsTo
        /// </summary>
        /// <param name="pAlias"></param>
        /// <param name="pModel"></param>
        public void AttachBelongsTo(string pAlias, Model pModel)
        {
            Attach(pModel.GetType(), pAlias, AssocType.BELONGS_TO, pModel);
        }

        /// <summary>
        /// Attaches a Model to HasMany
        /// </summary>
        /// <param name="pAlias"></param>
        /// <param name="pModel"></param>
        public void AttachHasMany(string pAlias, Model pModel)
        {
            Attach(pModel.GetType(), pAlias, AssocType.HAS_MANY, pModel);
        }

        /// <summary>
        /// Detaches a Model
        /// </summary>
        public void Detach(string pAlias)
        {
            _aliases.Remove(pAlias);
            if (_models.Any(pX => pX.Value.Remove(pAlias)))
            {
                return;
            }

            throw new ModelException(string.Format("Alias {0} is not attached.", pAlias));
        }

        /// <summary>
        /// Attaches the Models defined as custom attributes in the Model class.
        /// </summary>
        /// <param name="pModel">The model to inspect</param>
        /// <param name="pDataSource"></param>
        public void CreateByAttributes(Model pModel, iDataSource pDataSource)
        {
            object[] attributes = pModel.GetType().GetCustomAttributes(typeof(HasMany), true);
            foreach (object attribute in attributes)
            {
                HasMany hm = attribute as HasMany;
                Model m = ModelRegistry.init(hm.ModelType, pDataSource);
                AttachHasMany(hm.Alias, m);
            }
        }
    }
}


text:
package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.queries.GetVdsByVdsIdParameters;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;

public class GetVdsByVdsIdQuery<P extends GetVdsByVdsIdParameters> extends QueriesCommandBase<P> {
    public GetVdsByVdsIdQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        VDS vds =
                DbFacade.getInstance()
                        .getVdsDAO()
                        .get(getParameters().getVdsId(), getUserID(), getParameters().isFiltered());

        if (vds != null) {
            vds.setCpuName(CpuFlagsManagerHandler.FindMaxServerCpuByFlags(vds.getcpu_flags(),
                    vds.getvds_group_compatibility_version()));
        }

        getQueryReturnValue().setReturnValue(vds);
    }
}


text:
> Simple carousel without any complicated stuff around it

## Why

You all know these huge jQuery carousel plugins, right?
Besides these 20kB or even more, you also have to include jQuery on your site.

I found out that I don't need jQuery in my daily life - it would make my life a bit easier but I really don't like overhead.
Don't get me wrong: Using jQuery can make sense, but not for sites that otherwise don't use much JavaScript.

So I decided to write basic JS libraries without any dependencies.

Flexisel is the first library in this series.
I also released [Flexibox](https://git.lukasbestle.com/flexijs/flexibox), a lightbox library.

## Features

- based on a list of links which can include just about any HTML content (images, text etc.) and a "stage" where the active item is transferred to
- hides the stage using a custom class name, which will get attached when the stage changes (you will do something like `opacity: 0;` combined with transitions for that class)
- automatically rotates the items in a specified interval
- can be triggered manually by the user (clicking an item) or by the developer (`Flexisel.set()` method)
- can exist multiple times on a page
- doesn't annoy the user:
	- doesn't change automatically if the user is hovering the carousel
	- doesn't change for a while after the user manually clicked on an item

## Flexisel is:

- a simple carousel framework
- ~ 1KB minified and gzipped (!) with no dependencies
- totally flexible and customizable

## Flexisel is *not*:

- packed with any CSS or graphics, so it can be highly configured
- one of these amazing 3D rotation carousels as the clickable items are separate from the "stage"
- usable out-of-the-box™
- usable in stone-age browsers (requires `document.querySelector` and `Function.bind()`)

## Usage

### HTML

```html
<section id="carousel">
	<ul>
		<li class="active">
			<a href="http://example.com/this/is/the/destination/of/the/item">
				<!-- Whatever -->
			</a>
		</li>
		<li>
			<a href="http://example.com/this/is/another/destination/of/the/item">
				<!-- Whatever -->
			</a>
		</li>
		<li>
			<a href="http://example.com/this/is/another/destination/of/the/item">
				<!-- Whatever -->
			</a>
		</li>
	</ul>
	<div class="stage">
		<a href="http://example.com/this/is/the/destination/of/the/item">
			<!-- Whatever -->
		</a>
	</div>
</section>
```

### JS

```javascript
var carousel = new Flexisel(document.getElementById('carousel'));
```

#### With custom configuration (see `flexisel.js` for documentation)

```javascript
var carousel = new Flexisel(document.getElementById('carousel'), {
	'debug':       true,
	'setCallback': function(link) { ... }
});
```

## Author

- Lukas Bestle <mail@lukasbestle.com>

## License

This project was published under the terms of the MIT license. You can find a copy [over at the repository](https://git.lukasbestle.com/flexijs/flexisel/blob/master/LICENSE.md).


text:
class dtkImage;

// /////////////////////////////////////////////////////////////////
// dtkVtWatershedFilter definition
// /////////////////////////////////////////////////////////////////

class dtkVtWatershedFilter final : public dtkAbstractWatershedFilter
{
public:
     dtkVtWatershedFilter(void);
    ~dtkVtWatershedFilter(void);

public:
    void setImage(dtkImage *image);
    void setSeed(dtkImage *seed);

    void setControlParameter(const QString& control_parameter);

public:
    dtkImage *filteredImage(void) const;

public:
    void run(void);

private:
    class dtkVtWatershedFilterPrivate *d;
};

// ///////////////////////////////////////////////////////////////////

inline dtkAbstractWatershedFilter *dtkVtWatershedFilterCreator(void)
{
    return new dtkVtWatershedFilter();
}

//
// dtkVtWatershedFilter.h ends here


text:
layout: post

title: No virtual reality in the mission field!
subtitle:
cover-image: 2018/no-virtual-reality-3x1.jpg

categories:
 - Binuangan

author:
 name: Jim Webb
 bio: Director of Laymen Ministries Philippines, Inc. and Katutubo Excel Schools, Inc.
 image: jim.jpg
---

In the mission field growth is both a blessing and a challenge. Blessings occur when we are able to share the love of god with someone in need of spiritual or material help. Blessings also occur as we grow in the process of serving our fellowman. In this service environment, we naturally draw closer to those we serve and better understand their reality.

In the mission field, we deal with real people, with real life challenges, in real time. There is no virtual reality here!

These challenges range from physical to emotional to material. The first response is to jump into the "I can handle this!" mode. "This and that is necessary to solve this. Problem solved!" Most of the time this approach is a temporary fix and only prolongs the problem, or even makes it worse.

Through many painful experiences, I have learned the hard way to approach these "growth opportunities" with pre-determined guide lines.

*   Have I prayed for wisdom and discernment?
*   Do I have all the facts?
*   Am I the best one to help solve this challenge, or do I seek help?
*   Is my solution enabling a bad habit to continue, or helping someone get on his feet?

These simple guidelines, when followed, have saved many a heartache; when not followed, the result is many heartaches as well as headaches!

For the past 10 days, all the high school students and staff have been living in the remote village of Binuangan. In an attempt to add practical application to the academic and spiritual lessons, we decided to add "manual labor" to our curriculum as counseled in the book "Education"

We loaded our shovels, picks, digging bars and wheelbarrows into the Laymen Ministries Express III and three hours later we were delivered onto the beach of the village of Binuangan. There the adjacent river is eating away at the village's riverbank endangering our church and school. We immediately went to work digging a channel to redirect the flow of the river away from the village.

Four Laymen Ministries teachers from the village of Pinagbayanan heard of our endeavor and along with 14 older students and parents came and joined us for three days of work. This demonstrated to our high school students how initiative stimulates willingness by others to join in worthwhile efforts.

Working in the riverbank with manual tools

Digging in a riverbed is hard work! In addition to sand and gravel and roots, large boulders had been washed downstream and buried by the annual floods. In this remote location, mechanical equipment was impossible to bring in. Human hands, sometimes using coconut shells, did all work.

As life here for the indigenous tribe is a daily struggle to find something to eat, planning and participating in a major project to "help the community" is not even part of their thinking.

After five days of physical toil, and a lot of laughs and Christian camaraderie with the teachers who were not accustomed to physical labor, the entrance barrier to the new channel was removed and half the river water was diverted into the new channel.

Susanne taking a picture with her arms as reference

In five days of working together the team had moved more than 400 cubic meters of rock and gravel to dig a canal four meters wide at the top, two meters wide at the base and average 1 ½ meters deep and 107 meters long.

Next the team, under the direction of civil engineer Susanne Marz, a Student Missionary from Germany, began planting trees and bushes along the riverbank to assist in erosion control.

Unfortunately, I missed the last days of digging and planting. The first days I wore rubber reef shoes. I was quite happy to wear them, but doing so all day long made my feet very soft. Some sand got inside and irritated the skin. Here in the tropics the bacteria and fungi are hyperactive. After three days, in between my toes and the pads of the toes were bloody and like freshly cut meat.

Jim is transportet off by the villagers in a wheelbarrow after not being able to walk anymore of pain

Fortunately, we have here in this village a missionary teacher who received medical missionary training at Wildwood. Marie Victor has been treating me with guava leaf wash, clay and charcoal poultices, plus an ointment for the fungus. Thank god! Healing is taking place. Here again, we experience reality, nothing virtual here!

Having the high school students and staff here in this remote village for 10 days has been beneficial as the cooperation and working side-by-side has bonded us closer. In addition, the students have interacted with the elementary students and their parents; they have observed and participated in classes and also observed a very ineffective village meeting. They know they will later be village leaders and are seeing firsthand their future challenges in real time.

Jesus has called all Christians to be his ambassadors and to represent him **now** in real time!

Thank you prayer partners and donors for giving us the possibility and privilege of preparing these native youth for service to their own people.

We appreciate you and pray that you are also working now in your local vineyard of our master!


text:
<?php
$liq_ops = array(0=>"NO",1=>"SÍ");

echo Form::open(array("class"=>"form-horizontal")); ?>
	<fieldset>

			<?php echo Form::label('Nombre', 'nombre', array('class'=>'control-label')); ?>
			<?php echo Form::input('nombre', Input::post('nombre', isset($proveedor) ? $proveedor->nombre : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Nombre del proveedor o razón social de la empresa')); ?>

			<?php echo Form::label('Domicilio', 'domicilio', array('class'=>'control-label')); ?>
			<?php echo Form::input('domicilio', Input::post('domicilio', isset($proveedor) ? $proveedor->domicilio : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Domicilio')); ?>

			<?php echo Form::label('Población', 'poblacion', array('class'=>'control-label')); ?>
			<?php echo Form::input('poblacion', Input::post('poblacion', isset($proveedor) ? $proveedor->poblacion : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Población')); ?>

			<?php echo Form::label('NIF/CIF', 'nifcif', array('class'=>'control-label')); ?>
			<?php echo Form::input('nifcif', Input::post('nifcif', isset($proveedor) ? $proveedor->nifcif : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'NIF ó CIF del proveedor')); ?>

			<?php echo Form::label('Teléfono', 'telefono', array('class'=>'control-label')); ?>
			<?php echo Form::input('telefono', Input::post('telefono', isset($proveedor) ? $proveedor->telefono : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Teléfono de contacto')); ?>

			<?php echo Form::label('Tipo de proveedor', 'tipo', array('class'=>'control-label'));
            $options=array(
                'persona fisica'=>'Persona Física',
                'empresa'=>'Empresa'
            );
            echo Form::select('tipo', '', $options, array('class' => 'col-md-4 form-control'));
            ?>

            <?php echo Form::label('Comentario', 'comentario', array('class'=>'control-label')); ?>
            <?php echo Form::input('comentario', Input::post('comentario', isset($proveedor) ? $proveedor->comentario : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Comentario')); ?>

            <?php echo Form::label('Envases prestados', 'envases', array('class'=>'control-label')); ?>
            <?php echo Form::input('envases', Input::post('envases', isset($proveedor) ? $proveedor->envases : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Núm. envases prestados')); ?>

            <?php echo Form::label('Liquidado', 'liquidado', array('class'=>'control-label')); ?>
            <?php echo Form::select('liquidado', Input::post('liquidado', isset($proveedor) ? $proveedor->liquidado : ''),$liq_ops, array('class' => 'col-md-4 form-control', 'placeholder'=>'Núm. envases prestados')); ?>

			<?php echo Form::button('submit', ' Guardar cambios', array('class' => 'btn btn-primary','type'=>'submit')); ?>

	</fieldset>
<?php echo Form::close(); ?>


text:
using System.Diagnostics;
using static System.RuntimeTypeHandle;

namespace System.Collections.Generic
{
    /// <summary>
    /// Helper class for creating the default <see cref="Comparer{T}"/> and <see cref="EqualityComparer{T}"/>.
    /// </summary>
    /// <remarks>
    /// This class is intentionally type-unsafe and non-generic to minimize the generic instantiation overhead of creating
    /// the default comparer/equality comparer for a new type parameter. Efficiency of the methods in here does not matter too
    /// much since they will only be run once per type parameter, but generic code involved in creating the comparers needs to be
    /// kept to a minimum.
    /// </remarks>
    internal static class ComparerHelpers
    {
        /// <summary>
        /// Creates the default <see cref="Comparer{T}"/>.
        /// </summary>
        /// <param name="type">The type to create the default comparer for.</param>
        /// <remarks>
        /// The logic in this method is replicated in vm/compile.cpp to ensure that NGen saves the right instantiations,
        /// and in vm/jitinterface.cpp so the jit can model the behavior of this method.
        /// </remarks>
        internal static object CreateDefaultComparer(Type type)
        {
            Debug.Assert(type != null && type is RuntimeType);

            object result = null;
            var runtimeType = (RuntimeType)type;

            // If T implements IComparable<T> return a GenericComparer<T>
            if (typeof(IComparable<>).MakeGenericType(type).IsAssignableFrom(type))
            {
                result = CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), runtimeType);
            }
            // Nullable does not implement IComparable<T?> directly because that would add an extra interface call per comparison.
            // Instead, it relies on Comparer<T?>.Default to specialize for nullables and do the lifted comparisons if T implements IComparable.
            else if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    result = TryCreateNullableComparer(runtimeType);
                }
            }
            // The comparer for enums is specialized to avoid boxing.
            else if (type.IsEnum)
            {
                result = TryCreateEnumComparer(runtimeType);
            }

            return result ?? CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ObjectComparer<object>), runtimeType);
        }

        /// <summary>
        /// Creates the default <see cref="Comparer{T}"/> for a nullable type.
        /// </summary>
        /// <param name="nullableType">The nullable type to create the default comparer for.</param>
        private static object TryCreateNullableComparer(RuntimeType nullableType)
        {
            Debug.Assert(nullableType != null);
            Debug.Assert(nullableType.IsGenericType && nullableType.GetGenericTypeDefinition() == typeof(Nullable<>));

            var embeddedType = (RuntimeType)nullableType.GetGenericArguments()[0];

            if (typeof(IComparable<>).MakeGenericType(embeddedType).IsAssignableFrom(embeddedType))
            {
                return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), embeddedType);
            }

            return null;
        }

        /// <summary>
        /// Creates the default <see cref="Comparer{T}"/> for an enum type.
        /// </summary>
        /// <param name="enumType">The enum type to create the default comparer for.</param>
        private static object TryCreateEnumComparer(RuntimeType enumType)
        {
            Debug.Assert(enumType != null);
            Debug.Assert(enumType.IsEnum);

            // Explicitly call Enum.GetUnderlyingType here. Although GetTypeCode
            // ends up doing this anyway, we end up avoiding an unnecessary P/Invoke
            // and virtual method call.
            TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(enumType));

            // Depending on the enum type, we need to special case the comparers so that we avoid boxing.
            // Specialize differently for signed/unsigned types so we avoid problems with large numbers.
            switch (underlyingTypeCode)
            {
                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int32EnumComparer<int>), enumType);
                case TypeCode.Byte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt32EnumComparer<uint>), enumType);
                // 64-bit enums: Use `UnsafeEnumCastLong`
                case TypeCode.Int64:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int64EnumComparer<long>), enumType);
                case TypeCode.UInt64:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt64EnumComparer<ulong>), enumType);
            }

            return null;
        }

        /// <summary>
        /// Creates the default <see cref="EqualityComparer{T}"/>.
        /// </summary>
        /// <param name="type">The type to create the default equality comparer for.</param>
        /// <remarks>
        /// The logic in this method is replicated in vm/compile.cpp to ensure that NGen saves the right instantiations.
        /// </remarks>
        internal static object CreateDefaultEqualityComparer(Type type)
        {
            Debug.Assert(type != null && type is RuntimeType);

            object result = null;
            var runtimeType = (RuntimeType)type;

            // Specialize for byte so Array.IndexOf is faster.
            if (type == typeof(byte))
            {
                result = new ByteEqualityComparer();
            }
            // If T implements IEquatable<T> return a GenericEqualityComparer<T>
            else if (typeof(IEquatable<>).MakeGenericType(type).IsAssignableFrom(type))
            {
                result = CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericEqualityComparer<int>), runtimeType);
            }
            // Nullable does not implement IEquatable<T?> directly because that would add an extra interface call per comparison.
            // Instead, it relies on EqualityComparer<T?>.Default to specialize for nullables and do the lifted comparisons if T implements IEquatable.
            else if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    result = TryCreateNullableEqualityComparer(runtimeType);
                }
            }
            // The equality comparer for enums is specialized to avoid boxing.
            else if (type.IsEnum)
            {
                result = TryCreateEnumEqualityComparer(runtimeType);
            }

            return result ?? CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ObjectEqualityComparer<object>), runtimeType);
        }

        /// <summary>
        /// Creates the default <see cref="EqualityComparer{T}"/> for a nullable type.
        /// </summary>
        /// <param name="nullableType">The nullable type to create the default equality comparer for.</param>
        private static object TryCreateNullableEqualityComparer(RuntimeType nullableType)
        {
            Debug.Assert(nullableType != null);
            Debug.Assert(nullableType.IsGenericType && nullableType.GetGenericTypeDefinition() == typeof(Nullable<>));

            var embeddedType = (RuntimeType)nullableType.GetGenericArguments()[0];

            if (typeof(IEquatable<>).MakeGenericType(embeddedType).IsAssignableFrom(embeddedType))
            {
                return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableEqualityComparer<int>), embeddedType);
            }

            return null;
        }

        /// <summary>
        /// Creates the default <see cref="EqualityComparer{T}"/> for an enum type.
        /// </summary>
        /// <param name="enumType">The enum type to create the default equality comparer for.</param>
        private static object TryCreateEnumEqualityComparer(RuntimeType enumType)
        {
            Debug.Assert(enumType != null);
            Debug.Assert(enumType.IsEnum);

            // See the METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST and METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST_LONG cases in getILIntrinsicImplementation
            // for how we cast the enum types to integral values in the comparer without boxing.

            TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(enumType));

            // Depending on the enum type, we need to special case the comparers so that we avoid boxing.
            // Note: We have different comparers for short and sbyte, since for those types GetHashCode does not simply return the value.
            // We need to preserve what they would return.
            switch (underlyingTypeCode)
            {
                case TypeCode.Int16:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ShortEnumEqualityComparer<short>), enumType);
                case TypeCode.SByte:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(SByteEnumEqualityComparer<sbyte>), enumType);
                case TypeCode.Int32:
                case TypeCode.UInt32:
                case TypeCode.Byte:
                case TypeCode.UInt16:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer<int>), enumType);
                case TypeCode.Int64:
                case TypeCode.UInt64:
                    return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(LongEnumEqualityComparer<long>), enumType);
            }

            return null;
        }
    }
}


text:
.. _ug_advanced:

Advanced usage
==============

The following chapters contain information about advanced use cases and
features.

:ref:`ug_advanced_compat`

:ref:`ug_advanced_extensions`

:ref:`ug_advanced_bokehjs`

.. toctree::
    :hidden:

    advanced/compat
    advanced/extensions
    advanced/bokehjs


text:
package org.neo4j.kernel.impl.transaction.state;

import static java.util.Arrays.binarySearch;
import static java.util.Arrays.copyOf;

import static org.neo4j.collection.primitive.PrimitiveLongCollections.EMPTY_LONG_ARRAY;

public class LabelChangeSummary
{
    private final long[] addedLabels;
    private final long[] removedLabels;
    private final long[] unchangedLabels;

    public LabelChangeSummary( long[] labelsBefore, long[] labelsAfter )
    {
        // Ids are sorted in the store
        long[] addedLabels = new long[labelsAfter.length];
        long[] removedLabels = new long[labelsBefore.length];
        long[] unchangedLabels = new long[Math.min( addedLabels.length, removedLabels.length )];
        int addedLabelsCursor = 0, removedLabelsCursor = 0, unchangedLabelsCursor = 0;
        for ( long labelAfter : labelsAfter )
        {
            if ( binarySearch( labelsBefore, labelAfter ) < 0 )
            {
                addedLabels[addedLabelsCursor++] = labelAfter;
            }
            else
            {
                unchangedLabels[unchangedLabelsCursor++] = labelAfter;
            }
        }
        for ( long labelBefore : labelsBefore )
        {
            if ( binarySearch( labelsAfter, labelBefore ) < 0 )
            {
                removedLabels[removedLabelsCursor++] = labelBefore;
            }
        }

        // For each property on the node, produce one update for added labels and one for removed labels.
        this.addedLabels = shrink( addedLabels, addedLabelsCursor );
        this.removedLabels = shrink( removedLabels, removedLabelsCursor );
        this.unchangedLabels = shrink( unchangedLabels, unchangedLabelsCursor );
    }

    private long[] shrink( long[] array, int toLength )
    {
        if ( toLength == 0 )
        {
            return EMPTY_LONG_ARRAY;
        }
        return array.length == toLength ? array : copyOf( array, toLength );
    }

    public boolean hasAddedLabels()
    {
        return addedLabels.length > 0;
    }

    public boolean hasRemovedLabels()
    {
        return removedLabels.length > 0;
    }

    public boolean hasUnchangedLabels()
    {
        return unchangedLabels.length > 0;
    }

    public long[] getAddedLabels()
    {
        return addedLabels;
    }

    public long[] getRemovedLabels()
    {
        return removedLabels;
    }

    public long[] getUnchangedLabels()
    {
        return unchangedLabels;
    }
}


text:
class Charts::OverseasAidController < ApplicationController
  def contributions
    @title = 'Contributions'
    contributions_json = File.read("storage/#{ENV['place_code']}/overseas_aid/contributions.json")
    contributions = JSON.parse(contributions_json)

    @labels = []

    @africa_aid = []
    @africa_emergency = []
    @eu_aid = []
    @eu_emergency = []
    @india_aid = []
    @india_emergency = []
    @latin_aid = []
    @latin_emergency = []
    @asia_aid = []
    @asia_emergency = []
    @mid_east_aid = []
    @mid_east_emergency = []

    contributions.sort_by{ |p| p['Year'] }.each do |val|
      @labels << val['Year'].to_s
      @africa_aid << val['Africa Aid']
      @africa_emergency << val['Africa Emergency Relief']
      @eu_aid << val['Europe Aid']
      @eu_emergency << val['Europe Emergency Relief']
      @india_aid << val['Indian Sub-Continent Aid']
      @india_emergency << val['Indian Sub-Continent Emergency Relief']
      @latin_aid << val['Latin America and Caribbean Aid']
      @latin_emergency << val['Latin America and Caribbean Emergency Relief']
      @asia_aid << val['Other Asia and Pacific Aid']
      @asia_emergency << val['Other Asia and Pacific Emergency Relief']
      @mid_east_aid << val['Middle East Aid']
      @mid_east_emergency << val['Middle East Emergency Relief']
    end
  end
end


text:
package org.apache.cassandra.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;

import com.google.common.annotations.VisibleForTesting;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;

import static org.apache.cassandra.utils.ByteBufferUtil.copyBytes;

/**
 * A Netty inbound handler that decodes incoming frames and passes them forward to
 * {@link InboundMessageHandler} for processing.
 *
 * Handles work stashing, and together with {@link InboundMessageHandler} - flow control.
 *
 * Unlike most Netty inbound handlers, doesn't use the pipeline to talk to its
 * upstream handler. Instead, a {@link FrameProcessor} must be registered with
 * the frame decoder, to be invoked on new frames. See {@link #deliver(FrameProcessor)}.
 *
 * See {@link #activate(FrameProcessor)}, {@link #reactivate()}, and {@link FrameProcessor}
 * for flow control implementation.
 *
 * Five frame decoders currently exist, one used for each connection depending on flags and messaging version:
 * 1. {@link FrameDecoderCrc}:
          no compression; payload is protected by CRC32
 * 2. {@link FrameDecoderLZ4}:
          LZ4 compression with custom frame format; payload is protected by CRC32
 * 3. {@link FrameDecoderUnprotected}:
          no compression; no integrity protection
 * 4. {@link FrameDecoderLegacy}:
          no compression; no integrity protection; turns unframed streams of legacy messages (< 4.0) into frames
 * 5. {@link FrameDecoderLegacyLZ4}
 *        LZ4 compression using standard LZ4 frame format; groups legacy messages (< 4.0) into frames
 */
abstract class FrameDecoder extends ChannelInboundHandlerAdapter
{
    private static final FrameProcessor NO_PROCESSOR =
        frame -> { throw new IllegalStateException("Frame processor invoked on an unregistered FrameDecoder"); };

    private static final FrameProcessor CLOSED_PROCESSOR =
        frame -> { throw new IllegalStateException("Frame processor invoked on a closed FrameDecoder"); };

    interface FrameProcessor
    {
        /**
         * Frame processor that the frames should be handed off to.
         *
         * @return true if more frames can be taken by the processor, false if the decoder should pause until
         * it's explicitly resumed.
         */
        boolean process(Frame frame) throws IOException;
    }

    abstract static class Frame
    {
        final boolean isSelfContained;
        final int frameSize;

        Frame(boolean isSelfContained, int frameSize)
        {
            this.isSelfContained = isSelfContained;
            this.frameSize = frameSize;
        }

        abstract void release();
        abstract boolean isConsumed();
    }

    /**
     * The payload bytes of a complete frame, i.e. a frame stripped of its headers and trailers,
     * with any verification supported by the protocol confirmed.
     *
     * If {@code isSelfContained} the payload contains one or more {@link Message}, all of which
     * may be parsed entirely from the bytes provided.  Otherwise, only a part of exactly one
     * {@link Message} is contained in the payload; it can be relied upon that this partial {@link Message}
     * will only be delivered in its own unique {@link Frame}.
     */
    final static class IntactFrame extends Frame
    {
        final ShareableBytes contents;

        IntactFrame(boolean isSelfContained, ShareableBytes contents)
        {
            super(isSelfContained, contents.remaining());
            this.contents = contents;
        }

        void release()
        {
            contents.release();
        }

        boolean isConsumed()
        {
            return !contents.hasRemaining();
        }

        void consume()
        {
            contents.consume();
        }
    }

    /**
     * A corrupted frame was encountered; this represents the knowledge we have about this frame,
     * and whether or not the stream is recoverable.
     *
     * Generally we consider a frame with corrupted header as unrecoverable, and frames with intact header,
     * but corrupted payload - as recoverable, since we know and can skip payload size.
     *
     * {@link InboundMessageHandler} further has its own idea of which frames are and aren't recoverable.
     * A recoverable {@link CorruptFrame} can be considered unrecoverable by {@link InboundMessageHandler}
     * if it's the first frame of a large message (isn't self contained).
     */
    final static class CorruptFrame extends Frame
    {
        final int readCRC, computedCRC;

        CorruptFrame(boolean isSelfContained, int frameSize, int readCRC, int computedCRC)
        {
            super(isSelfContained, frameSize);
            this.readCRC = readCRC;
            this.computedCRC = computedCRC;
        }

        static CorruptFrame recoverable(boolean isSelfContained, int frameSize, int readCRC, int computedCRC)
        {
            return new CorruptFrame(isSelfContained, frameSize, readCRC, computedCRC);
        }

        static CorruptFrame unrecoverable(int readCRC, int computedCRC)
        {
            return new CorruptFrame(false, Integer.MIN_VALUE, readCRC, computedCRC);
        }

        boolean isRecoverable()
        {
            return frameSize != Integer.MIN_VALUE;
        }

        void release() { }

        boolean isConsumed()
        {
            return true;
        }
    }

    protected final BufferPoolAllocator allocator;

    @VisibleForTesting
    final Deque<Frame> frames = new ArrayDeque<>(4);
    ByteBuffer stash;

    private boolean isActive;
    private boolean isClosed;
    private ChannelHandlerContext ctx;
    private FrameProcessor processor = NO_PROCESSOR;

    FrameDecoder(BufferPoolAllocator allocator)
    {
        this.allocator = allocator;
    }

    abstract void decode(Collection<Frame> into, ShareableBytes bytes);
    abstract void addLastTo(ChannelPipeline pipeline);

    /**
     * For use by InboundMessageHandler (or other upstream handlers) that want to start receiving frames.
     */
    void activate(FrameProcessor processor)
    {
        if (this.processor != NO_PROCESSOR)
            throw new IllegalStateException("Attempted to activate an already active FrameDecoder");

        this.processor = processor;

        isActive = true;
        ctx.read();
    }

    /**
     * For use by InboundMessageHandler (or other upstream handlers) that want to resume
     * receiving frames after previously indicating that processing should be paused.
     */
    void reactivate() throws IOException
    {
        if (isActive)
            throw new IllegalStateException("Tried to reactivate an already active FrameDecoder");

        if (deliver(processor))
        {
            isActive = true;
            onExhausted();
        }
    }

    /**
     * For use by InboundMessageHandler (or other upstream handlers) that want to resume
     * receiving frames after previously indicating that processing should be paused.
     *
     * Does not reactivate processing or reading from the wire, but permits processing as many frames (or parts thereof)
     * that are already waiting as the processor requires.
     */
    void processBacklog(FrameProcessor processor) throws IOException
    {
        deliver(processor);
    }

    /**
     * For use by InboundMessageHandler (or other upstream handlers) that want to permanently
     * stop receiving frames, e.g. because of an exception caught.
     */
    void discard()
    {
        isActive = false;
        processor = CLOSED_PROCESSOR;
        if (stash != null)
        {
            ByteBuffer bytes = stash;
            stash = null;
            allocator.put(bytes);
        }
        while (!frames.isEmpty())
            frames.poll().release();
    }

    /**
     * Called by Netty pipeline when a new message arrives; we anticipate in normal operation
     * this will receive messages of type {@link BufferPoolAllocator.Wrapped} or
     * {@link BufferPoolAllocator.Wrapped}.
     *
     * These buffers are unwrapped and passed to {@link #decode(Collection, ShareableBytes)},
     * which collects decoded frames into {@link #frames}, which we send upstream in {@link #deliver}
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException
    {
        if (msg instanceof BufferPoolAllocator.Wrapped)
        {
            ByteBuffer buf = ((BufferPoolAllocator.Wrapped) msg).adopt();
            // netty will probably have mis-predicted the space needed
            allocator.putUnusedPortion(buf);
            channelRead(ShareableBytes.wrap(buf));
        }
        else if (msg instanceof ShareableBytes) // legacy LZ4 decoder
        {
            channelRead((ShareableBytes) msg);
        }
        else
        {
            throw new IllegalArgumentException();
        }
    }

    void channelRead(ShareableBytes bytes) throws IOException
    {
        decode(frames, bytes);

        if (isActive) isActive = deliver(processor);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)
    {
        if (isActive)
            onExhausted();
    }

    /**
     * Only to be invoked when frames.isEmpty().
     *
     * If we have been closed, we will now propagate up the channelInactive notification,
     * and otherwise we will ask the channel for more data.
     */
    private void onExhausted()
    {
        if (isClosed)
            close();
        else
            ctx.read();
    }

    /**
     * Deliver any waiting frames, including those that were incompletely read last time, to the provided processor
     * until the processor returns {@code false}, or we finish the backlog.
     *
     * Propagate the final return value of the processor.
     */
    private boolean deliver(FrameProcessor processor) throws IOException
    {
        boolean deliver = true;
        while (deliver && !frames.isEmpty())
        {
            Frame frame = frames.peek();
            deliver = processor.process(frame);

            assert !deliver || frame.isConsumed();
            if (deliver || frame.isConsumed())
            {
                frames.poll();
                frame.release();
            }
        }
        return deliver;
    }

    void stash(ShareableBytes in, int stashLength, int begin, int length)
    {
        ByteBuffer out = allocator.getAtLeast(stashLength);
        copyBytes(in.get(), begin, out, 0, length);
        out.position(length);
        stash = out;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx)
    {
        this.ctx = ctx;
        ctx.channel().config().setAutoRead(false);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx)
    {
        isClosed = true;
        if (frames.isEmpty())
            close();
    }

    private void close()
    {
        discard();
        ctx.fireChannelInactive();
        allocator.release();
    }

    /**
     * Utility: fill {@code out} from {@code in} up to {@code toOutPosition},
     * updating the position of both buffers with the result
     * @return true if there were sufficient bytes to fill to {@code toOutPosition}
     */
    static boolean copyToSize(ByteBuffer in, ByteBuffer out, int toOutPosition)
    {
        int bytesToSize = toOutPosition - out.position();
        if (bytesToSize <= 0)
            return true;

        if (bytesToSize > in.remaining())
        {
            out.put(in);
            return false;
        }

        copyBytes(in, in.position(), out, out.position(), bytesToSize);
        in.position(in.position() + bytesToSize);
        out.position(toOutPosition);
        return true;
    }

    /**
     * @return {@code in} if has sufficient capacity, otherwise
     *         a replacement from {@code BufferPool} that {@code in} is copied into
     */
    ByteBuffer ensureCapacity(ByteBuffer in, int capacity)
    {
        if (in.capacity() >= capacity)
            return in;

        ByteBuffer out = allocator.getAtLeast(capacity);
        in.flip();
        out.put(in);
        allocator.put(in);
        return out;
    }
}


text:
package examples.todolist.persistence

import freestyle.tagless.tagless
import examples.todolist.Tag

@tagless(true)
trait TagRepository[F[_]] {

  def insert(tag: Tag): F[Option[Tag]]

  def get(id: Int): F[Option[Tag]]

  def delete(id: Int): F[Int]

  def update(tag: Tag): F[Option[Tag]]

  def list: F[List[Tag]]

  def drop: F[Int]

  def create: F[Int]

  def init: F[Int]
}


text:
package pl.tomo.provider.json.deserialize;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

public class TimeDeserializer extends JsonDeserializer<Date>{

	@Override
	public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
		JsonNode node = p.getCodec().readTree(p);
		try {
			return formatter.parse(node.asText());
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

}


text:
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Export('Config')

//@Require('Class')
//@Require('IJsonable')
//@Require('IObjectable')
//@Require('Obj')
//@Require('Properties')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var Class           = bugpack.require('Class');
    var IJsonable       = bugpack.require('IJsonable');
    var IObjectable     = bugpack.require('IObjectable');
    var Obj             = bugpack.require('Obj');
    var Properties      = bugpack.require('Properties');

    //-------------------------------------------------------------------------------
    // Class
    //-------------------------------------------------------------------------------

    /**
     * @class
     * @extends {Obj}
     * @implements {IJsonable}
     * @implements {IObjectable}
     */
    var Config = Class.extend(Obj, {

        _name: "Config",

        //-------------------------------------------------------------------------------
        // Constructor
        //-------------------------------------------------------------------------------

        /**
         * @constructs
         * @param {Object} configObject
         */
        _constructor: function(configObject) {

            this._super();

            //-------------------------------------------------------------------------------
            // Private Properties
            //-------------------------------------------------------------------------------

            /**
             * @private
             * @type {Properties}
             */
            this.properties = new Properties(configObject);
        },

        //-------------------------------------------------------------------------------
        // Getters and Setters
        //-------------------------------------------------------------------------------

        /**
         * @param {Config} config
         * @param {(Array.<string> | Collection.<string>)} propertyNames
         */
        absorbConfig: function(config, propertyNames) {
            this.properties.absorbProperties(config.getProperties(), propertyNames);
        },

        /**
         * @param {string} propertyQuery
         * @return {boolean}
         */
        deleteProperty: function(propertyQuery) {
            return this.properties.deleteProperty(propertyQuery);
        },

        /**
         * @return {Properties}
         */
        getProperties: function() {
            return this.properties;
        },

        /**
         * @param {string} propertyQuery
         * @return {*}
         */
        getProperty: function(propertyQuery) {
            return this.properties.getProperty(propertyQuery);
        },

         /**
         * @param {string} propertyQuery
         * @return {boolean}
         */
        hasProperty: function(propertyQuery) {
            return this.properties.hasProperty(propertyQuery);
        },

        /**
         * @param {string} propertyQuery
         * @param {*} propertyValue
         */
        setProperty: function(propertyQuery, propertyValue) {
            this.properties.setProperty(propertyQuery, propertyValue);
        },

        /**
         * @param {Object} propertiesObject
         */
        updateProperties: function(propertiesObject) {
            this.properties.updateProperties(propertiesObject);
        },

        //-------------------------------------------------------------------------------
        // IObjectable Implementation
        //-------------------------------------------------------------------------------

        /**
         * @return {Object}
         */
        toObject: function() {
            return Obj.clone(this.properties.getPropertiesObject(), true);
        },

        //-------------------------------------------------------------------------------
        // IJsonable Implementation
        //-------------------------------------------------------------------------------

        /**
         * @return {string}
         */
        toJson: function() {
            return JSON.stringify(this.toObject());
        }
    });

    //-------------------------------------------------------------------------------
    // Interfaces
    //-------------------------------------------------------------------------------

    Class.implement(Config, IJsonable);
    Class.implement(Config, IObjectable);

    //-------------------------------------------------------------------------------
    // Exports
    //-------------------------------------------------------------------------------

    bugpack.export("Config", Config);
});


text:
odie() {
  if [[ -t 2 ]] # check whether stderr is a tty.
  then
    echo -ne "\033[4;31mError\033[0m: " >&2 # highlight Error with underline and red color
  else
    echo -n "Error: " >&2
  fi
  if [[ $# -eq 0 ]]
  then
    /bin/cat >&2
  else
    echo "$*" >&2
  fi
  exit 1
}

chdir() {
  cd "$@" >/dev/null || odie "Error: failed to cd to $*!"
}

# Force UTF-8 to avoid encoding issues for users with broken locale settings.
if [[ "$(locale charmap 2> /dev/null)" != "UTF-8" ]]
then
  export LC_ALL="en_US.UTF-8"
fi

# Where we store built products; /usr/local/Cellar if it exists,
# otherwise a Cellar relative to the Repository.
if [[ -d "$HOMEBREW_PREFIX/Cellar" ]]
then
  HOMEBREW_CELLAR="$HOMEBREW_PREFIX/Cellar"
else
  HOMEBREW_CELLAR="$HOMEBREW_REPOSITORY/Cellar"
fi

case "$*" in
  --prefix) echo "$HOMEBREW_PREFIX"; exit 0 ;;
  --cellar) echo "$HOMEBREW_CELLAR"; exit 0 ;;
  --repository|--repo) echo "$HOMEBREW_REPOSITORY"; exit 0 ;;
esac

if [[ "$HOMEBREW_PREFIX" = "/" || "$HOMEBREW_PREFIX" = "/usr" ]]
then
  # it may work, but I only see pain this route and don't want to support it
  odie "Cowardly refusing to continue at this prefix: $HOMEBREW_PREFIX"
fi

# Users may have these set, pointing the system Ruby
# at non-system gem paths
unset GEM_HOME
unset GEM_PATH

if [[ -z "$HOMEBREW_DEVELOPER" ]]
then
  unset HOMEBREW_RUBY_PATH
fi

if [[ "$(uname -s)" = "Darwin" ]]
then
  HOMEBREW_OSX="1"
fi

if [[ -z "$HOMEBREW_RUBY_PATH" ]]
then
  if [[ -n "$HOMEBREW_OSX" ]]
  then
    HOMEBREW_RUBY_PATH="/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby"
  else
    HOMEBREW_RUBY_PATH="$(which ruby)"
  fi
fi

export HOMEBREW_BREW_FILE
export HOMEBREW_RUBY_PATH
export HOMEBREW_PREFIX
export HOMEBREW_REPOSITORY
export HOMEBREW_LIBRARY
export HOMEBREW_CELLAR

if [[ -n "$HOMEBREW_OSX" ]]
then
  if [[ "$('/usr/bin/xcode-select' --print-path)" = "/" ]]
  then
    odie <<EOS
Your xcode-select path is currently set to '/'.
This causes the 'xcrun' tool to hang, and can render Homebrew unusable.
If you are using Xcode, you should:
  sudo xcode-select -switch /Applications/Xcode.app
Otherwise, you should:
  sudo rm -rf /usr/share/xcode-select
EOS
  fi

  XCRUN_OUTPUT="$(/usr/bin/xcrun clang 2>&1)"
  XCRUN_STATUS="$?"

  if [[ "$XCRUN_STATUS" -ne 0 && "$XCRUN_OUTPUT" = *license* ]]
  then
    odie <<EOS
You have not agreed to the Xcode license. Please resolve this by running:
  sudo xcodebuild -license
EOS
  fi
fi

# Many Pathname operations use getwd when they shouldn't, and then throw
# odd exceptions. Reduce our support burden by showing a user-friendly error.
if [[ ! -d "$(pwd)" ]]
then
  odie "The current working directory doesn't exist, cannot proceed."
fi

if [[ "$1" = -v ]]
then
  # Shift the -v to the end of the parameter list
  shift
  set -- "$@" -v
fi

HOMEBREW_COMMAND="$1"
shift
case "$HOMEBREW_COMMAND" in
  '')          HOMEBREW_COMMAND="help";;
  ls)          HOMEBREW_COMMAND="list";;
  homepage)    HOMEBREW_COMMAND="home";;
  -S)          HOMEBREW_COMMAND="search";;
  up)          HOMEBREW_COMMAND="update";;
  ln)          HOMEBREW_COMMAND="link";;
  instal)      HOMEBREW_COMMAND="install";; # gem does the same
  rm)          HOMEBREW_COMMAND="uninstall";;
  remove)      HOMEBREW_COMMAND="uninstall";;
  configure)   HOMEBREW_COMMAND="diy";;
  abv)         HOMEBREW_COMMAND="info";;
  dr)          HOMEBREW_COMMAND="doctor";;
  --repo)      HOMEBREW_COMMAND="--repository";;
  environment) HOMEBREW_COMMAND="--env";;
  --config)    HOMEBREW_COMMAND="config";;
esac

if [[ -f "$HOMEBREW_LIBRARY/Homebrew/cmd/$HOMEBREW_COMMAND.sh" ]] ; then
  HOMEBREW_BASH_COMMAND="$HOMEBREW_LIBRARY/Homebrew/cmd/$HOMEBREW_COMMAND.sh"
elif [[ -n "$HOMEBREW_DEVELOPER" && -f "$HOMEBREW_LIBRARY/Homebrew/dev-cmd/$HOMEBREW_COMMAND.sh" ]] ; then
  HOMEBREW_BASH_COMMAND="$HOMEBREW_LIBRARY/Homebrew/dev-cmd/$HOMEBREW_COMMAND.sh"
fi

if [[ "$(id -u)" = "0" && "$(/usr/bin/stat -f%u "$HOMEBREW_BREW_FILE")" != "0" ]]
then
  case "$HOMEBREW_COMMAND" in
    install|reinstall|postinstall|link|pin|update|update-ruby|upgrade|create|migrate|tap|switch)
      odie <<EOS
Cowardly refusing to 'sudo brew $HOMEBREW_COMMAND'
You can use brew with sudo, but only if the brew executable is owned by root.
However, this is both not recommended and completely unsupported so do so at
your own risk.
EOS
      ;;
  esac
fi

if [[ -n "$HOMEBREW_BASH_COMMAND" ]]
then
  # source rather than executing directly to ensure the entire file is read into
  # memory before it is run. This makes running a Bash script behave more like
  # a Ruby script and avoids hard-to-debug issues if the Bash script is updated
  # at the same time as being run.
  #
  # Hide shellcheck complaint:
  # shellcheck source=/dev/null
  source "$HOMEBREW_BASH_COMMAND"
  { "homebrew-$HOMEBREW_COMMAND" "$@"; exit $?; }
else
  exec "$HOMEBREW_RUBY_PATH" -W0 "$HOMEBREW_LIBRARY/brew.rb" "$HOMEBREW_COMMAND" "$@"
fi