text:
<?php

	$operations = new RevOperations();

	$sliderID = self::getGetVar("id");

	if(empty($sliderID))
		UniteFunctionsRev::throwError("Slider ID not found");

	$slider = new RevSlider();
	$slider->initByID($sliderID);
	$sliderParams = $slider->getParams();

	$arrSliders = $slider->getArrSlidersShort($sliderID);
	$selectSliders = UniteFunctionsRev::getHTMLSelect($arrSliders,"","id='selectSliders'",true);

	$numSliders = count($arrSliders);

	//set iframe parameters
	$width = $sliderParams["width"];
	$height = $sliderParams["height"];

	$iframeWidth = $width+60;
	$iframeHeight = $height+50;

	$iframeStyle = "width:".$iframeWidth."px;height:".$iframeHeight."px;";

	$arrSlides = $slider->getSlides(false);

	$numSlides = count($arrSlides);

	$linksSliderSettings = self::getViewUrl(RevSliderAdmin::VIEW_SLIDER,"id=$sliderID");

	$patternViewSlide = self::getViewUrl("slide","id=[slideid]");

	//treat in case of slides from gallery
	if($slider->isSlidesFromPosts() == false){

		$templateName = "slides_gallery";

		//handle wpml
		$isWpmlExists = UniteWpmlRev::isWpmlExists();
		$useWpml = $slider->getParam("use_wpml","off");

		$wpmlActive = false;
		if($isWpmlExists && $useWpml == "on"){
			$wpmlActive = true;

			//get langs floating menu
			$urlIconDelete = self::$url_plugin."images/icon-trash.png";
			$urlIconEdit = self::$url_plugin."images/icon-edit.png";
			$urlIconPreview = self::$url_plugin."images/preview.png";

			$textDelete = __("Delete Slide",REVSLIDER_TEXTDOMAIN);
			$textEdit = __("Edit Slide",REVSLIDER_TEXTDOMAIN);
			$textPreview = __("Preview Slide",REVSLIDER_TEXTDOMAIN);

			$htmlBefore = "";
			$htmlBefore .= "
"."\n";
			$htmlBefore .= " ".$textDelete."\n";
			$htmlBefore .= "
"."\n";

			$htmlBefore .= "
"."\n";
			$htmlBefore .= " ".$textEdit."\n";
			$htmlBefore .= "
"."\n";

			$htmlBefore .= "
"."\n";
			$htmlBefore .= " ".$textPreview."\n";
			$htmlBefore .= "
"."\n";

			$htmlBefore .= "
"."\n";
			$htmlBefore .= "

"."\n";
			$htmlBefore .= "
"."\n";

			$langFloatMenu = UniteWpmlRev::getLangsWithFlagsHtmlList("id='slides_langs_float' class='slides_langs_float'",$htmlBefore);
		}

	}

	else{	//slides from posts

		$templateName = "slides_posts";

		$sourceType = $slider->getParam("source_type","posts");
		$showSortBy = ($sourceType == "posts")?true:false;

		//get button links
		$urlNewPost = UniteFunctionsWPRev::getUrlNewPost();
		$linkNewPost = UniteFunctionsRev::getHtmlLink($urlNewPost, __("New Post",REVSLIDER_TEXTDOMAIN),"button_new_post","button-primary revblue",true);

		//get ordering
		$arrSortBy = UniteFunctionsWPRev::getArrSortBy();
		$sortBy = $slider->getParam("post_sortby",RevSlider::DEFAULT_POST_SORTBY);
		$selectSortBy = UniteFunctionsRev::getHTMLSelect($arrSortBy,$sortBy,"id='select_sortby'",true);
	}

	require self::getPathTemplate($templateName);

?>


text:
import { MarvelPager } from '../components/MarvelPager';
import { connect } from 'react-redux';
import { compose, withProps, withHandlers } from 'recompose';
import { range, filter } from 'ramda';
import { getNavigation } from '../selectors';
import { nextPage, prevPage, toPage, toStart } from '../actions';

export default compose<any, { total: number; offset: number; }>(
  connect(getNavigation),
  withProps(
    ({ page, total, offset }) => ({
      prev: filter(num => num !== page && num > 0)(range(Math.abs(page - offset), page)),
      next: filter(num => page !== total && num <= total)(range(page + 1, (page + offset) + 1))
    })
  ),
  withHandlers({
    onNext: ({ dispatch }) => () => dispatch(nextPage()),
    onPrev: ({ dispatch }) => () => dispatch(prevPage()),
    onStart: ({ dispatch }) => () => dispatch(toStart()),
    onEnd: ({ dispatch, total }) => () => dispatch(toPage(total)),
    onPage: ({ dispatch }) => ({ currentTarget }) => {
      const { dataset: { page } } = currentTarget;
      dispatch(toPage(Number(page)));
    }
  })
)(MarvelPager);

redpajama_set_name: RedPajamaGithub


text:
using System;
namespace Thinktecture
{
	/// <summary>
	/// Event handler context of an abstraction.
	/// </summary>
	/// <typeparam name="TImplementationDelegate">Type of the delegate.</typeparam>
	public class AbstractionEventHandlerContext<TImplementationDelegate>
		where TImplementationDelegate : class
	{
		/// <summary>
		/// Event handler.
		/// </summary>
		public TImplementationDelegate Handler { get; }

		/// <summary>
		/// Indication how many times the handler has been attached.
		/// </summary>
		public int Count { get; set; }

		/// <summary>
		/// Initializes new istance of <see cref="AbstractionEventHandlerContext{TImplementationDelegate}"/>.
		/// </summary>
		/// <param name="handler">Event handler</param>
		public AbstractionEventHandlerContext(TImplementationDelegate handler)
		{
			Handler = handler ?? throw new ArgumentNullException(nameof(handler));
		}
	}
}


text:
package com.yanzhenjie.recyclerview.swipe;

/**
 * Created by Yan Zhenjie on 2016/7/26.
 */
public interface Closeable {

    /**
     * Smooth closed the menu on the left.
     */
    void smoothCloseLeftMenu();

    /**
     * Smooth closed the menu on the right.
     */
    void smoothCloseRightMenu();

    /**
     * Smooth closed the menu.
     */
    void smoothCloseMenu();

    /**
     * Smooth closed the menu for the duration.
     *
     * @param duration duration time.
     */
    void smoothCloseMenu(int duration);
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>cn.jpush.im.android.api.model (android API)</title>
<meta name="date" content="2018-05-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package cn.jpush.im.android.api.model

Class Summary

Class
Description

ChatRoomInfo

聊天室信息,本聊天室信息不实时更新
 如果想要获取最新信息调用ChatRoomManager里面的接口

Conversation

DeviceInfo

设备状态信息,使用JMessageClient.login(String, String, RequestCallback)可以返回账号所登陆过的设备信息。

GroupBasicInfo

群基本信息,只包括groupId,groupName,groupDescription, flag, level, maxMemberCount,avatarMediaID等基本信息。
 如果想获取详细信息使用JMessageClient.getGroupInfo(long, GetGroupInfoCallback)或者Conversation.getTargetInfo()获取GroupInfo

GroupInfo

Message

UserInfo

Enum Summary

Enum
Description

GroupBasicInfo.Type

UserInfo.Field

UserInfo.Gender

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
HTMLWidgets.widget({

  name: 'd3tree3',

  type: 'output',

  initialize: function(el, width, height) {

    return {

    }

  },

  renderValue: function(el, x, instance) {

    //clear out el in case of dynamic/Shiny situation
    el.innerHTML = "";

    var format = d3.format(",.1f");
    var valueField = x.options.valueField ? x.options.valueField : "size";
    var celltext = x.options.celltext ? x.options.celltext : "name";
    var cellid = x.options.id ? x.options.id : "id";

    // thanks Mike Bostock and Zan Armstrong for all the code on which
    //    this is based
    //  http://bost.ocks.org/mike/treemap/
    //  https://gist.github.com/zanarmstrong/76d263bd36f312cb0f9f

    var margin = {top: 60, right: 0, bottom: 20, left: 0, grandparent: 20},
        width = el.getBoundingClientRect().width,
        height = el.getBoundingClientRect().height - margin.top - margin.bottom,
        formatNumber = d3.format(",d"),
        transitioning;

    var svg = d3.select(el).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.bottom + margin.top)
        .style("margin-left", -margin.left + "px")
        .style("margin.right", -margin.right + "px");

    var graphic = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .style("shape-rendering", "crispEdges");

    // experiment to add a legend if provided from treemap
    if (x.legend){
      var regExp = /<rect id="GRID\.rect.*fill="(rgb\(.{5,15}\))"/g;
      var arrayOfRects = [];

      var m;
      do {
          m = regExp.exec(x.legend);
          if (m) {
            arrayOfRects.push(m[1]);
          }
      } while (m);

      //Pulls colors out of DOM and constructs legend fade object
      var colors = [];
      arrayOfRects.forEach(function(d, i) {
        colors.push({
           "offset" : (100 / (arrayOfRects.length - 1)) * i + "%",
           "color" : d
        });
      });

      //construct legend data object

      //Creates gradient for legend, assuming chunks of six
      svg.append("linearGradient")
        .attr("id", "legend-gradient")
        .attr("gradientUnits", "userSpaceOnUse")
        .attr("x1", margin.left + (width/2)).attr("y1", 0)
        .attr("x2", width - margin.left).attr("y2", 0)
      .selectAll("stop")
        .data(colors)
      .enter().append("stop")
        .attr("offset", function(d) { return d.offset; })
        .attr("stop-color", function(d) { return d.color; });

      //Adds in new legend
      legend = svg.append("g")
                  .attr("class", "legend");

      legend.append("rect")
            .attr("x", margin.left+ (width/2))
            .attr("width", (width/2) - margin.right - margin.left)
            .attr("y", 25)
            .attr("height", 15)
            .attr("fill", "url(#legend-gradient)")

      //Grabs minimum/maximum values
      var min = x.meta.range[0];
      var max = x.meta.range[1];
      //constructs scale
      var scale = d3.scale.linear().range([margin.left + (width/2), width - margin.right]).domain([min, max]);

      //Add triangles and cispan and label
      var ciSpan = legend.append('g').style('opacity',0);
      var arc = d3.svg.symbol().type('triangle-down').size(100);

      var ciRect = ciSpan.append('rect')
        .attr('stroke-width', 0)
        .attr('fill','#CDCDCD')
        .attr('width', 0)
        .attr('height', '10px')
        .attr('x', function() { return scale(0);})
        .attr('y', '15');
      var triangle = ciSpan.append('path')
				.attr('d',arc)
				.attr('fill','#000')
				.attr('stroke','#000')
				.attr('stroke-width',1)
				.attr('transform', 'translate(' + scale(0) + ',20)');
			var value = ciSpan.append('text')
			  .attr('class', 'value-label')
			  .attr('transform', 'translate(' + scale(0) + ',10)')
			  .style('text-anchor','middle');
		  var ciLower = ciSpan.append('text')
			  .attr('class', 'value-label')
			  .attr('transform', 'translate(' + scale(0) + ',23)')
			  .style('text-anchor','end');
		  var ciUpper = ciSpan.append('text')
			  .attr('class', 'value-label')
			  .attr('transform', 'translate(' + scale(0) + ',23)')
			  .style('text-anchor','start');
    }

    var xscale = d3.scale.linear()
        .domain([0, width])
        .range([0, width]);

    var yscale = d3.scale.linear()
        .domain([0, height])
        .range([0, height]);

    var color = d3.scale.category20();
    color.range(
      color.range().map(
        function(d,i){
          return (i==0) ? "#bbb" : d
        }
      )
    );

    var treemap = d3.layout.treemap()
        .children(function(d, depth) { return depth ? null : d._children; })
        .sort(function(a, b) { return a[valueField] - b[valueField]; })
        .ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
        .round(false)
        .value(function(d) {
            return d[valueField];
        });

    var grandparent = graphic.append("g")
        .attr("class", "grandparent");

    grandparent.append("rect")
        .attr("y", -margin.grandparent)
        .attr("width", width)
        .attr("height", margin.grandparent);

    grandparent.append("text")
        .attr("x", 6)
        .attr("y", 6 - margin.grandparent)
        .attr("dy", ".75em");

    // determines if white or black will be better contrasting color
    //  copied from

    function getRGBComponents(color) {
        return d3.rgb(color)
    }

    function idealTextColor(bgColor) {
        var nThreshold = 105;
        var components = getRGBComponents(bgColor);
        var bgDelta = (components.r * 0.299) + (components.g * 0.587) + (components.b * 0.114);
        return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";
    }

    draw( x.data );

    // set up a container for tasks to perform after completion
    //  one example would be add callbacks for event handling
    //  styling
    if (!(typeof x.tasks === "undefined") ){
      if ( (typeof x.tasks.length === "undefined") ||
       (typeof x.tasks === "function" ) ) {
         // handle a function not enclosed in array
         // should be able to remove once using jsonlite
         x.tasks = [x.tasks];
      }
      x.tasks.map(function(t){
        // for each tasks call the task with el supplied as `this`
        t.call(el);
      })
    }

    function draw(root) {
      initialize(root);
      accumulate(root);
      layout(root);
      display(root);

      function initialize(root) {
        root.x = root.y = 0;
        root.dx = width;
        root.dy = height;
        root.depth = 0;
      }

      // Aggregate the values for internal nodes. This is normally done by the
      // treemap layout, but not here because of our custom implementation.
      // We also take a snapshot of the original children (_children) to avoid
      // the children being overwritten when when layout is computed.
      function accumulate(d) {

        if( Array.isArray(d.children) ) {
            return (d._children = d.children)
              ? d[valueField] = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0)
              : d[valueField];
        } else {
          return d[valueField];
        }

      }

      // Compute the treemap layout recursively such that each group of siblings
      // uses the same size (1×1) rather than the dimensions of the parent cell.
      // This optimizes the layout for the current zoom state. Note that a wrapper
      // object is created for the parent node for each group of siblings so that
      // the parent's dimensions are not discarded as we recurse. Since each group
      // of sibling was laid out in 1×1, we must rescale to fit using absolute
      // coordinates. This lets us use a viewport to zoom.
      function layout(d) {
        if (d._children) {
          treemap.nodes({_children: d._children});
          d._children.forEach(function(c) {
            c.x = d.x + c.x * d.dx;
            c.y = d.y + c.y * d.dy;
            c.dx *= d.dx;
            c.dy *= d.dy;
            c.parent = d;
            layout(c);
          });
        }
      }
      function display(d) {
        grandparent
            .datum( d )
            .on("click", function(d){
              transition( (d.parent) ? d.parent: d );
              communicateClick( d.parent ? d.parent: d );
            } )
          .on('mouseover', function(d) {
            showSpan(d);
          })
          .on('mouseout', function(d) {
            hideSpan(d);
          })
          .select("text")
            .text(name(d))
            .style("fill", function (d) {
              return idealTextColor( d.color ? d.color : color(leveltwo(d)[celltext]) );
            });

        grandparent
          .select("rect")
            .style("fill",function(d){
              return (d) ?
                ( (d.color) ? d.color : color(leveltwo(d)[celltext]) ) :
                "#bbb";
            })

        var g1 = graphic.insert("g", ".grandparent")
            .datum(d)
            .attr("class", "depth");

        var g = g1.selectAll("g")
            .data(d._children)
          .enter().append("g");

        g.filter(function(d) { return d._children; })
            .classed("children", true)
            .on("click", transition);

        g.selectAll(".child")
            .data(function(d) { return d._children || [d]; })
          .enter().append("rect")
            .attr("class", "child")
            .call(rect);

        g.append("rect")
            .attr("class", "parent")
            .call(rect)
            .on("click", function(d){
              communicateClick(d);
            })
            .on("mouseover", function(d) {
              showSpan(d);
            })
            .on("mouseout", function(d) {
              hideSpan(d);
            })
          .append("title")
            .text(function(d) { return formatNumber(d[valueField]); });

        g.append("text")
            .attr("dy", ".75em")
            .text(function(d) { return d[celltext]; })
            .call(text);

        function transition(d) {
          if (transitioning || !d) return;
          transitioning = true;

          var g2 = display(d),
              t1 = g1.transition().duration(750),
              t2 = g2.transition().duration(750);

          // Update the domain only after entering new elements.
          xscale.domain([d.x, d.x + d.dx]);
          yscale.domain([d.y, d.y + d.dy]);

          // Enable anti-aliasing during the transition.
          svg.style("shape-rendering", null);

          // Draw child nodes on top of parent nodes.
          svg.selectAll(".depth").sort(function(a, b) { return a.depth - b.depth; });

          // Fade-in entering text.
          g2.selectAll("text").style("fill-opacity", 0);

          // Transition to the new view.
          t1.selectAll("text").call(text).style("fill-opacity", 0);
          t2.selectAll("text").call(text).style("fill-opacity", 1);
          t1.selectAll("rect").call(rect);
          t2.selectAll("rect").call(rect);

          // Remove the old node when the transition is finished.
          t1.remove().each("end", function() {
            svg.style("shape-rendering", "crispEdges");
            transitioning = false;
          });
        }

        return g;
      }

      function communicateClick(d){

        // add a hook to Shiny
        if( HTMLWidgets.shinyMode ){
          Shiny.onInputChange(el.id + '_click', {name:d[celltext],id:d[cellid]});
        }

        // check for additional clickAction to perform
        if( x.options.clickAction && typeof x.options.clickAction === "function" ){
          x.options.clickAction(d);
        }

      };
      function showSpan(d) {
        if(scale && d.vColorValue){

          ciSpan.style('opacity', 1);
          triangle.attr('transform', 'translate(' + scale(d.vColorValue) + ',20)');
          value.attr('transform', 'translate(' + scale(d.vColorValue) + ',10)').text(format(d.vColorValue));

          if (d.stdErr) {
            ciRect.attr('x', scale(d.vColorValue))
                .attr('width', 0);
            ciRect.transition().duration(750)
                .attr('x', scale(d.vColorValue - d.stdErr))
                .attr('width', 2 * Math.abs(scale(d.vColorValue) - scale(d.vColorValue - d.stdErr)));
            ciLower.style('opacity', 0).attr('transform', 'translate(' + scale(d.vColorValue - d.stdErr) + ',23)').text(format(d.vColorValue - d.stdErr));
            ciLower.transition().duration(750).style('opacity', 1);
            ciUpper.style('opacity', 0)
                .attr('transform', function() {
                    return scale(d.vColorValue + d.stdErr) > (width - margin.left - margin.right - 30) ?
                      'translate(' + (width-margin.left-margin.right)+ ',13)' :'translate(' + scale(d.vColorValue + d.stdErr) + ',23)';
                  })
                .text(format(d.vColorValue + d.stdErr))
                .style('text-anchor', function() {
                  return scale(d.vColorValue + d.stdErr) > (width - margin.left - margin.right - 30) ?
                    'end' : 'start';
                })
            ciUpper.transition().duration(750).style('opacity', 1);

          }

        }
      };
      function hideSpan(d) {
        ciSpan.style('opacity', 0);
        ciSpan.select('rect').attr('width', 0);
      };
      function text(text) {
        text.attr("x", function(d) { return xscale(d.x) + 6; })
            .attr("y", function(d) { return yscale(d.y) + 6; })
            .style("fill", function (d) {
              return idealTextColor( d.color ? d.color : color(leveltwo(d)[celltext]) );
            });
      }

      function rect(rect) {
        rect.attr("x", function(d) { return xscale(d.x); })
            .attr("y", function(d) { return yscale(d.y); })
            .attr("width", function(d) { return xscale(d.x + d.dx) - xscale(d.x); })
            .attr("height", function(d) { return yscale(d.y + d.dy) - yscale(d.y); })
            .style("fill", function(d){
              return d.color ? d.color : color(leveltwo(d)[celltext]);
            })
            ;
      }

      function name(d) {
        return d.parent
            ? name(d.parent) + "." + d[celltext]
            : d[celltext];

      }

      function leveltwo(d){
        return ( typeof d.parent !== "undefined" && d.parent.parent ) ?
          leveltwo( d.parent ) :
          d;
      }

    }

  },

  resize: function(el, width, height, instance) {

  }

});


text:
package org.aikodi.java.core.method;

/**
 *
 */

import java.util.List;

import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.relation.WeakPartialOrder;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.java.core.type.ArrayType;

public class JavaVarargsOrder implements WeakPartialOrder<List<Type>> {

	public static JavaVarargsOrder create() {
		return _protoType;
	}

	private static JavaVarargsOrder _protoType = new JavaVarargsOrder();

	private JavaVarargsOrder() {

	}

	@Override
  public boolean contains(List<Type> first, List<Type> second)
      throws LookupException {
  	// for varags, the last type of the second list is an array type.
    int size = first.size();
		int nbNormalArguments = second.size() - 1;
		boolean result = size >= nbNormalArguments;
    for(int i = 0; result && i < nbNormalArguments; i++) {
      result = result && first.get(i).assignableTo(second.get(i));
    }
    Type other = ((ArrayType) second.get(nbNormalArguments)).elementType();
    for(int i = nbNormalArguments; result && i < size; i++) {
			result = result && first.get(i).assignableTo(other);
    }
    return result;
  }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Logic.Models
{
    public partial class IntegrationServiceEnvironmentNetworkEndpoint
    {
        internal static IntegrationServiceEnvironmentNetworkEndpoint DeserializeIntegrationServiceEnvironmentNetworkEndpoint(JsonElement element)
        {
            Optional<IntegrationServiceEnvironmentNetworkEndPointAccessibilityState> accessibility = default;
            Optional<string> domainName = default;
            Optional<IReadOnlyList<string>> ports = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("accessibility"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    accessibility = new IntegrationServiceEnvironmentNetworkEndPointAccessibilityState(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("domainName"))
                {
                    domainName = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("ports"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    ports = array;
                    continue;
                }
            }
            return new IntegrationServiceEnvironmentNetworkEndpoint(Optional.ToNullable(accessibility), domainName.Value, Optional.ToList(ports));
        }
    }
}


text:
#include<windows.h>

BOOL WINAPI
DllMain(__in  HINSTANCE hinstDLL,
	__in  DWORD fdwReason,
	__in  LPVOID lpvReserved)
{
    return TRUE;
}


text:
package org.ovirt.engine.core.common.errors;

public class VdcBLLException extends RuntimeException {

    private static final long serialVersionUID = 9070362191178977106L;

    public VdcBLLException(VdcBllErrors errCode, RuntimeException baseException) {
        super("VdcBLLException:", baseException);
        VDSError tempVar = new VDSError();
        tempVar.setCode(errCode);
        setVdsError(tempVar);
    }

    public VdcBLLException(VdcBllErrors errCode, String errorStr) {
        super("VdcBLLException: " + errorStr);
        VDSError tempVar = new VDSError();
        tempVar.setCode(errCode);
        setVdsError(tempVar);
    }

    public VdcBLLException(VdcBllErrors errCode) {
        super("VdcBLLException: " + errCode.toString());
        VDSError tempVar = new VDSError();
        tempVar.setCode(errCode);
        setVdsError(tempVar);
    }

    private VDSError privateVdsError;

    public VDSError getVdsError() {
        return privateVdsError;
    }

    public void setVdsError(VDSError value) {
        privateVdsError = value;
    }

    public VdcBllErrors getErrorCode() {
        return getVdsError().getCode();
    }

    public VdcBLLException() {
    }

    @Override
    public String getMessage() {
        return String.format(super.getMessage() + " (Failed with error %1$s and code %2$s)",
                privateVdsError.getCode(),
                privateVdsError.getCode().getValue());
    }

}


text:
using System;

namespace Sharpit.Command
{
    public abstract class Command
    {
        public string Name { get; set; }
        public string[] Aliases { get; set; }

        public Command(string name, string[] aliases)
        {
            Name = name;
            Aliases = aliases;
        }

        public Command(string name)
        {
            Name = name;
            Aliases = null;
        }

        public abstract void execute(CommandSender sender, String message);
    }
}


text:
import React from 'react';

import './FormattingTooltipItemButton.css';

const FormattingTooltipItemButton = props => (
	<button
		className={`formattingTooltipItemButton ${props.className}`}
		onClick={props.onClick}
	>
		{props.children}
	</button>
);

export default FormattingTooltipItemButton;


text:
=begin

Copyright (c) 2015, Koichiro Tamura/Toshinari Naminatsu/Yuki Ishikawa/Tatsuya Onishi/Mamoru Endo/Kenji Suzuki

This software is released under the BSD 2-Clause License.

http://opensource.org/licenses/BSD-2-Clause

=end

# for teachers of lecture

class LectureMember::TeachersController < RunsController

  def prepare_for_adding_assoc_target(assoc_target, pre_assoc_items)
    @academic_year = @background_params.to_h[:academic_year]
    @academic_season = @background_params.to_h[:academic_season]
    @default_since = beginning_of_academic_season
  end
end


text:
#include "SkDraw3D.h"
#include "SkAnimateMaker.h"
#include "SkCanvas.h"
#include "SkTypedArray.h"

#if SK_USE_CONDENSED_INFO == 0

const SkMemberInfo Sk3D_Point::fInfo[] = {
    SK_MEMBER_ALIAS(x, fPoint.fX, Float),
    SK_MEMBER_ALIAS(y, fPoint.fY, Float),
    SK_MEMBER_ALIAS(z, fPoint.fZ, Float)
};

#endif

DEFINE_NO_VIRTUALS_GET_MEMBER(Sk3D_Point);

Sk3D_Point::Sk3D_Point() {
    fPoint.set(0, 0, 0);
}

#if SK_USE_CONDENSED_INFO == 0

const SkMemberInfo Sk3D_Camera::fInfo[] = {
    SK_MEMBER_ALIAS(axis, fCamera.fAxis, 3D_Point),
    SK_MEMBER(hackHeight, Float),
    SK_MEMBER(hackWidth, Float),
    SK_MEMBER_ALIAS(location, fCamera.fLocation, 3D_Point),
    SK_MEMBER_ALIAS(observer, fCamera.fObserver, 3D_Point),
    SK_MEMBER(patch, 3D_Patch),
    SK_MEMBER_ALIAS(zenith, fCamera.fZenith, 3D_Point),
};

#endif

DEFINE_GET_MEMBER(Sk3D_Camera);

Sk3D_Camera::Sk3D_Camera() : hackWidth(0), hackHeight(0), patch(NULL) {
}

Sk3D_Camera::~Sk3D_Camera() {
}

bool Sk3D_Camera::draw(SkAnimateMaker& maker) {
    fCamera.update();
    SkMatrix matrix;
    fCamera.patchToMatrix(patch->fPatch, &matrix);
    matrix.preTranslate(hackWidth / 2, -hackHeight / 2);
    matrix.postTranslate(hackWidth / 2, hackHeight / 2);
    maker.fCanvas->concat(matrix);
    return false;
}

enum Sk3D_Patch_Functions {
    SK_FUNCTION(rotateDegrees)
};

const SkFunctionParamType Sk3D_Patch::fFunctionParameters[] = {
    (SkFunctionParamType) SkType_Float,
    (SkFunctionParamType) SkType_Float,
    (SkFunctionParamType) SkType_Float,
    (SkFunctionParamType) 0 // terminator for parameter list (there may be multiple parameter lists)
};

#if SK_USE_CONDENSED_INFO == 0

const SkMemberInfo Sk3D_Patch::fInfo[] = {
    SK_MEMBER_ALIAS(origin, fPatch.fOrigin, 3D_Point),
    SK_MEMBER_FUNCTION(rotateDegrees, Float),
    SK_MEMBER_ALIAS(u, fPatch.fU, 3D_Point),
    SK_MEMBER_ALIAS(v, fPatch.fV, 3D_Point)
};

#endif

DEFINE_GET_MEMBER(Sk3D_Patch);

void Sk3D_Patch::executeFunction(SkDisplayable* target, int index,
        SkTDArray<SkScriptValue>& parameters, SkDisplayTypes type,
        SkScriptValue* ) {
    SkASSERT(target == this);
    switch (index) {
        case SK_FUNCTION(rotateDegrees):
            SkASSERT(parameters.count() == 3);
            SkASSERT(type == SkType_Float);
            fPatch.rotateDegrees(parameters[0].fOperand.fScalar,
                parameters[1].fOperand.fScalar, parameters[2].fOperand.fScalar);
            break;
        default:
            SkASSERT(0);
    }
}

const SkFunctionParamType* Sk3D_Patch::getFunctionsParameters() {
    return fFunctionParameters;
}


text:
package gui.dialogs;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;

/**
 *
 * @author Alessandro Falappa <alex.falappa@gmail.com>
 */
public class XmlDialog extends javax.swing.JDialog {

    private RSyntaxTextArea staSource;

    public XmlDialog(java.awt.Frame parent) {
        super(parent, true);
        staSource = new RSyntaxTextArea(40, 80);
        staSource.setCodeFoldingEnabled(true);
        staSource.setAntiAliasingEnabled(true);
        staSource.setHighlightCurrentLine(false);
        staSource.setSyntaxEditingStyle("text/xml");
        staSource.setEditable(false);
        initComponents();
    }

    public void setSourceText(String text) {
        staSource.setText(text);
        staSource.setCaretPosition(0);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this
     * method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bClose = new javax.swing.JButton();
        rtsScroller = new RTextScrollPane(staSource);
        bClipCopy = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Request Source");

        bClose.setText("Close");
        bClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCloseActionPerformed(evt);
            }
        });

        bClipCopy.setText("Copy to clipboard");
        bClipCopy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bClipCopyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(bClipCopy)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 405, Short.MAX_VALUE)
                        .addComponent(bClose))
                    .addComponent(rtsScroller, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rtsScroller, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bClose)
                    .addComponent(bClipCopy))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCloseActionPerformed
        setVisible(false);
    }//GEN-LAST:event_bCloseActionPerformed

    private void bClipCopyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bClipCopyActionPerformed
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        StringSelection strSel = new StringSelection(staSource.getText());
        clipboard.setContents(strSel, null);
    }//GEN-LAST:event_bClipCopyActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bClipCopy;
    private javax.swing.JButton bClose;
    private org.fife.ui.rtextarea.RTextScrollPane rtsScroller;
    // End of variables declaration//GEN-END:variables
}


text:
package com.tq.requisition.autoMapper;

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

import com.tq.requisition.domain.model.registedAgricultureInfo.RegistedAgricultureInfo;
import com.tq.requisition.presentation.dto.registedAgr.RegistedAgricultureInfoDto;

public class RegistedAgricMapper {
	public static RegistedAgricultureInfo toModel(RegistedAgricultureInfoDto dto) {
		RegistedAgricultureInfo model = new RegistedAgricultureInfo();
		model.setAddress(dto.getAddress());
		model.setDel(dto.isDel());
		model.setIdNumber(dto.getIdNumber());
		model.setIsRemove(dto.isRemove());
		model.setIsSetting(dto.isSetting());
		model.setIsSocialSecurity(dto.isSocialSecurity());
		model.setIsTransfer(dto.isTransfer());
		model.setName(dto.getName());
		model.setPolicyStateId(dto.getPolicyStateId());
		model.setUserStateId(dto.getUserStateId());
		model.setUserStateStr(dto.getUserStateStr());
		model.setPolicyStr(dto.getPolicyStr());
		return model;
	}

	public static RegistedAgricultureInfoDto toDto(RegistedAgricultureInfo model) {
		RegistedAgricultureInfoDto dto = new RegistedAgricultureInfoDto();
		dto.setAddress(model.getAddress());
		dto.setDel(model.getDel());
		dto.setIdNumber(model.getIdNumber());
		dto.setRemove(model.getIsRemove());
		dto.setSetting(model.getIsSetting());
		dto.setSocialSecurity(model.getIsSocialSecurity());
		dto.setTransfer(model.getIsTransfer());
		dto.setName(model.getName());
		dto.setPolicyStateId(model.getPolicyStateId());
		dto.setUserStateId(model.getUserStateId());
		dto.setUserStateStr(model.getUserStateStr());
		dto.setPolicyStr(model.getPolicyStr());
		dto.setId(model.getId());
		return dto;
	}

	public static List<RegistedAgricultureInfoDto> toDtoList(List<RegistedAgricultureInfo> models) {
		List<RegistedAgricultureInfoDto> dtos = new ArrayList<RegistedAgricultureInfoDto>();
		for (RegistedAgricultureInfo registedAgricultureInfo : models) {
			dtos.add(toDto(registedAgricultureInfo));
		}
		return dtos;
	}

	public static List<RegistedAgricultureInfo> toModelList(List<RegistedAgricultureInfoDto> dtos) {
		List<RegistedAgricultureInfo> models = new ArrayList<>();
		for (RegistedAgricultureInfoDto registedAgricultureInfoDto : dtos) {
			models.add(toModel(registedAgricultureInfoDto));
		}
		return models;
	}
}


text:
require "spec_helper"

describe BlockTypsController do
  describe "routing" do

    it "routes to #index" do
      get("/block_typs").should route_to("block_typs#index")
    end

    it "routes to #new" do
      get("/block_typs/new").should route_to("block_typs#new")
    end

    it "routes to #show" do
      get("/block_typs/1").should route_to("block_typs#show", :id => "1")
    end

    it "routes to #edit" do
      get("/block_typs/1/edit").should route_to("block_typs#edit", :id => "1")
    end

    it "routes to #create" do
      post("/block_typs").should route_to("block_typs#create")
    end

    it "routes to #update" do
      put("/block_typs/1").should route_to("block_typs#update", :id => "1")
    end

    it "routes to #destroy" do
      delete("/block_typs/1").should route_to("block_typs#destroy", :id => "1")
    end

  end
end


text:
import validators
import unittest
import yaml
import sys
import os

# MAKING SURE THAT SETTINGS.YAML IS GOING TO BE FOUND!
TEEKA_SETTINGS = os.getenv('TEEKA_SETTINGS', "../settings.yaml")

# ADDING PARENT AND CURRENT DIRECTORIES INTO SYSTEM PATH
CURREN_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(CURREN_DIR, os.pardir))
sys.path.append(CURREN_DIR)

from server.setting_parser import SettingsParser

class TestStringMethods(unittest.TestCase):

    def setUp(self):
        self.settings_file = TEEKA_SETTINGS
        self.settings_parser_instance = SettingsParser(self.settings_file)

    def tearDown(self):
        pass

    def test_port(self):
        self.assertIsInstance(self.settings_parser_instance.get_port(), int)
        self.assertLess(self.settings_parser_instance.get_port(), 65536)
        self.assertGreater(self.settings_parser_instance.get_port(), 0)

    def test_ip(self):
        self.assertTrue(validators.ipv4(self.settings_parser_instance.get_ip()))

    def test_data_path(self):
        self.assertTrue(os.path.exists(self.settings_parser_instance.get_data_path()))
        self.assertTrue(os.path.isdir(self.settings_parser_instance.get_data_path()))
        self.assertTrue(os.access(self.settings_parser_instance.get_data_path(), os.W_OK))
        self.assertTrue(os.access(self.settings_parser_instance.get_data_path(), os.R_OK))

    def test_meta_store_engine(self):
        meta_stores = ["sqlite3"]
        self.assertIsInstance(self.settings_parser_instance.get_meta_store_engine(), str)
        self.assertIn(self.settings_parser_instance.get_meta_store_engine(), meta_stores)

    def test_meta_store_name(self):
        self.assertIsInstance(self.settings_parser_instance.get_meta_store_name(), str)
        self.assertGreater(len(self.settings_parser_instance.get_meta_store_name()), 0)

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


text:
<?xml version="1.0" encoding="utf-8"?>
<products xmlns:xlink="http://www.w3.org/1999/xlink">
   <latestpdf>MidoNet_Troubleshooting_Guide_JA_5.0-SNAPSHOT-latest.pdf</latestpdf>
   <pdfoutname>MidoNet_Troubleshooting_Guide_JA_5.0-SNAPSHOT.pdf</pdfoutname>
   <docname>MidoNet トラブルシューティング ガイド</docname>
   <productname>MidoNet トラブルシューティング ガイド</productname>
   <webappname>troubleshooting-guide_ja</webappname>
   <pominfo>
      <groupid>org.midonet</groupid>
      <artifactid>midonet-docs-troubleshooting-guide-ja</artifactid>
      <version>5.0-SNAPSHOT</version>
      <pomname>midonet-docs-troubleshooting-guide-ja v5.0-SNAPSHOT</pomname>
   </pominfo>
</products>


text: export { MarineWarning16 as default } from "../../";


text:
layout: post
author: gsagie
title: Kuryr and Neutron Existing Resources
date: 2016-5-15 16:25:06 -0700
categories:
- SDN
- Openstack
- Docker
- Kuryr
- Neutron
tags:
- OpenStack
- Kuryr
- Docker
---

If you don`t know what Kuryr is by now, shame on you!  please check out
our [OpenStack Tokyo Kuryr Introduction talk](https://www.openstack.org/videos/video/tokyo-2474)
or read [my blog post](http://galsagie.github.io/2015/08/24/kuryr-part1/) about it.

# Kuryr Current Status

Mitaka was the first actual release that we fully worked on Kuryr and i wanted
to describe some of the nice features that we support in our current version.

In this post i will describe the ability to attach elements to existing Neutron/OpenStack resources
which is useful for many different use cases, in the next part i will describe our Kubernetes
integration and nested containers/Magnum support which are two really nice features
we have in late progress stages.

The following diagram depicts the current components we have in Kuryr:

As you can see Kuryr already has full integration working with Docker libnetwork and
with Docker Swarm as a by product of the above.
What we essentially do is implementing a libnetwork remote driver and IPAM driver that maps
the Docker calls into Neutron resources and model.

This works well and as user creates new resources like networks in Docker these networks are created
in Neutron on the fly and Kuryr keeps the mapping between the two entities.
However, we have noticed that we can provide much more by allowing users to attach their newly created
Docker network into an existing Neutron network.

# The Use Cases

## Connecting VMs, Containers and Bare Metal

Allowing to attach into existing networks enable this very useful ability which users really
need and want.
The ability to connect VMs, containers and bare metal servers to the same virtual network in
a seamless management experience and have a consistent networking for all the three.

There are many reasons why you want to do that and there is no real good reason why you
should`nt be able to do it, connecting your OpenStack and containers workloads together
and applying a unified security, isolation and policy profiles on them.

This simple feature in Kuryr allow all of the above using Neutron as we should soon see.

## Bulk creations

Another use case that i hear a lot about are users that wants to deploy batches
of containers and want to do it as fast as possible.
Sometimes with many different networks and newly created ports.

What we noticed is that the API calls to Neutron in these cases can be time consuming
and slow down this process, this is a common problem for any networking plugin
implementation.

By pre-allocating networks/ports in Neutron and then only binding these elements
from their pools when the user needs (when the user uses the Docker API or any other
orchestration/management tool that does) we are able to improve this process
quite significantly.

Attaching to existing Neutron resources feature enable us to provide and achieve this.

# The Flow

The following steps demonstrate how to use this feature with Kuryr.
First we create a Docker network using Docker CLI API and specify to Docker to use
Kuryr as the networking driver and IPAM driver.

If we look at Neutron, we can see that a new network was created with "kuryr" in its prefix

We can see that Kuryr save the mapping between Neutron network id and Docker network id using
a new feature in Neutron called resource tags.
This is a feature that was designed by the Kuryr team and implemented in Neutron exactly for
a use case like this (and many others as described in the spec).

You can read more about [this feature in this document.](http://docs.openstack.org/developer/neutron/devref/tag.html)

What we see above is that the user creates a network in Docker and it is automatically
added to Neutron by Kuryr with the appropriate mapping, any new container that is
added to this Docker network will be attached to the same Neutron network.

But what if there is already a Neutron network that already has few VMs attached to it.
The user can specify the network name or network id as a Docker options.
Kuryr instead of creating a new Neutron network will attach the containers to the existing
network.

We can see that Kuryr keeps a special tag on the network to indicate that this is not a network
created by Kuryr.
This is important as we dont want to delete this network when the user delete the Docker network, just
remove the associations (tha mapping tags on the Neutron network).

# Future

Currently, Kuryr only support attaching to existing networks from one Docker control plane, for example
only from one environment of Docker Swarm.
However, we see strong use cases that users may want to connect containers to the same network from two
different Docker Swarm instances for example.

Enabling this is rather simple with the above feature, we will just need to manage tags per a Docker
Swarm environment, this is something we are looking to support really soon.

# Summary

I think this post demonstrate the power of Kuryr and how we can help and simplify life for users
that deploy OpenStack workloads mixed with containers workloads in a very easy manner.

In the next posts i am going to describe other exciting features we are working on like Kubernetes
Integration and Nested containers support.

If you want to take part of our journey feel free to reach out to me or join our IRC channel
in freenode (#openstack-kuryr)


text:
package br.com.odara.app.agendou.controllers;

import java.util.List;

import javax.transaction.Transactional;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import br.com.odara.app.agendou.daos.EmpresaDAO;
import br.com.odara.app.agendou.models.Empresa;

@RestController
@Transactional
@RequestMapping("/")
public class IndexController {

	private static final Logger logger = Logger.getLogger(IndexController.class);

	private List<Empresa> empresas;

	@Autowired
	private EmpresaDAO dao;

	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView view = new ModelAndView("public/index");
		empresas = dao.listAll();
		view.addObject("empresas", empresas);
		return view;
	}

	@RequestMapping(value="/cadastro", method=RequestMethod.GET)
	public ModelAndView cadastro() {
		ModelAndView view = new ModelAndView("public/cadastro");
		return view;
	}

	@RequestMapping(value="/salvar", method=RequestMethod.POST)
	public ModelAndView salvarEmpresa( @RequestBody Empresa empresa ) {
		ModelAndView view = new ModelAndView("public/cadastro");
		logger.info(empresa.getRazaoSocial());
		logger.info(empresa.getCnpj());
		dao.save(empresa);
		return view;
	}

}


text:
@implementation UIDevice (Addition)

- (NSString *)deviceIdentifier
{

//    return @"F63FF6B4-AE44-4805-81F3-E1AAEAE15E9C";

    NSString *identify =nil;
//    if (IOS6_OR_LATER)
//    {
//        KeychainItemWrapper * keychin                                                          = [[KeychainItemWrapper alloc]initWithIdentifier:@"SDIDFV" accessGroup:nil];
//        NSString *idfv                                                                         = [keychin objectForKey:(__bridge id)kSecValueData];
//        NSLog(@"%@",idfv);
//        if (idfv.length == 0) {
//            idfv                                                                                = [[[UIDevice currentDevice]identifierForVendor]UUIDString];
//
//            [keychin setObject:idfv forKey:(__bridge id)kSecValueData];
//        }w//        NSLog(@"%@",idfv);
//        return idfv;
//
////        identify= [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
//    }
//    else
//    {
        identify = [[[UIDevice currentDevice]identifierForVendor]UUIDString];
//    }

    return identify;
}

@end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>service.models.repository</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Trees

         Indices

         Help

Jisc Publications Router

        Package service ::
        Package models ::
        Module repository

[hide private]

[frames] | no frames]

Module repository

source code

Model objects used to represent interactions with repositories

        Classes
        [hide private]

        RepositoryConfig

      Class to represent the configuration information that repositories provide to the system
to enable routing based on RoutingMetadata extracted from notifications

        MatchProvenance

      Class to represent a record of a match between a RepositoryConfig and a RoutingMetadata object

        RetrievalRecord

      Class to allow us to record a retrieval of a file for the purposes of later reporting

         Trees

         Indices

         Help

Jisc Publications Router

    Generated by Epydoc 3.0.1 on Tue Dec  1 17:26:35 2015

      http://epydoc.sourceforge.net


text:
import {TBlockElement} from "../FD/IFD";
import {TypeToComponentMapService} from "../TypeToComponentMap";
import {ElementContainerComponent} from "./ElementContainerComponent";
import {FormattedDocument} from "../Types/FormattedDocument";
import {IFormattedDocumentStyle} from "../Interfaces/IFormattedDocumentStyle";

export class FormattedDocumentComponent
    extends ElementContainerComponent<FormattedDocument, IFormattedDocumentStyle, TBlockElement> {
}

TypeToComponentMapService.set(FormattedDocument, FormattedDocumentComponent);


text:
<?php

namespace Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Factory\Service;

use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Service\ChangeSecurityQuestionsSessionService;
use DvsaClient\MapperFactory;
use Zend\ServiceManager\Factory\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Session\Container;

use Interop\Container\ContainerInterface;

class ChangeSecurityQuestionsSessionServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $this($serviceLocator, ChangeSecurityQuestionsSessionService::class);
    }

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $sessionContainer = new Container(ChangeSecurityQuestionsSessionService::UNIQUE_KEY);

        $mapperFactory = $container->get(MapperFactory::class);

        return new ChangeSecurityQuestionsSessionService(
            $sessionContainer,
            $mapperFactory
        );
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="Highlighter.cs" company="01 Binary">
//     Copyright (C) 01 Binary.
// </copyright>
//-----------------------------------------------------------------------

namespace SyntaxHighlighter
{
    /// <summary>
    /// Performs code syntax highlighting.
    /// </summary>
    public class Highlighter
    {
        /// <summary>
        /// The pre-defined name for pattern used to detect token separators.
        /// </summary>
        private static readonly string SeparatorsPattern = "separators";

        /// <summary>
        /// The base path for loading transform definitions.
        /// </summary>
        private string transformPath;

        /// <summary>
        /// The debug options for diagnosing unexpected token transforms.
        /// </summary>
        private Options options;

        /// <summary>
        /// The current transform definition for the current code block type.
        /// </summary>
        private TransformDefinition transformDefinition;

        /// <summary>
        /// The transform buffer.
        /// </summary>
        private Buffer buffer;

        /// <summary>
        /// Initializes a new instance of the <see cref="Highlighter"/> class.
        /// </summary>
        public Highlighter()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Highlighter"/> class.
        /// </summary>
        /// <param name="transformBasePath">The base path for loading transform definitions.</param>
        public Highlighter(string transformBasePath)
        {
            this.transformPath = transformBasePath;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Highlighter"/> class.
        /// </summary>
        /// <param name="transformBasePath">The base path for loading transform definitions.</param>
        /// <param name="highlightOptions">The debug options for diagnosing unexpected token transforms.</param>
        public Highlighter(string transformBasePath, Options highlightOptions)
        {
            this.transformPath = transformBasePath;
            this.options = highlightOptions;
        }

        /// <summary>
        /// Transform the code by adding highlight markup and styles to recognized tokens.
        /// </summary>
        /// <param name="code">The code block to transform.</param>
        /// <param name="type">The code block type.</param>
        /// <returns>The transformed block.</returns>
        public string Transform(string code, string type)
        {
            this.transformDefinition = TransformDefinitionFactory.Load(
                this.transformPath, type, this.options);

            this.buffer = new Buffer(
                code, this.transformDefinition.Patterns[SeparatorsPattern], this.options);

            while (!this.buffer.Eof)
            {
                if (!this.transformDefinition.Apply(this.buffer))
                {
                    this.buffer.SkipToken();
                }

                this.buffer.NextToken();
            }

            return this.buffer.Data;
        }
    }
}


text:
#ifndef ASCII_H_6491BD47
#define ASCII_H_6491BD47

#include "../file.h"

TextArtFile* load_ascii_file(char *filename);

#endif /* end of include guard: ASCII_H_6491BD47 */


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entries_model extends DataMapper
{
    public $table = "entries";
    public $has_one = array(
        'content_types' => array(
            'class' => 'content_types_model',
            'other_field' => 'entries',
            'join_self_as' => 'entry',
            'join_other_as' => 'content_type',
        ),
    );

    public $has_many = array(
        'entries_data' => array(
            'class' => 'entries_data_model',
            'other_field' => 'entries',
            'join_self_as' => 'entry',
        ),
        'categories' => array(
            'class' => 'categories_model',
            'other_field' => 'entries',
            'join_self_as' => 'entry',
            'join_other_as' => 'category',
            'join_table' => 'categories_entries',
        ),
    );

    public function get_entry_revisions() {
        $CI =& get_instance();
        $CI->load->model('revisions_model');

        $Revisions = new Revisions_model();
        $Revisions->where_related('revision_resource_types', 'key_name', 'ENTRY')
                  ->where('resource_id', $this->id)
                  ->order_by('id', 'desc')
                  ->get();

        return $Revisions;
    }
}


text:
 Create Task

    <ng-form name="createTaskDialog" novalidate role="form">

            Task Name
            <input type="text" class="form-control" ng-model="data.name" />

            Description
            <textarea class="form-control" ng-model="data.description" />

            API key
            <input type="text" class="form-control" ng-model="data.key" />
            Enter the API key that you got during registration.

    </ng-form>

    <button class="btn btn-success" ng-click="done()">Create</button>
    <button class="btn btn-default" ng-click="$close()">Close</button>


text:
/*
* Property.java
*
* User: Greg Schueler greg@dtosolutions.com
* Created: 7/27/11 4:53 PM
*
*/
package com.dtolabs.rundeck.core.plugins.configuration;

import java.util.List;
import java.util.Map;

/**
 * Property describes a configuration property of a provider
 *
 * @author Greg Schueler greg@dtosolutions.com
 */
public interface Property {
    /**
     * Available property types
     */
    static enum Type {
        /**
         * A simple string input property
         */
        String,
        /**
         * A boolean input property
         */
        Boolean,
        /**
         * An integer input property
         */
        Integer,
        /**
         * A long input property
         */
        Long,
        /**
         * A multiple selection input property
         */
        Select,
        /**
         * A string input property with a select
         */
        FreeSelect,
        /**
         * A set of checkbox options
         */
        Options
    }

    /**
     * @return descriptive name of the property
     */
    public String getTitle();

    /**
     * @return property key to use
     */
    public String getName();

    /**
     * @return description of the values of the property
     */
    public String getDescription();

    /**
     * @return the property type
     */
    public Type getType();

    /**
     * @return the validator for this property
     */
    public PropertyValidator getValidator();

    /**
     * @return true if an empty value is not allowed
     */
    public boolean isRequired();

    /**
     * @return the default value of the property, or default select value to select
     */
    public String getDefaultValue();

    /**
     * @return a list of values for a select property
     */
    public List<String> getSelectValues();

    /**
     * @return a map of display labels to use for the select values, keyed by value
     */
    public Map<String, String> getSelectLabels();

    /**
     * @return the scope of this property, i.e. where the value can be retrieved and overridden, or null to indicate
     * the default scope.
     */
    public PropertyScope getScope();

    /**
     * @return a map of optional rendering options for the UI
     */
    public Map<String, Object> getRenderingOptions();
}


text:
package net.minidev.ovh.core;

import java.util.HashMap;
import java.util.Map;

public class OvhEntryPoint {
	private final static Map<String, String> endpoints;
	public final static String OVH_EU = "https://eu.api.ovh.com/1.0";
	public final static String OVH_CA = "https://ca.api.ovh.com/1.0";
	public final static String KS_EU = "https://eu.api.kimsufi.com/1.0";
	public final static String KS_CA = "https://ca.api.kimsufi.com/1.0";
	public final static String SO_EU = "https://eu.api.soyoustart.com/1.0";
	public final static String SO_CA = "https://ca.api.soyoustart.com/1.0";
	public final static String RA_EU = "https://api.runabove.com/1.0";
	public final static String RA_CA = "https://api.runabove.com/1.0";

	static {
		endpoints = new HashMap<String, String>();
		endpoints.put("ovh-eu", OVH_EU);
		endpoints.put("ovh-ca", OVH_CA);
		endpoints.put("kimsufi-eu", KS_EU);
		endpoints.put("kimsufi-ca", KS_CA);
		endpoints.put("soyoustart-eu", SO_EU);
		endpoints.put("soyoustart-ca", SO_CA);
		endpoints.put("runabove", RA_EU);
		endpoints.put("runabove-ca", RA_CA);
	}
}


text:
title: "Development Tools"
permalink: /manual/devtools/
author: yaw@aem.design
editor: max@aem.design
comments: true
redirect_from:
  - /manual/projects/
---

{% include toc_sticky.html %}

# Development Tools

## Git

The projects sources are managed with Git.

## Apache Maven

Maven manages the build lifecycle for the AEM content packages, service bundles and configurations, as well their dependencies. Maven 3.5.0 was used during the development of the project.

The content package projects uses 'content-package-maven-plugin' to create a CRX content package.

 The project was originally created using the 'CQ Project Maven Archetype' ([https://www.cqblueprints.com/setup/maven.html](https://www.cqblueprints.com/setup/maven.html)).

The AEM project contains 4 child modules:

1. aemdesign-aem-common

    1. Embeds aemdesign-aem-services under /apps/aemdesign/install

2. aemdesign-aem-services

3. aemdesign-aem-config

    2. Creates a configuration package per environment

4. aemdesign-aem-content

### Package Build

Maven commands when run in the aemdesign-aem project.

#### Local Development Build

```bash
mvn -PautoInstallPackage clean package
```

#### Local Development Service Module Build

```bash
mvn -pl services clean package
```

#### Local Development Common Module Build

```bash
mvn -pl common clean package
```

Note: this embeds the last built service module. To ensure the latest build, use -pl services,common in the command parameters and the order of the modules is important.

#### Local Development Config Module Build

```bash
mvn -pl config clean package
```

#### Local Development Content Module Build

```bash
mvn -pl content clean package
```

#### Full Build and Deploy to Repository

```bash
mvn clean deploy
```

### JGitFlow Plugin

The JGitFlow Maven Goals manages the Git Flow branching strategy.  The table below lists common usages of the JGitFlow. All commands are run in the 'aemdesign-aem-dam' parent module.

| Maven Goals                     | Actions                                     |
|---------------------------------|---------------------------------------------|
| mvn jgitflow:feature-start      | Creates and checks out the new feature branch from /develop |
| mvn jgitflow:feature-finish     | Merges the current working feature branch into /develop and deletes the feature branch |
| mvn jgitflow:release-start      | Creates a new /release/[build_version] branch from /develop |
| mvn jgitflow:release-finish     | Creates a tag named version/[build_version] from /release/[build_version] and merges /release/[build_version] back into /develop and /master. Finally, JGitFlow deletes /release/[build_version]. This ensures that there is only one release in any point in time |
| mvn jgitflow:hotfix-start       | Creates a new /hotfix/[build_version] branch from /master |
| mvn jgitflow:hotfix-finish      | Creates a tag named version/[build_version] from /hotfix/[build_version] and merges /hotfix/[build_version] back into /develop and /master. Finally, JGitFlow deletes /hotfix/[build_version] |

#### Plugin Usage

Branching is not be intended to be limited to the JGitFlow Maven Goals. Its underlying actions are standard Git commands and as such they can be repeated with the git command line tool. Also, there are cases where the git command line tool is required. One such case is when a new feature is required in the current release, in which case the feature is branched from */release/[build_version]* and not */develop*. Another case is resolving conflicts during branch merging.

For details on Git Flow, see the Processes section on [Git Flow](/manual/process#git-flow)

For additional details on the plugin [https://bitbucket.org/atlassian/jgit-flow/wiki/Home](https://bitbucket.org/atlassian/jgit-flow/wiki/Home).

## Ansible Playbooks

There are three types of playbooks that perform automated tasks; operation playbooks, group playbooks and site playbooks. A group playbook provisions servers and applications while a site playbook provisions an entire platform. The site playbook will typically run a few group playbooks which will form the platform. Operation playbooks performs regular tasks on groups such as repository maintenance and package deployments.

By convention, the group playbooks are named after the group vars and site playbooks are prefixed with 'site-'.

### Site Playbooks

#### site.yml

The site playbook manages the AEM platform and its testing environments with the use of inventories.

The following playbook command will provision a complete site using the local development inventory,

```bash
./devops accesslocal
```

or:

```bash
ansible-playbook -i inventory/localdev site.yml --user aemdesign --private-key ../aemdesign-vm/keys/current/aemdesign
```

A well designed playbook should perform all tasks required to provision a site in a single command. However, there are scenarios where only a part of the playbook is required. It is possible to activate a subset of tasks by running a playbook with tags. For example, by adding the --tags parameter to the ansible-playbook command.

The following are tags that are in use:

* docker-host-stop-containers

* docker-host-stopped

* docker-images-build

* Install-packages

To list all tags in the site playbook,

```bash
ansible-playbook site.yml --list-tags
```

Similarly, playbooks may skip parts of the play with the use of the --skip-tags parameter. For example, in cases where the Docker images are built separately, a playbook that is provisioning a site may decide not to rebuild the images and instead pull them from a Docker registry.

The practice of tagging tasks is best done during the development of roles. This allows the developer to not only exercise the new roles but also test that tags work in isolation.

A recommended approach in developing playbooks is to start with the localdev inventory and promote the changes through each of the environments. The project is designed with roles, groups and host variable precedence to facilitate this development process.

The following environments have inventories configured (in order of promotion):

* localdev

* develop

* sit

* uat

* training

* staging

* production

The platform consists of servers and services. In order to provision the platform, the site playbook includes the following group playbooks that perform the actual provisioning:

* convoy.yml

    * See [Convoy Volume Plugin](/manual/osenv/#convoy-volume-plugin)

* server.yml

* applications.yml

* solr.yml

* author.yml

* publisher.yml

* processing.yml

* dispatcher.yml

* esb.yml

#### site-teardown.yml

Teardown playbook is for removing all applications and their data in a Docker host. Its purpose is to prepare the servers such that a new site can be provisioned without any dependencies on a previous state.

For example, it can be used to rebuild the develop environment on a daily basis and/or prepare the UAT environment before each test cycle.

Sample usage,

```bash
ansible-playbook -i inventory/localdev site-teardown.yml --user aemdesign --private-key ../aemdesign-vm/keys/current/aemdesign
```

#### site-devops.yml

Deploys and configures the Management services.

### Operations Playbooks

#### operation-aem-deploy.yml

Installs versioned AEM content packages from a Maven repository to each of the authors, publishers and processing servers defined in the inventory.

#### operation-esb-deploy.yml

Installs versioned ESB packages from a Maven repository to the Mulesoft ESB hot deploy folder *'/opt/mule/apps'*.

#### operation-oak-compaction.yml

Operations playbook that implements the revision cleanup for the AEM Repository. Refer to the Adobe's online documentation under '*Maintaining the Repository *'for the significance of this operation:

[https://docs.adobe.com/docs/en/aem/6-3/deploy/platform/storage-elements-in-aem-6.html](https://docs.adobe.com/docs/en/aem/6-3/deploy/platform/storage-elements-in-aem-6.html)

#### operation-volume-fstrim.yml

Operations playbook to releasing unused blocks used by Convoy thinly provisioned volume. (refer to: [Thin Volume Management](/manual/osenv/#thin-volume-management)).

### Group Playbooks

There are two group playbooks. Tasks that maintain the server and tasks that manages an application.

#### Server Playbooks

| Playbook                        | Actions                                     |
|---------------------------------|---------------------------------------------|
| server.yml                      | Configures Red Hat Enterprise Linux servers. The following tasks are performed (role references in parenthesis),
Adding Network Interfaces before other roles requiring network connectivity ( server-network-interfaces).
Installation of RPMs using YUM
Installation of security updates
Installation of Python Packages required by Ansible (python-packages)
Configuration of the Docker service  (docker-host)
Configuration of Docker networks (docker-network)
Configuration of Server IPTables (server-iptables) |
| applications.yml                | Configures common services for the Docker service and its containers.
Deploys Consul servers
Deploys Consul clients
Deploys a Registrator service for all Consul servers and clients |
| convoy.yml                      | Deploys and configures the Convoy Docker plugin.
Creates a data device in the rhel volume group
Creates a metadata device in the rhel volume group
Installs Convoy as a system service
Stats the Convoy system service |

#### Application Playbooks

| Playbook                        | Actions                                     |
|---------------------------------|---------------------------------------------|
| author.yml                      | Automates the deployment and configuration of AEM authors.
Deploys AEM
Installs AEM Content Packages such as,
Feature Packs
Hotfixes
ACS Commons
3rd Party Content Packages
Configures Replication Agents
Configures Workflows |
| publisher.yml                   | Automates the deployment and configuration of AEM publishers.
Deploys AEM
Installs AEM Content Packages such as,
Feature Packs
Hotfixes
ACS Commons
3rd Party Content Packages |
| dispatcher.yml                  | Deploys and configures an author and publisher dispatcher.
Builds and configures the author and publisher dispatcher services Starts the services |
| esb.yml                         | Deploys and configures the ESB service |
| processing.yml                  | Automates the deployment and configuration of AEM processing.
Deploys AEM
Installs AEM Content Packages such as,
Feature Packs
Hotfixes
ACS Commons
3rd Party Content Packages |
| solr.yml                        | Deploys and configures Solr Cloud service |

### Management Playbooks

Deploys and configures management services in the AEM DAM Platform.  These are devops services such as,

1. Jenkins

2. Nexus

These are discussed in detail in the [Development Tools](/manual/devtools/#development-tools) section.

### Libraries

Ansible Modules adding AEM and Docker tasks to Playbooks.

Python source code for the modules can be found under the project location; *'aemdesign-deploy/library/ansible-modules'*.

| Module                          | Action                                     |
|---------------------------------|---------------------------------------------|
| aem_bundles_wait_activated.py   | Polls AEM at '/system/console/bundles.json' until ALL bundles are activated |
| docker_containers.py            | Starts or stops ALL Docker containers on a server |
| docker_images.py                | Removes ALL Docker images on a server |
| docker_volumes.py               | Removes ALL Docker volumes on a server |

There are additional modules in the project. They are omitted as they are documented in [https://github.com/wildone/pyaem](https://github.com/Sensis/pyaem).


text:
namespace safe_browsing {

MockIncidentReceiver::MockIncidentReceiver() {}

MockIncidentReceiver::~MockIncidentReceiver() {}

}  // namespace safe_browsing


text:
#!/bin/bash
set -e
export FABRIC_REPO=joequant
export PATH=/opt/gopath/bin:/opt/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

#install go and protobuf
rm -f /var/lib/apt/lists/*Sources* /var/lib/apt/lists/*universe*
sed -i /universe/d /etc/apt/sources.list
apt-get purge -y eject whiptail
apt-get install -y curl binutils golang-1.6-go apt-utils
rm -rf /var/cache/apt /usr/share/doc /usr/share/man
rm -rf /usr/share/go-1.6/test
ln -s $GOROOT /opt/go
ln -s $GOROOT /opt/gopath
mkdir -p /var/hyperledger/db
mkdir -p /var/hyperledger/production
strip --strip-unneeded /usr/bin/* /usr/sbin/* || true
strip --strip-unneeded  $GOROOT/bin/* $GOROOT/pkg/tool/*/* || true
apt-get install -y protobuf-compiler libsnappy-dev zlib1g-dev libbz2-dev \
        unzip build-essential git-core libstdc++-5-dev \
	--no-install-recommends --no-install-suggests
strip --strip-unneeded /usr/bin/* /usr/sbin/* || true
strip --strip-unneeded /usr/lib/* /usr/local/lib/* || true
rm -rf /var/cache/apt /usr/share/doc /usr/share/man

#install rocksdb
cd /tmp
git clone --single-branch -b v4.6.1 --depth 1 https://github.com/facebook/rocksdb.git
cd rocksdb
PORTABLE=1 make shared_lib
INSTALL_PATH=/usr/local make install-shared
ldconfig
cd ..
rm -rf rocksdb
apt-get purge -y make patch xz-utils g++ libdpkg-perl \
	    libtimedate-perl sgml-base xml-core xdg-user-dirs manpages \
	    krb5-locales libglib2.0-0 libxtables11 shared-mime-info \
	    ifupdown rename
apt-get purge -y --allow-remove-essential sed e2fsprogs
apt-get autoremove -y
strip --strip-unneeded /usr/local/lib/* || true

# install hyperledger
mkdir -p $GOPATH/src/github.com/hyperledger
cd $GOPATH/src/github.com/hyperledger
git clone --single-branch --depth 1 https://github.com/$FABRIC_REPO/fabric.git
cd $GOPATH/src/github.com/hyperledger/fabric/peer
CGO_CFLAGS=" " CGO_LDFLAGS="-lrocksdb -lstdc++ -lm -lz -lbz2 -lsnappy" go install
curl https://raw.githubusercontent.com/joequant/hyperledger/master/config/core.yaml > $GOPATH/bin/core.yaml
go clean

cd $GOPATH/src/github.com/hyperledger/fabric/membersrvc
CGO_CFLAGS=" " CGO_LDFLAGS="-lrocksdb -lstdc++ -lm -lz -lbz2 -lsnappy" go install
curl https://raw.githubusercontent.com/joequant/hyperledger/master/config/membersrvc.yaml > $GOPATH/bin/membersrvc.yaml
go clean

strip $GOPATH/bin/* || true
cp $GOPATH/src/github.com/hyperledger/fabric/consensus/noops/config.yaml $GOPATH/bin


text:
<?= __d('users', 'Password Recovery'); ?>

<?= __d('users', 'Reset your password for {0}', SITE_TITLE); ?>

                <?= Session::getMessages(); ?>

                <form action="<?= site_url('password/remind'); ?>" method='POST' role="form">

                <fieldset>

<?= __d('users', 'Please enter your e-mail address to be sent a link to reset your password.'); ?>

<input type="email" name="email" id="email" class="form-control input-lg col-xs-12 col-sm-12 col-md-12" placeholder="<?= __d('users', 'E-mail'); ?>">

                    <?php if (Config::get('reCaptcha.active') === true) { ?>

                    <?php } ?>

                            <input type="submit" name="submit" class="btn btn-success col-sm-10" value="<?= __d('users', 'Send Reset Link'); ?>">

                            <a href="<?= site_url('login'); ?>" class="btn btn-link pull-right"><?= __d('users', 'Login'); ?>

                </fieldset>

                <input type="hidden" name="_token" value="<?= csrf_token(); ?>" />

                </form>

<?php if (Config::get('reCaptcha.active') === true) { ?>

<?php } ?>


text:
import { FileInput } from './FileInput';

export {
  FileInput
}


text:
#!/usr/bin/env node

/**
 * bitcoind.js example
 */

process.title = 'bitcoind_stripped.js';

/**
 * bitcoind
 */

var bitcoind = require('../index_stripped.js')({
  directory: '~/.libbitcoind-example'
});

bitcoind.on('error', function(err) {
  bitcoind.log('error="%s"', err.message);
});

bitcoind.on('open', function(status) {
  bitcoind.log('status="%s"', status);
});


text:
package org.apache.uima.taeconfigurator.editors.ui;

import org.apache.uima.resource.ExternalResourceDescription;
import org.apache.uima.resource.FileLanguageResourceSpecifier;
import org.apache.uima.resource.FileResourceSpecifier;
import org.apache.uima.resource.ResourceSpecifier;
import org.apache.uima.resource.impl.ExternalResourceDescription_impl;
import org.apache.uima.resource.impl.FileLanguageResourceSpecifier_impl;
import org.apache.uima.resource.impl.FileResourceSpecifier_impl;
import org.apache.uima.resource.metadata.ExternalResourceBinding;
import org.apache.uima.resource.metadata.impl.ExternalResourceBinding_impl;
import org.apache.uima.taeconfigurator.editors.MultiPageEditor;
import org.apache.uima.taeconfigurator.editors.ui.dialogs.AddExternalResourceDialog;
import org.apache.uima.taeconfigurator.wizards.ResourceManagerConfigurationNewWizard;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.forms.IManagedForm;

/**
 * The Class ExtnlResBindSection.
 */
public class ExtnlResBindSection extends AbstractSection {

  /** The Constant boundHeader. */
  private final static String boundHeader = "Bound to: ";

  /** The section client. */
  private Composite sectionClient;

  /** The tree. */
  private Tree tree;

  /** The add button. */
  private Button addButton;

  /** The edit button. */
  private Button editButton;

  /** The remove button. */
  private Button removeButton;

  /** The bind button. */
  private Button bindButton;

  /** The export button. */
  private Button exportButton;

  /** The resource dependency section. */
  private ResourceDependencySection resourceDependencySection;

  /** The res bind import section. */
  private ImportResBindSection resBindImportSection;

  /**
   * Instantiates a new extnl res bind section.
   *
   * @param aEditor
   *          the a editor
   * @param parent
   *          the parent
   */
  public ExtnlResBindSection(MultiPageEditor aEditor, Composite parent) {
    super(aEditor, parent, "Resources Needs, Definitions and Bindings",
            "Specify External Resources; Bind them to dependencies on the right panel by selecting the corresponding dependency and clicking Bind.");
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.uima.taeconfigurator.editors.ui.AbstractSection#initialize(org.eclipse.ui.forms.
   * IManagedForm)
   */
  @Override
  public void initialize(IManagedForm form) {
    super.initialize(form);
    // set up Composite to hold widgets in the section
    sectionClient = new2ColumnComposite(getSection());

    tree = newTree(sectionClient);
    // Buttons
    Composite buttonContainer = newButtonContainer(sectionClient);

    addButton = newPushButton(buttonContainer, S_ADD,
            "Click to add a new External Resource definition");
    editButton = newPushButton(buttonContainer, S_EDIT,
            "Click to edit an External Resource definition");
    removeButton = newPushButton(buttonContainer, "Remove",
            "Click to remove selected binding or External Resource");
    bindButton = newPushButton(buttonContainer, "Bind",
            "Click to bind selected dependency with selected Resource");
    exportButton = newPushButton(buttonContainer, S_EXPORT, S_EXPORT_TIP);

    buttonContainer.pack();
    getSection().getParent().getParent().pack();
    getSection().getParent().getParent().layout();
    initialFormWidth = getSection().getSize().x;
    ((GridData) tree.getLayoutData()).widthHint = initialFormWidth - buttonContainer.getSize().x;

    enableBorders(sectionClient);
    toolkit.paintBordersFor(sectionClient);

    tree.addListener(SWT.MouseDoubleClick, this);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.ui.forms.AbstractFormPart#refresh()
   */
  @Override
  public void refresh() {
    if (null == resBindImportSection)
      resBindImportSection = editor.getResourcesPage().getResBindImportSection();
    super.refresh();
    resourceDependencySection = editor.getResourcesPage().getResourceDependencySection();
    ExternalResourceDescription[] xrds = getExternalResources();
    ExternalResourceBinding[] bindings = getExternalResourceBindings();
    tree.removeAll();
    if (null != xrds) {
      for (int i = 0; i < xrds.length; i++) {
        addExternalResourceDescriptionToGUI(xrds[i], bindings);
      }
    }
    enable();
  }

  /**
   * Adds the external resource description to GUI.
   *
   * @param xrd
   *          the xrd
   * @param bindings
   *          the bindings
   */
  private void addExternalResourceDescriptionToGUI(ExternalResourceDescription xrd,
          ExternalResourceBinding[] bindings) {
    TreeItem item = new TreeItem(tree, SWT.NONE);
    fillXrdItem(item, xrd);
    fillBindings(item, xrd, bindings);
    item.setExpanded(true);
  }

  /**
   * Fill xrd item.
   *
   * @param item
   *          the item
   * @param xrd
   *          the xrd
   */
  private void fillXrdItem(TreeItem item, ExternalResourceDescription xrd) {
    StringBuffer text = new StringBuffer();
    text.append(xrd.getName());
    ResourceSpecifier rs = xrd.getResourceSpecifier();
    if (rs instanceof FileLanguageResourceSpecifier) {
      FileLanguageResourceSpecifier flrs = (FileLanguageResourceSpecifier) rs;
      text.append("  URL_Prefix: ").append(flrs.getFileUrlPrefix()).append("  URL_Suffix: ")
              .append(flrs.getFileUrlSuffix());
    } else if (rs instanceof FileResourceSpecifier) {
      FileResourceSpecifier frs = (FileResourceSpecifier) rs;
      text.append("  URL: ").append(frs.getFileUrl());
    } else {
      text.append("  Custom Resource Specifier");
    }
    String implName = xrd.getImplementationName();
    if (null != implName && !implName.equals("")) {
      text.append("  Implementation: ").append(implName);
    }
    item.setText(text.toString());
    item.setData(xrd);
  }

  /**
   * Fill bindings.
   *
   * @param parent
   *          the parent
   * @param xrd
   *          the xrd
   * @param bindings
   *          the bindings
   */
  private void fillBindings(TreeItem parent, ExternalResourceDescription xrd,
          ExternalResourceBinding[] bindings) {
    if (null != bindings) {
      for (int i = 0; i < bindings.length; i++) {
        if (bindings[i].getResourceName().equals(xrd.getName())) {
          addBindingToGUI(parent, bindings[i].getKey(), bindings[i]);
        }
      }
    }
  }

  /**
   * Adds the binding to GUI.
   *
   * @param parent
   *          the parent
   * @param key
   *          the key
   * @param xrb
   *          the xrb
   */
  private void addBindingToGUI(TreeItem parent, String key, ExternalResourceBinding xrb) {
    TreeItem item = new TreeItem(parent, SWT.NONE);
    item.setText(boundHeader + key);
    item.setData(xrb);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
   */
  @Override
  public void handleEvent(Event event) {
    if (event.widget == addButton)
      handleAdd();
    else if (event.widget == editButton || event.type == SWT.MouseDoubleClick)
      handleEdit();
    else if (event.widget == removeButton
            || (event.widget == tree && event.type == SWT.KeyUp && event.character == SWT.DEL))
      handleRemove();
    else if (event.widget == bindButton)
      handleBind();
    else if (event.widget == exportButton) {
      try {
        resBindImportSection.exportImportablePart("<resourceManagerConfiguration>",
                ResourceManagerConfigurationNewWizard.RESOURCEMANGERCONFIGURATION_TEMPLATE);
      } finally {
        refresh(); // update in case of throw, even
      }
    }

    enable();
  }

  /**
   * Gets the XR description from tree item.
   *
   * @param item
   *          the item
   * @return the XR description from tree item
   */
  public ExternalResourceDescription getXRDescriptionFromTreeItem(TreeItem item) {
    return (ExternalResourceDescription) item.getData();
  }

  /**
   * Bindings can't be edited. They can be removed or new ones bound. External resources can be
   * edited. Edit button is disabled unles an editable thing is selected. But user could double
   * click an illegal entry
   *
   */
  private void handleEdit() {
    TreeItem item = tree.getSelection()[0];
    if (isBoundSpec(item))
      return;
    ExternalResourceDescription xrd = getXRDescriptionFromTreeItem(item);
    ResourceSpecifier rs = xrd.getResourceSpecifier();
    if (!((rs instanceof FileResourceSpecifier) || (rs instanceof FileLanguageResourceSpecifier))) {
      Utility.popMessage("Can''t edit custom resource",
              "This resource is a '" + rs.getClass().getName()
                      + "', and any edits have to be done directly in the XML in the Source view.",
              MessageDialog.INFORMATION);
      return;
    }

    AddExternalResourceDialog dialog = new AddExternalResourceDialog(this, xrd);

    if (dialog.open() == Window.CANCEL)
      return;
    alterExistingXRD(dialog, xrd, item);
  }

  /**
   * Add new external resource, with no bindings.
   */
  private void handleAdd() {
    AddExternalResourceDialog dialog = new AddExternalResourceDialog(this);

    if (dialog.open() == Window.CANCEL)
      return;
    ExternalResourceDescription xrd = new ExternalResourceDescription_impl();
    TreeItem item = new TreeItem(tree, SWT.NONE);
    alterExistingXRD(dialog, xrd, item);
    getResourceManagerConfiguration().addExternalResource(xrd);
  }

  /**
   * Alter existing XRD.
   *
   * @param dialog
   *          the dialog
   * @param xrd
   *          the xrd
   * @param item
   *          the item
   */
  private void alterExistingXRD(AddExternalResourceDialog dialog, ExternalResourceDescription xrd,
          TreeItem item) {
    valueChanged = false;
    xrd.setName(setValueChanged(dialog.xrName, xrd.getName()));
    xrd.setDescription(setValueChanged(dialog.xrDescription, xrd.getDescription()));
    xrd.setImplementationName(
            setValueChanged(dialog.xrImplementation, xrd.getImplementationName()));

    ResourceSpecifier rs = xrd.getResourceSpecifier();
    if (null == dialog.xrUrlSuffix || "".equals(dialog.xrUrlSuffix)) {
      FileResourceSpecifier frs;
      if (null != rs && rs instanceof FileResourceSpecifier) {
        frs = (FileResourceSpecifier) rs;
      } else {
        frs = new FileResourceSpecifier_impl();
      }
      frs.setFileUrl(setValueChanged(dialog.xrUrl, frs.getFileUrl()));
      xrd.setResourceSpecifier(frs);
    } else {
      FileLanguageResourceSpecifier flrs;
      if (null != rs && rs instanceof FileLanguageResourceSpecifier) {
        flrs = (FileLanguageResourceSpecifier) rs;
      } else {
        flrs = new FileLanguageResourceSpecifier_impl();
      }
      flrs.setFileUrlPrefix(setValueChanged(dialog.xrUrl, flrs.getFileUrlPrefix()));
      flrs.setFileUrlSuffix(setValueChanged(dialog.xrUrlSuffix, flrs.getFileUrlSuffix()));
      xrd.setResourceSpecifier(flrs);
    }
    fillXrdItem(item, xrd);
    if (valueChanged)
      setFileDirty();
  }

  /**
   * Bind button - enabled only when one dependency is selected, and one External Resource, not
   * already bound to this key, is selected.
   */
  private void handleBind() {
    TreeItem xrItem = tree.getSelection()[0];
    if (null != xrItem.getParentItem())
      xrItem = xrItem.getParentItem();
    ExternalResourceDescription xrd = getXRDescriptionFromTreeItem(xrItem);

    TableItem keyItem = resourceDependencySection.getTable().getSelection()[0];

    ExternalResourceBinding xrb = new ExternalResourceBinding_impl();
    String key = keyItem.getText(ResourceDependencySection.KEY_COL);
    xrb.setKey(key);
    xrb.setResourceName(xrd.getName());
    getResourceManagerConfiguration().addExternalResourceBinding(xrb);
    addBindingToGUI(xrItem, key, xrb);
    xrItem.setExpanded(true);
    keyItem.setText(0, "Bound");
    keyItem.getParent().getColumn(0).pack();
    setFileDirty();
  }

  /**
   * remove either a binding or an external resource. Removing the resource removes all bindings
   * associated with it
   *
   */
  private void handleRemove() {
    int selectionCount = tree.getSelectionCount();
    if (1 != selectionCount)
      return;
    TreeItem item = tree.getSelection()[0];
    if (null == item.getParentItem()) { // case of removing a resource
      if (Window.CANCEL == Utility.popOkCancel("Removing Resource",
              "Removing an External Resource and all its bindings. Resource name:" + item.getText(),
              MessageDialog.WARNING))
        return;
      removeAllBindings(item);
      removeResource(item);
    } else { // case of removing a binding
      removeBinding(item);
    }
  }

  /**
   * Gets the XR binding from tree item.
   *
   * @param item
   *          the item
   * @return the XR binding from tree item
   */
  public ExternalResourceBinding getXRBindingFromTreeItem(TreeItem item) {
    return (ExternalResourceBinding) item.getData();
  }

  /**
   * Removes the binding.
   *
   * @param item
   *          the item
   */
  private void removeBinding(TreeItem item) {
    ExternalResourceBinding xrb = getXRBindingFromTreeItem(item);
    getResourceManagerConfiguration().removeExternalResourceBinding(xrb);
    removeBoundFlagInDependencySection(xrb);
    item.dispose();
    setFileDirty();
  }

  /**
   * Removes the bound flag in dependency section.
   *
   * @param xrb
   *          the xrb
   */
  private void removeBoundFlagInDependencySection(ExternalResourceBinding xrb) {
    String key = xrb.getKey();
    TableItem[] items = resourceDependencySection.getTable().getItems();
    for (int i = 0; i < items.length; i++) {
      if (key.equals(items[i].getText(ResourceDependencySection.KEY_COL)))
        items[i].setText(0, ""); // reset bound
    }
  }

  /**
   * Removes the all bindings.
   *
   * @param item
   *          the item
   */
  private void removeAllBindings(TreeItem item) {
    TreeItem[] items = item.getItems();
    for (int i = items.length - 1; i >= 0; i--) {
      removeBinding(items[i]);
    }
  }

  /**
   * Removes the resource.
   *
   * @param item
   *          the item
   */
  private void removeResource(TreeItem item) {
    ExternalResourceDescription xrd = getXRDescriptionFromTreeItem(item);
    getResourceManagerConfiguration().removeExternalResource(xrd);
    item.dispose();
    setFileDirty();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.uima.taeconfigurator.editors.ui.AbstractSection#enable()
   */
  @Override
  public void enable() {
    // bind enabled when one item in tree and one in table is selected
    bindButton.setEnabled(tree.getSelectionCount() == 1
            && resourceDependencySection.getTable().getSelectionCount() == 1
            && "".equals(resourceDependencySection.getTable().getSelection()[0].getText(0))); // not
                                                                                // bound

    removeButton.setEnabled(tree.getSelectionCount() > 0);
    editButton.setEnabled(tree.getSelectionCount() == 1 && !isBoundSpec(tree.getSelection()[0]));
    exportButton.setEnabled(tree.getItemCount() > 0);
  }

  /**
   * Checks if is bound spec.
   *
   * @param item
   *          the item
   * @return true, if is bound spec
   */
  private boolean isBoundSpec(TreeItem item) {
    return item.getText().startsWith(boundHeader);
  }

  /**
   * Resource name already defined.
   *
   * @param name
   *          the name
   * @return true, if successful
   */
  public boolean resourceNameAlreadyDefined(String name) {
    ExternalResourceDescription[] xrds = getExternalResources();
    if (xrds != null) {
      for (int i = 0; i < xrds.length; i++) {
        if (xrds[i].getName().equals(name)) {
          Utility.popMessage("Name Already Defined",
                  "The External Resource Name specified is already defined", MessageDialog.ERROR);
          return true;
        }
      }
    }
    return false;
  }

}


text:
<?php
namespace Icecave\Exie\Output;

class CallbackOutput implements OutputInterface
{
    /**
     * @param callable $callback
     */
    public function __construct($callback)
    {
        $this->callback = $callback;
    }

    /**
     * @param string $buffer
     */
    public function write($buffer)
    {
        call_user_func($this->callback, $buffer);
    }

    public function close()
    {
        call_user_func($this->callback, null);
    }

    private $callback;
}


text:
test -f "$(dirname $0)/paths.sh" && source "$(dirname $0)/paths.sh"

# Set this in your environment variable, for example:
#POESIE_BIN=/Users/me/Documents/Dev/Poesie/bin/poesie
if [ ! -x "$POESIE_BIN" ]; then
  echo You must define the POESIE_BIN variable to the path to the 'poesie' tool
  exit 1
fi

### Project-specific variables ###
PROJ_DIR=$(dirname $0)/../ProjectName
LOCALIZABLE="$PROJ_DIR/Resources/Base.lproj/Localizable.strings"
# Fill the following with values from https://poeditor.com/account/api
API_TOKEN=""
PROJECT_ID=""

### Run the Script ###
"$POESIE_BIN" --token "$API_TOKEN" --project "$PROJECT_ID" --lang fr --ios "$LOCALIZABLE"


text:
<?php
namespace HtSettingsModule\Mapper\FileSystem;

use HtSettingsModule\Entity\ParameterInterface;
use HtSettingsModule\Exception;
use League\Flysystem\FilesystemInterface;
use HtSettingsModule\Mapper\SettingsMapperInterface;

class FileSystemMapper implements SettingsMapperInterface
{
    /**
     * @var ParameterInterface
     */
    protected $entityPrototype;

    /**
     * @var FilesystemInterface
     */
    protected $fileSystem;

    /**
     * @var Adapter\AdapterInterface
     */
    protected $adapter;

    /**
     * Constructor
     *
     * @param FilesystemInterface $fileSystem
     * @param ParameterInterface  $entityPrototype
     */
    public function __construct(FilesystemInterface $fileSystem, ParameterInterface $entityPrototype, Adapter\AdapterInterface $adapter)
    {
        $this->fileSystem = $fileSystem;
        $this->entityPrototype = $entityPrototype;
        $this->adapter = $adapter;
    }

    /**
     * {@inheritDoc}
     */
    public function findByNamespace($namespace)
    {
        $data = $this->read($namespace);
        $parameters = [];
        foreach ($data as $name => $value) {
            $parameter = clone $this->entityPrototype;
            $parameter->setName($name);
            $parameter->setValue($value);
            $parameter->setNamespace($namespace);
            $parameters[] = $parameter;
        }

        return $parameters;
    }

    /**
     * {@inheritDoc}
     */
    public function insertParameter(ParameterInterface $parameter)
    {
        $this->updateParameter($parameter);
    }

    /**
     * {@inheritDoc}
     */
    public function updateParameter(ParameterInterface $parameter)
    {
        $data = $this->read($parameter->getNamespace());
        $data[$parameter->getName()] = $parameter->getValue();
        $this->write($parameter->getNamespace(), $data);
    }

    /**
     * {@inheritDoc}
     */
    public function deleteParameter(ParameterInterface $parameter)
    {
        $data = $this->read($parameter->getNamespace());
        unset($data[$parameter->getName()]);

        $this->write($parameter->getNamespace(), $data);
    }

    /**
     * {@inheritDoc}
     */
    public function findParameter($parameter, $name = null)
    {
        if ($parameter instanceof ParameterInterface) {
            $namespace = $parameter->getNamespace();
            $name = $parameter->getName();
            $data = $this->read($namespace);
            $parameter->setValue($data[$name]);

            return $parameter;
        } elseif (!is_string($parameter)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be string or an instance of HtSettingsModule\Entity\ParameterInterface, %s provided instead',
                    __METHOD__,
                    is_object($parameter) ? get_class($parameter) : gettype($parameter)
                )
            );
        }

        $namespace = $parameter;
        $data = $this->read($namespace);
        $parameter = clone $this->entityPrototype;
        $parameter->setName($name);
        $parameter->setValue($data[$name]);
        $parameter->setNamespace($namespace);

        return $parameter;
    }

    /**
     * Reads settings content of a namespace
     *
     * @param  string $namespace
     * @return array
     */
    protected function read($namespace)
    {
        $file = $this->adapter->getFileName($namespace);
        if (!$this->fileSystem->has($file)) {
            return [];
        }

        return $this->adapter->onRead($this->fileSystem->read($file));
    }

    /**
     * Write settings content of a namespace
     *
     * @param  string $namespace
     * @param  array  $data
     * @return void
     */
    protected function write($namespace, array $data)
    {
        $file = $this->adapter->getFileName($namespace);
        $contents = $this->adapter->prepareForWriting($data);
        if (!$this->fileSystem->has($file)) {
            $this->fileSystem->write($file, $contents);
        }

        $this->fileSystem->update($file, $contents);
    }
}


text:
package com.coolweather.hong.coolweather.util;

/**
 * Created by 11603 on 2016/11/5.
 */

public interface HttpCallBackListener {
    void onFinish(String response);
    void onError(Exception e);
}


text:
function AbstractFilter(config) {

};

AbstractFilter.prototype.validate = function(value) {
    return this._validate(value);
};

AbstractFilter.prototype.sanitize = function(value) {
    return this._sanitize(value);
};

module.exports = AbstractFilter;