text:
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
                        print_function, unicode_literals)

import os
import time

from pants.backend.python.python_chroot import PythonChroot
from pants.backend.python.targets.python_binary import PythonBinary
from pants.backend.python.tasks.python_task import PythonTask
from pants.base.exceptions import TaskError

class PythonBinaryCreate(PythonTask):
  @staticmethod
  def is_binary(target):
    return isinstance(target, PythonBinary)

  def __init__(self, *args, **kwargs):
    super(PythonBinaryCreate, self).__init__(*args, **kwargs)
    self._distdir = self.context.config.getdefault('pants_distdir')

  def execute(self):
    binaries = self.context.targets(self.is_binary)

    # Check for duplicate binary names, since we write the pexes to <dist>/<name>.pex.
    names = {}
    for binary in binaries:
      name = binary.name
      if name in names:
        raise TaskError('Cannot build two binaries with the same name in a single invocation. '
                        '%s and %s both have the name %s.' % (binary, names[name], name))
      names[name] = binary

    for binary in binaries:
      self.create_binary(binary)

  def create_binary(self, binary):
    interpreter = self.select_interpreter_for_targets(binary.closure())

    run_info = self.context.run_tracker.run_info
    build_properties = {}
    build_properties.update(run_info.add_basic_info(run_id=None, timestamp=time.time()))
    build_properties.update(run_info.add_scm_info())

    pexinfo = binary.pexinfo.copy()
    pexinfo.build_properties = build_properties

    with self.temporary_pex_builder(pex_info=pexinfo, interpreter=interpreter) as builder:
      chroot = PythonChroot(
        targets=[binary],
        builder=builder,
        platforms=binary.platforms,
        interpreter=interpreter,
        conn_timeout=self.conn_timeout)

      pex_path = os.path.join(self._distdir, '%s.pex' % binary.name)
      chroot.dump()
      builder.build(pex_path)


text:
layout: post
title:  "Ruby coding standards followed in milacron project "
date:   2014-06-02 02:49:29
categories: style-guide
permalink: ruby-standards
---

## Ruby Coding Style

This is our internal style guide for Ruby. In milacron project we are using Ruby for automating migration from legacy website to milacron codebase .

## Table of Contents

  * [Coding Style](#coding-style)
  * [Documentation](#documentation)
  * [Syntax](#syntax)
  * [Naming](#naming)
  * [Classes](#classes)

## Coding Style
 * Use soft-tabs with a two space indent.
 * Keep lines fewer than 80 characters.
 * Never leave trailing whitespace.
 * End each file with a blank newline.
 * Please use underscore for function names and complete words for class names , never ever bring in camelcase .
 * Use spaces around operators, after commas, colons and semicolons, around { and before }.

 ````Ruby
 sum = 1 + 2
  a, b = 1, 2
  1 > 2 ? true : false; puts "Hi"
  [1, 2, 3].each { |e| puts e }

 ```
 * No spaces after (, [ or before ], ).

 ````Ruby
 some(arg).other
 [1, 2, 3].length

 ```
 * No spaces after !.

 ```Ruby
 !array.include?(element)

 ```

* Indent `when` as deep as `case`. I know that many would disagree
  with this one, but it's the style established in both "The Ruby
  Programming Language" and "Programming Ruby".

  ```Ruby
  # bad
  case
    when song.name == 'Misty'
      puts 'Not again!'
    when song.duration > 120
      puts 'Too long!'
    when Time.now.hour > 21
      puts "It's too late"
    else
      song.play
  end

  # good
  case
  when song.name == 'Misty'
    puts 'Not again!'
  when song.duration > 120
    puts 'Too long!'
  when Time.now.hour > 21
    puts "It's too late"
  else
    song.play
  end
  ```
 * Use empty lines between defs and to break up a method into logical paragraphs.

  ````Ruby
  def some_method
    data = initialize(options)

    data.manipulate!

    data.result
  end

  def some_method
    result
  end
  ```

## Documentation
 * Please use ([Rdoc](http://en.wikibooks.org/wiki/Ruby_Programming/RubyDoc))  for best of your ability

  ````Ruby
  # content class which defines various attributes and behaviours which are used in
  # migration
  #
  # Author::    Aravind Udayashankara  (mailto:aravind.udayashankara@gmail.com)
  # Copyright:: Copyright (c) 2012 Crossroads
  # License::   MIT
  #
  # Instantiating this class leads to migration
  #
  class Content

    #
    # This method clears old files by deleting the destination directory to recreate it
    #
    # * checks if the log files exists in the location and deletes only on exist
    # * validates the destination path
    # * if exists removes the directory
    # * logs the error message
    #
    # content.clean_old_files
    #
    def clean_old_files
     # your logic
    end

 ```
## Syntax

 * Use `def` with parentheses when there are arguments. Omit the parentheses
   when the method doesn't accept any arguments

    ````Ruby
    def some_method
      # body omitted
    end

    def some_method_with_arguments(arg1, arg2)
      # body omitted
    end

    ```
 * Never use `for`, unless you know exactly why. Most of the time iterators
   should be used instead. `for` is implemented in terms of `each` (so you're
   adding a level of indirection), but with a twist - `for` doesn't introduce a
   new scope (unlike `each`) and variables defined in its block will be visible
   outside it

    ````Ruby
    arr = [1, 2, 3]

    # bad
    for elem in arr do
      puts elem
    end

    # good
    arr.each { |elem| puts elem }

     ```

 * Never use `then` for multi-line `if/unless`

    ````Ruby
    # bad
    if some_condition then
      # body omitted
    end

    # good
    if some_condition
        # body omitted
    end
     ```

 * Avoid the ternary operator except in cases where all expressions are
   extremely trivial. However, do use the ternary operator over
   `if/then/else/end` constructs for single line conditionals

    ````Ruby
    # bad
    result = if some_condition then something else something_else end

    # good
    result = some_condition ? something : something_else
     ```

 * Use one expression per branch in a ternary operator. This also means that
   ternary operators must not be nested. Prefer `if/else` constructs in these
   cases

    ````Ruby
    # bad
    some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else

    # good
    if some_condition
      nested_condition ? nested_something : nested_something_else
    else
      something_else
    end
     ```

 * The `and` and `or` keywords are banned. It's just not worth it. Always use
   `&&` and `||` instead

 * Avoid multi-line ternary operator, use `if/unless` instead

 * Favor modifier `if/unless` usage when you have a single-line body

    ````Ruby
    # bad
    if some_condition
      do_something
    end

    # good
    do_something if some_condition
     ```

 * Never use `unless` with `else`. Rewrite these with the positive case first

    ````Ruby
    # bad
    unless success?
      puts 'failure'
    else
      puts 'success'
    end

    # good
    if success?
      puts 'success'
    else
      puts 'failure'
    end
     ```

 * Don't use parentheses around the condition of an `if/unless/while`

    ````Ruby
    # bad
    if (x > 10)
      # body omitted
    end

    # good
    if x > 10
      # body omitted
    end
     ```

 * Prefer `{...}` over `do...end` for single-line blocks. Avoid using `{...}`
   for multi-line blocks (multiline chaining is always ugly). Always use
   `do...end` for "control flow" and "method definitions" (e.g. in Rakefiles
   and certain DSLs).  Avoid `do...end` when chaining

    ````Ruby
    names = ["Bozhidar", "Steve", "Sarah"]

    # good
    names.each { |name| puts name }

    # bad
    names.each do |name|
      puts name
    end

    # good
    names.select { |name| name.start_with?("S") }.map { |name| name.upcase }

    # bad
    names.select do |name|
      name.start_with?("S")
    end.map { |name| name.upcase }
    ```

   Some will argue that multiline chaining would look OK with the use of `{...}`,
   but they should ask themselves - is this code really readable and can't the
   block's contents be extracted into nifty methods?

 * Avoid `return` where not required

    ````Ruby
    # bad
    def some_method(some_arr)
        return some_arr.size
    end

    # good
    def some_method(some_arr)
        some_arr.size
    end
     ```

 * Use spaces around the `=` operator when assigning default values to method
   parameters:

    ````Ruby
    # bad
    def some_method(arg1=:default, arg2=nil, arg3=[])
      # do something...
    end

    # good
    def some_method(arg1 = :default, arg2 = nil, arg3 = [])
      # do something...
    end
     ```

While several Ruby books suggest the first style, the second is much more
prominent in practice (and arguably a bit more readable).

 * Using the return value of `=` (an assignment) is ok assignment with
   parenthesis

    ````Ruby
    # bad
    if (v = array.grep(/foo/)) ...

    # good
    if v = array.grep(/foo/) ...

    # also good - has correct precedence.
    if (v = next_value) == "hello" ...
     ```

 * Use `||=` freely to initialize variables

    ````Ruby
    # set name to Bozhidar, only if it's nil or false
    name ||= 'Bozhidar'
     ```
 * Don't use `||=` to initialize boolean variables (consider what would happen
   if the current value happened to be false)

    ````Ruby
    # bad - would set enabled to true even if it was false
    enabled ||= true

    # good
    enabled = true if enabled.nil?
     ```
 * Avoid using Perl-style special variables (like `$0-9`, `$`, etc. ). They are
   quite cryptic and their use in anything but one-liner scripts is
   discouraged. Prefer long form versions such as `$PROGRAM_NAME`

 * Never put a space between a method name and the opening parenthesis

    ````Ruby
    # bad
    f (3 + 2) + 1

    # good
    f(3 + 2) + 1
    ```
 * If the first argument to a method begins with an open parenthesis, always
   use parentheses in the method invocation. For example, write `f((3 + 2) +
   1)`

 * Use `_` for unused block parameters

    ````Ruby
    # bad
    result = hash.map { |k, v| v + 1 }

    # good
    result = hash.map { |_, v| v + 1 }
    ```

## Naming

* Use snake\_case for methods and variables
* Use CamelCase for classes and modules (keep acronyms like HTTP, RFC, XML
   uppercase)
* Use SCREAMING\_SNAKE\_CASE for other constants
* The names of predicate methods (methods that return a boolean value) should
   end in a question mark. (i.e. `Array#empty?`)
* The names of potentially "dangerous" methods (i.e. methods that modify
   `self` or the arguments, `exit!`, etc.) should end with an exclamation mark
   Bang methods should only exist if a non-bang method exists  ([more on
   this](http://dablog.rubypal.com/2007/8/15/bang-methods-or-danger-will-rubyist))

## Classes

* Avoid the usage of class (`@@`) variables due to their "nasty" behavior in
   inheritance

    ```Ruby
    class Parent
      @@class_var = 'parent'

      def self.print_class_var
        puts @@class_var
      end
    end

    class Child < Parent
      @@class_var = 'child'
    end

    Parent.print_class_var # => will print "child"
    ```

As you can see all the classes in a class hierarchy actually share one class
variable. Class instance variables should usually be preferred over class
variables.

* Use `def self.method` to define singleton methods. This makes the methods
   more resistant to refactoring changes

    ```Ruby
    class TestClass
      # bad
      def TestClass.some_method
        # body omitted
      end

      # good
      def self.some_other_method
        # body omitted
      end

    ```

redpajama_set_name: RedPajamaGithub


text:
<?php

  $errors = array();

  function fieldname_as_text($fieldname){
    $fieldname = str_replace("_"," ",$fieldname);
    $fieldname = ucfirst($fieldname);
    return $fieldname;
  }

  function has_presence($value){
    return isset($value) && $value !== "";
  }
  function validate_presences($fields){
    global $errors;
    foreach($fields as $field){
      $value = trim($_POST[$field]);
      if(!has_presence($value)){
        $errors[$field] = fieldname_as_text($field)." can't be blank";
      }
    }
  }

  function has_max_length($value,$max){
    return strlen($value) <= $max;
  }

  function validate_max_lengths($fields){
    global $errors;
    foreach($fields as $field => $max){
      $value = trim($_POST[$field]);
      if(!has_max_length($value,$max)){
        $errors[$field] = fieldname_as_text($field)." is too long";
      }
    }
  }

  function has_inclusion($value,$set){
    return in_array($value,$set);
  }

?>


text:
package com.googlecode.blaisemath.graph.metrics;

import com.google.common.graph.Graph;
import com.google.common.graph.Graphs;
import com.googlecode.blaisemath.graph.GraphUtils;

import java.util.Set;

/**
 * Global metric describing the clustering coefficient of the graph; in the
 * directed case, measures "transitivity", i.e. when a-%gt;b,b-%gt;c implies
 * a-%gt;c
 *
 * @author Elisha Peterson
 */
public class ClusteringCoefficient extends AbstractGraphMetric<Double> {

    public ClusteringCoefficient() {
        super("Clustering coefficient", "Computes the clustering coefficient:"
                + " Out of all triples of nodes with at least two edges, how many have three edges?", true);
    }

    @Override
    public Double apply(Graph graph) {
        int[] tri = triples(graph);
        int triangles = tri[0], triples = tri[1];
        if (!graph.isDirected()) {
            triangles /= 3;
            triples -= 2 * triangles;
        }
        return triangles / (double) triples;
    }

    /**
     * Computes triple characteristics of a graph.
     *
     * @param <N> coordinate type of graph
     * @param graph the graph
     * @return int[] array where first entry is number of triangles and second
     *      is number of path triples (i.e., when three nodes are connected together)
     */
    static <N> int[] triples(Graph<N> graph) {
        int triangles = 0;
        int triples = 0;
        for (N node : graph.nodes()) {
            Set<N> g1 = graph.adjacentNodes(node);
            int dist1 = g1.size();
            int aDist1 = Graphs.inducedSubgraph(graph, g1).edges().size();
            Set<N> g2 = GraphUtils.neighborhood(graph, node, 2);
            int dist2 = g2.size() - 1 - g1.size();

            if (graph.isDirected()) {
                // in the directed case, potential triples are connected nodes at distance 1 and nodes at distance 2
                // ... each node at distance 2 contributes a triple, but no triangle
                triples += aDist1 + dist2;
                triangles += aDist1;
            } else {
                // in copyUndirected case, each pair of nodes @ distance 1 contributes to a triple
                // ... each edge in this neighborhood indicates a triangle
                // corrections for later: each triangle is counted 3 times
                triples += dist1 * (dist1 - 1) / 2;
                triangles += aDist1;
            }
        }
        return new int[]{triangles, triples};
    }
}


text:
package com.yidejia.app.mall.net.commments;

import java.io.IOException;

import org.apache.http.conn.ConnectTimeoutException;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.yidejia.app.mall.exception.TimeOutEx;
import com.yidejia.app.mall.jni.JNICallBack;
import com.yidejia.app.mall.net.HttpAddressParam;
import com.yidejia.app.mall.net.HttpGetConn;
import com.yidejia.app.mall.util.Md5;
/**
 * 获取用户待评论的商品列表
 * @author long bin
 *
 */
public class WaitingComment {
	private String TAG = WaitingComment.class.getName();

	private String result = "";
	public String getHttpResp(String userid)throws IOException, TimeOutEx{
//		HttpGetConn conn = new HttpGetConn(getHttpAddress(where, offset, limit, group, order, fields));
		HttpGetConn conn = new HttpGetConn(new JNICallBack().getHttp4GetNoEvaluate(userid), true);
		result = conn.getJsonResult();
		Log.i(TAG, result);
		return result;
	}

}


text:
var C = require('../constants.js');

var utils = require('../utils.js'),
    is = utils.is;

var segments = require('./segments.js'),
    MSeg = segments.MSeg,
    LSeg = segments.LSeg,
    CSeg = segments.CSeg,
    Crossings = segments.Crossings,
    engine = require('engine'),
    useP2D = !!engine.Path2D;

var Brush = require('./brush.js');

var Bounds = require('./bounds.js');

// Paths
// -----------------------------------------------------------------------------

// M<X> <Y> - move to
// L<X> <Y> - line to
// C<X1> <Y1> <X2> <Y2> <X3> <Y3> - curve to
// Z - close path
// lowercase marker means relative coord
// Example: "M0 10 L20 20 C10 20 15 30 10 9 Z"

// all commands:
// V = vertical lineto
// C = curveto
// S = smooth curveto
// Q = quadratic Bézier curve
// T = smooth quadratic Bézier curveto
// A = elliptical Arc
// Z = closepath

/**
 * @class anm.Path
 *
 * A Class that helps in creating SVG-compatible paths easily.
 *
 * Examples:
 *
 * * `var path = new Path('M0.0 10.0 L20.0 20.0 C10.0 20.0 15.0 30.0 10.0 9.0 Z');`
 * * `var path = new Path().add(new MSeg([0, 0])).add(new LSeg([20, 20])).add(new CSeg([10, 20, 15, 30, 10, 9]));`
 * * `var path = new Path().move(0, 0).line(20, 20).curve(10, 20, 15, 30, 10, 9);`
 * * `var path = new Path().move(0, 0).line(20, 20).curve(10, 20, 15, 30, 10, 9).close();`
 *
 * See: {@link anm.Element#path Element.path}, {@link anm.Element#translate_path Element.translate_path}
 *
 * @constructor
 *
 * @param {String} [value] String representation of SVG path
 *
 * @return {anm.Path}
 */
function Path(val) {
    this.segs = [];
    this.closed = false;

    if (is.str(val)) {
        this.parse(val);
        this.updatePath2D(val);
    } else if (is.arr(val)) {
        this.segs = val;
    }
    this.cached_hits = {};
}

/**
 * @method visit
 * @chainable
 *
 * // FIXME: rename to `.each`
 *
 * Visits every chunk of path in array-form and calls visitor function, so
 * visitor function gets chunk marker and positions sequentially
 * data argument will be also passed to visitor if specified
 *
 * @param {Function} visitor
 * @param {anm.MSeg|anm.LSeg|anm.CSeg} visitor.segment
 */
Path.prototype.visit = function(visitor, data) {
    var segments = this.segs;
    for (var si = 0, sl = segments.length; si < sl; si++) {
        visitor(segments[si], data);
    }
    return this;
};
/**
 * @method length
 *
 * Get path length, in points.
 *
 * @return {Number} path length
 */
Path.prototype.length = function() {
    if (is.defined(this.cached_len)) return this.cached_len;
    var sum = 0;
    var p = this.start();
    this.visit(function(segment) {
        sum += segment.length(p);
        p = segment.last();
    });
    this.cached_len = sum;
    return sum;
};
/**
 * @method add
 * @chainable
 *
 * Add a segment to this path
 *
 * @param {anm.MSeg|anm.LSeg|anm.CSeg} segment segment to add
 *
 * @return {anm.Path} itself
 */
Path.prototype.add = function(seg) {
    this.segs.push(seg);
    this._p2dCurrent = false;
    return this;
};
/**
 * @method move
 * @chainable
 *
 * Shortcut to adding Move Segment
 *
 * @param {Number} x X coordinate of move-to operation
 * @param {Number} y Y coordinate of move-to operation
 *
 * @return {anm.Path} itself
 */
Path.prototype.move = function(x, y) {
    return this.add(new MSeg([x, y]));
};
/**
 * @method line
 * @chainable
 *
 * Shortcut to adding Line Segment
 *
 * @param {Number} x X coordinate of line-to operation
 * @param {Number} y Y coordinate of line-to operation
 *
 * @return {anm.Path} itself
 */
Path.prototype.line = function(x, y) {
    return this.add(new LSeg([x, y]));
};
/**
 * @method curve
 * @chainable
 *
 * Shortcut to adding Curve Segment
 *
 * @param {Number} x1 X coordinate of first point of curve-to operation
 * @param {Number} y1 Y coordinate of first point of curve-to operation
 * @param {Number} x2 X coordinate of second point of curve-to operation
 * @param {Number} y2 Y coordinate of second point of curve-to operation
 * @param {Number} x3 X coordinate of third point of curve-to operation
 * @param {Number} y3 Y coordinate of third point of curve-to operation
 *
 * @return {anm.Path} itself
 */
Path.prototype.curve = function(x1, y1, x2, y2, x3, y3) {
    return this.add(new CSeg([x1, y1, x2, y2, x3, y3]));
};
/**
 * @method close
 * @chainable
 *
 * Close the path
 *
 * @return {anm.Path} itself
 */
Path.prototype.close = function() {
    this.closed = true;
    return this;
};
/**
 * @method apply
 *
 * Apply this path to a given 2D context with given fill / stroke / shadow
 *
 * Example: `path.apply(ctx, Brush.fill('#ff0000'), Brush.stroke('#00ff00', 2))`
 *
 * @param {Context2D} ctx where to apply
 * @param {anm.Brush} fill fill to use
 * @param {anm.Brush} stroke stroke to use
 * @param {anm.Brush} shadow shadow to use
 *
 * @return {anm.Path} itself
 */
Path.prototype.apply = function(ctx, fill, stroke, shadow) {
    if (useP2D) {
        this.updatePath2D();
        if (shadow) {
            shadow.apply(ctx);
        }
        if (fill) {
            fill.apply(ctx);
            ctx.fill(this.path2d);
        }
        if (shadow) {
            Brush.clearShadow(ctx);
        }
        if (stroke) {
            stroke.apply(ctx);
            ctx.stroke(this.path2d);
        }
        return this;
    }
    ctx.beginPath();
    // unrolled for speed
    var segments = this.segs;
    for (var si = 0, sl = segments.length; si < sl; si++) {
        segments[si].draw(ctx);
    }

    if (this.closed) ctx.closePath();

    if (shadow) { shadow.apply(ctx); }
    if (fill) { fill.apply(ctx); ctx.fill(); }
    if (shadow) { Brush.clearShadow(ctx); }
    if (stroke) { stroke.apply(ctx); ctx.stroke(); }

    return this;
};
/**
 * @method parse
 * @chainable
 * @deprecated
 *
 * Same as `new Path(str)`, but updates current instance instead of creating new one.
 *
 * @param {String} source string representation of SVG path
 * @return {anm.Path} itself
 */
Path.prototype.parse = function(str) {
    if (str) Path.parse(str, this);
    return this;
};
/**
 * @method hitAt
 *
 * Find a segment hit data in a path that corresponds
 * to specified distance (t) of the path.
 *
 * @param {Number} t distance in a range of [0..1]
 * @return {Object} hit data
 */
Path.prototype.hitAt = function(t) {
    if (is.defined(this.cached_hits[t])) return this.cached_hits[t];

    var plen = this.length(); // path length in pixels
    if (plen === 0) return null;
    if (t < 0 || t > 1.0) return null;

    var startp = this.start(); // start point of segment
    var cache_t = utils.roundTo(t, 3); // t for caching could be rounded

    if (t === 0) return (this.cached_hits[cache_t] = {
        'seg': this.segs[0], 'start': startp, 'slen': 0.0, 'segt': 0.0
    });

    /*var endp = this.end();
      if (t == 1) return func ? func(startp, endp) : endp;*/

    var nsegs = this.segs.length; // number of segments
    if (nsegs === 0) return null;

    var distance = t * plen;
    var p = startp;
    var length = 0; // checked length in pixels
    var seg, slen;
    for (var si = 0; si < nsegs; si++) {
        seg = this.segs[si];
        slen = seg.length(p); // segment length
        if (distance <= (length + slen)) {
            // inside current segment
            var segdist = distance - length;
            return (this.cached_hits[cache_t] = {
                'seg': seg, 'start': p, 'slen': slen, 'segt': (slen != 0) ? seg.findT(p, segdist) : 0
            });
        }
        length += slen;
        // end point of segment
        p = seg.last();
    }

    /*var lseg = this.segs[nsegs - 1];
      return {
        'seg': lseg, 'start': p, 'slen': lseg.length(p), 'segt': 1.0
      };*/
    return null;
};
/**
 * @method pointAt
 *
 * Find a point on a path at specified distance (t) of the path.
 *
 * @param {Number} t distance in a range of [0..1]
 * @return {[Number]} point in a form of [x, y]
 */
Path.prototype.pointAt = function(t) {
    var hit = this.hitAt(t);
    if (!hit) return this.start();
    return hit.seg.atT(hit.start, hit.segt);
};
/**
 * @method inside
 *
 * Checks if point is inside the path. _Does no test for bounds_, the point is
 * assumed to be already inside of the bounds, so check `path.bounds().inside(pt)`
 * before calling this method manually.
 *
 * @param {Object} pt point to check
 * @param {Number} pt.x
 * @param {Number} pt.y
 * @return {Boolean} is point inside
 */
Path.prototype.inside = function(pt) {
    var x = pt.x, y = pt.y;

    var mask = /*(windingRule == WIND_NON_ZERO ?*/ -1 /*: 1)*/;
    var nsegs = this.segs.length; // number of segments

    if (nsegs < 2) return false;

    var startp = this.start(); // start point of segment
    var p = startp;

    var crossings = 0;
    for (var si = 0; si < nsegs; si++) {
        var seg = this.segs[si];
        crossings += seg.crossings(p, x, y);
        p = seg.last();
    }

    if (startp !== p) {
        crossings += Crossings.line(x, y, p[0], p[1], startp[0], startp[1]);
    }

    return ((crossings & mask) !== 0);
};
/**
 * @method tangentAt
 *
 * Find a tangent on a path at specified distance (t) of the path.
 *
 * @param {Number} t distance in a range of [0..1]
 * @return {[Number]} point in a form of [x, y]
 */
Path.prototype.tangentAt = function(t) {
    var hit = this.hitAt(t);
    if (!hit) return 0;
    return hit.seg.tangentAt(hit.start, hit.segt);
};
/**
 * @method start
 *
 * Get first point of a path
 *
 * @return {[Number]|Null} point in a form of [x, y]
 */
Path.prototype.start = function() {
    if (this.segs.length < 1) return null;
    return [ this.segs[0].pts[0],   // first-x
             this.segs[0].pts[1] ]; // first-y
};
/**
 * @method end
 *
 * Get last point of a path
 *
 * @return {[Number]|Null} point in a form of [x, y]
 */
Path.prototype.end = function() {
    if (this.segs.length < 1) return null;
    return this.segs[this.segs.length - 1].last();
};
/**
 * @method bounds
 *
 * Get bounds of a path
 *
 * @return {anm.Bounds} path bounds
 */
Path.prototype.bounds = function() {
    // FIXME: it is not ok for curve path, possibly
    if (this.$bounds) return this.$bounds;
    if (this.segs.length <= 0) return Bounds.NONE;
    var minX = this.segs[0].pts[0], maxX = this.segs[0].pts[0],
        minY = this.segs[0].pts[1], maxY = this.segs[0].pts[1];
    this.visit(function(segment) {
        var pts = segment.pts,
            pnum = pts.length, pi;
        for (pi = 0; pi < pnum; pi+=2) {
            minX = Math.min(minX, pts[pi]);
            maxX = Math.max(maxX, pts[pi]);
        }
        for (pi = 1; pi < pnum; pi+=2) {
            minY = Math.min(minY, pts[pi]);
            maxY = Math.max(maxY, pts[pi]);
        }
    });
    return (this.$bounds = new Bounds(minX, minY,
                                      maxX - minX, maxY - minY));
};
/* TODO: rename to `modify`? */
Path.prototype.vpoints = function(func) {
    this.visit(function(segment) {
        var pts = segment.pts,
            pnum = pts.length;
        for (var pi = 0; pi < pnum; pi+=2) {
            var res = func(pts[pi], pts[pi+1]);
            if (res) {
                pts[pi] = res[0];
                pts[pi+1] = res[1];
            }
        }
    });
};
/**
 * @method shift
 * @chainable
 *
 * Shift this path to a point
 *
 * @param {[Number]} point in a form of [x, y]
 *
 * @return {anm.Path} itself
 */
Path.prototype.shift = function(pt) {
    this.vpoints(function(x, y) {
        return [ x + pt[0],
                 y + pt[1] ];
    });
    return this;
};
/**
 * @method zoom
 * @chainable
 *
 * Scale this path by given values
 *
 * @param {[Number]} values in a form of [sx, sy]
 *
 * @return {anm.Path} itself
 */
Path.prototype.zoom = function(vals) {
    this.vpoints(function(x, y) {
        return [ x * vals[0],
                 y * vals[1] ];
    });
    return this;
};
/**
 * @method normalize
 *
 * Moves path to be positioned at 0,0 and returns the difference
 *
 * @return {[Number]} [ center-x, center-y ]
 */
// moves path to be positioned at 0,0 and
// returns subtracted top-left point
// and a center point
Path.prototype.normalize = function() {
    var bounds = this.bounds();
    var w = bounds.width,
        h = bounds.height;
    var hw = Math.floor(w/2),
        hh = Math.floor(h/2);
    var min_x = bounds.x,
        min_y = bounds.y;
    this.vpoints(function(x, y) {
        return [ x - min_x - hw,
                 y - min_y - hh];
        });
    return [ hw, hh ];
};

Path.prototype.getPoints = function() {
    var points = [];
    this.visit(function(seg) {
        points = points.concat(seg.pts);
    });
    return points;
};

Path.prototype.toString = function() {
    return "[ Path '" + Path.toSVGString(this) + "' ]";
};
/**
 * @method clone
 *
 * Clone this path
 *
 * @return {anm.Path} clone
 */
Path.prototype.clone = function() {
    var _clone = new Path();
    this.visit(function(seg) {
        _clone.add(seg.clone());
    });
    clone.closed = this.closed;
    return _clone;
};
/**
 * @method invalidate
 *
 * Invalidate bounds of this path
 */
Path.prototype.invalidate = function() {
    this.cached_len = undefined;
    this.cached_hits = {};
    this.$bounds = null;
};

Path.prototype.reset = function() {
    this.segs = [];
    this.closed = false;
};

Path.prototype.dispose = function() { };

Path.prototype.updatePath2D = function(str) {
    if (!useP2D || this._p2dCurrent) return;
    str = str || Path.toSVGString(this);
    this.path2d = new engine.Path2D(str);
    this._p2dCurrent = true;
};

Path.toSVGString = function(path) {
    var buffer = [];
    path.visit(encodeVisitor, buffer);
    buffer.push('Z');
    return buffer.join(' ');
};

var encodeVisitor = function(segment, buffer) {
    buffer.push(segment.toString());
};

// converts path given in string form to array of segments
Path.parse = function(path, target) {
    target = target || new Path();
    target.segs = [];
    var segPaths = path.match(/[a-z][^a-z]*/ig);
    for (var i = 0; i < segPaths.length; i++) {
        var seg = Path.parseSegment(segPaths[i]);
        if (seg) {
            target.segs.push(seg);
        }
    }
    target.str = path;
    return target;
};

Path.parseSegment = function(segment) {
    segment = segment.toUpperCase();
    var values = segment.substring(1).trim()
        .replace(/,/g, ' ')
        .split(' ').map(function(n){
            return parseFloat(n);
        });
    switch(segment[0]) {
        case 'M':{
            return new MSeg(values);
        }
        case 'L':{
            return new LSeg(values);
        }
        case 'C':{
            return new CSeg(values);
        }
        default: {
            return null;
        }
    }
};

module.exports = Path;


text:
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>$fileinputname$ Widget</title>
    <script src="../scripts/VSS.SDK.js"></script>
    <script type="text/javascript">
                VSS.init({
                    explicitNotifyLoaded: true,
                    usePlatformStyles: true
                });

                VSS.require(["TFS/Dashboards/WidgetHelpers"], function (WidgetHelpers) {
                    WidgetHelpers.IncludeWidgetStyles();
                    VSS.register("$fileinputname$", function () {
                        return {
                            load: function (widgetSettings) {
                                /*
                                Enter your widget code here

                                */

                                return WidgetHelpers.WidgetStatusHelper.Success();
                            }
                        }
                    });
                    VSS.notifyLoadSucceeded();
                });
    </script>

</head>
<body>

</body>
</html>


text:
package com.cebedo.pmsys.bean;

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

import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

import com.cebedo.pmsys.base.IObjectExpense;
import com.cebedo.pmsys.domain.ProjectPayroll;
import com.cebedo.pmsys.enums.SortOrder;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;

public class StatisticsProject extends SummaryStatistics {

    public static final int DESCRIPTIVE_MAX = 0;
    public static final int DESCRIPTIVE_MIN = 1;
    public static final int DESCRIPTIVE_MEAN = 2;

    private static final long serialVersionUID = 1330741496424321113L;

    private List<IObjectExpense> payrolls;
    private List<IObjectExpense> deliveries;
    private List<IObjectExpense> equipment;
    private List<IObjectExpense> otherExpenses;

    public StatisticsProject() {
	;
    }

    public StatisticsProject(List<IObjectExpense> payrolls, List<IObjectExpense> deliveries,
	    List<IObjectExpense> equipmentExpenses, List<IObjectExpense> otherExpenses) {
	this.payrolls = payrolls;
	this.deliveries = deliveries;
	this.equipment = equipmentExpenses;
	this.otherExpenses = otherExpenses;
    }

    private void addValuesPayroll() {
	for (IObjectExpense payroll : this.payrolls) {
	    PayrollResultComputation result = ((ProjectPayroll) payroll).getPayrollComputationResult();
	    if (result != null) {
		addValue(result.getOverallTotalOfStaff());
	    }
	}
    }

    /**
     * Get the mean then clear the list.
     *
     * @param payrolls
     * @return
     */
    public double getMeanPayroll() {
	addValuesPayroll();
	double mean = getMean();
	clear();
	return mean;
    }

    public double getMeanDelivery() {
	addValuesDelivery();
	double mean = getMean();
	clear();
	return mean;
    }

    private void addValuesDelivery() {
	for (IObjectExpense obj : this.deliveries) {
	    addValue(obj.getCost());
	}
    }

    public double getMeanEquipment() {
	addValuesEquipment();
	double mean = getMean();
	clear();
	return mean;
    }

    private void addValuesEquipment() {
	for (IObjectExpense obj : this.equipment) {
	    addValue(obj.getCost());
	}
    }

    public double getMeanOtherExpenses() {
	addValuesOtherExpenses();
	double mean = getMean();
	clear();
	return mean;
    }

    private void addValuesOtherExpenses() {
	for (IObjectExpense obj : this.otherExpenses) {
	    addValue(obj.getCost());
	}
    }

    public double getMeanProject() {
	addValuesProject();
	double mean = getMean();
	clear();
	return mean;
    }

    private void addValuesProject() {
	addValuesPayroll();
	addValuesDelivery();
	addValuesEquipment();
	addValuesOtherExpenses();
    }

    public double getSumPayroll() {
	addValuesPayroll();
	double sum = getSum();
	clear();
	return sum;
    }

    public double getSumDelivery() {
	addValuesDelivery();
	double sum = getSum();
	clear();
	return sum;
    }

    public double getSumEquipment() {
	addValuesEquipment();
	double sum = getSum();
	clear();
	return sum;
    }

    public double getSumOtherExpenses() {
	addValuesOtherExpenses();
	double sum = getSum();
	clear();
	return sum;
    }

    /**
     * Get max payrolls.
     *
     * @return
     */
    // public List<ProjectPayroll> getMaxPayrolls() {
    public List<IObjectExpense> getMaxPayrolls() {

	// Get the greatest value.
	addValuesPayroll();
	double comparator = getMax();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingPayrolls(comparator);
	return returnList;
    }

    public ImmutableList<IObjectExpense> getAllSortedByCostPayrolls(SortOrder order) {
	return getLimitedSortedByCostPayrolls(null, order);
    }

    public ImmutableList<IObjectExpense> getAllSortedByCostDeliveries(SortOrder order) {
	return getLimitedSortedByCostDeliveries(null, order);
    }

    public ImmutableList<IObjectExpense> getAllSortedByCostEquipment(SortOrder order) {
	return getLimitedSortedByCostEquipment(null, order);
    }

    public ImmutableList<IObjectExpense> getAllSortedByCostOtherExpenses(SortOrder order) {
	return getLimitedSortedByCostOtherExpenses(null, order);
    }

    public ImmutableList<IObjectExpense> getLimitedSortedByCostOtherExpenses(Integer limit, SortOrder order) {
	return sortByCostInterface(this.otherExpenses, limit, order);
    }

    public ImmutableList<IObjectExpense> getLimitedSortedByCostEquipment(Integer limit, SortOrder order) {
	return sortByCostInterface(this.equipment, limit, order);
    }

    public ImmutableList<IObjectExpense> getLimitedSortedByCostDeliveries(Integer limit, SortOrder order) {
	return sortByCostInterface(this.deliveries, limit, order);
    }

    public ImmutableList<IObjectExpense> getLimitedSortedByCostPayrolls(Integer maxCount, SortOrder order) {
	return sortByCostInterface(this.payrolls, maxCount, order);
    }

    public ImmutableList<IObjectExpense> getAllSortedByCostProject(SortOrder order) {
	return sortByCostInterface(collectExpenses(), null, order);
    }

    public ImmutableList<IObjectExpense> getLimitedSortedByCostProject(Integer maxCount, SortOrder order) {
	return sortByCostInterface(collectExpenses(), maxCount, order);
    }

    private List<IObjectExpense> collectExpenses() {
	List<IObjectExpense> expenses = new ArrayList<IObjectExpense>();
	expenses.addAll(this.deliveries);
	expenses.addAll(this.equipment);
	expenses.addAll(this.otherExpenses);
	expenses.addAll(this.payrolls);
	return expenses;
    }

    /**
     * Sort and limit the given list.
     *
     * @param objList
     * @param maxCount
     * @param order
     * @return
     */
    private ImmutableList<IObjectExpense> sortByCostInterface(List<IObjectExpense> objList, Integer maxCount,
	    SortOrder order) {
	Collections.sort(objList, new OrderingIObjectExpense(order));
	if (maxCount != null) {
	    return FluentIterable.from(objList).limit(maxCount).toList();
	}
	return FluentIterable.from(objList).toList();
    }

    /**
     * Get min payrolls.
     *
     * @return
     */
    public List<IObjectExpense> getMinPayrolls() {

	// Get the greatest value.
	addValuesPayroll();
	double comparator = getMin();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingPayrolls(comparator);
	return returnList;
    }

    /**
     * Get objects match a specific value.
     *
     * @param comparator
     * @return
     */
    private List<IObjectExpense> getMatchingPayrolls(double comparator) {
	List<IObjectExpense> max = new ArrayList<IObjectExpense>();
	for (IObjectExpense payroll : this.payrolls) {
	    PayrollResultComputation result = ((ProjectPayroll) payroll).getPayrollComputationResult();
	    if (result != null) {
		double total = result.getOverallTotalOfStaff();
		if (total == comparator) {
		    max.add(payroll);
		}
	    }
	}
	return max;
    }

    /**
     * Get min deliveries.
     *
     * @return
     */
    public List<IObjectExpense> getMinDeliveries() {

	// Get the greatest value.
	addValuesDelivery();
	double comparator = getMin();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingDeliveries(comparator);
	return returnList;
    }

    /**
     * Get max deliveries.
     *
     * @return
     */
    public List<IObjectExpense> getMaxDelivery() {

	// Get the greatest value.
	addValuesDelivery();
	double comparator = getMax();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingDeliveries(comparator);
	return returnList;
    }

    /**
     * Get deliveries matching a value.
     *
     * @param comparator
     * @return
     */
    private List<IObjectExpense> getMatchingDeliveries(double comparator) {
	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = new ArrayList<IObjectExpense>();
	// Get all objects that are equal with the greatest value.
	for (IObjectExpense obj : this.deliveries) {
	    double total = obj.getCost();
	    if (total == comparator) {
		returnList.add(obj);
	    }
	}
	return returnList;
    }

    /**
     * Get min equipment.
     *
     * @return
     */
    public List<IObjectExpense> getMinEquipment() {

	// Get the greatest value.
	addValuesEquipment();
	double comparator = getMin();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingEquipment(comparator);
	return returnList;
    }

    /**
     * Get max equipment.
     *
     * @return
     */
    public List<IObjectExpense> getMaxEquipment() {

	// Get the greatest value.
	addValuesEquipment();
	double comparator = getMax();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingEquipment(comparator);
	return returnList;
    }

    private List<IObjectExpense> getMatchingEquipment(double comparator) {
	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = new ArrayList<IObjectExpense>();

	// Get all objects that are equal with the greatest value.
	for (IObjectExpense obj : this.equipment) {
	    double total = obj.getCost();
	    if (total == comparator) {
		returnList.add(obj);
	    }
	}
	return returnList;
    }

    public List<IObjectExpense> getMinOtherExpenses() {
	// Get the greatest value.
	addValuesOtherExpenses();
	double comparator = getMin();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingOtherExpenses(comparator);
	return returnList;
    }

    /**
     * Get max of other expenses.
     *
     * @return
     */
    public List<IObjectExpense> getMaxOtherExpenses() {
	// Get the greatest value.
	addValuesOtherExpenses();
	double comparator = getMax();
	clear();

	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = getMatchingOtherExpenses(comparator);
	return returnList;
    }

    private List<IObjectExpense> getMatchingOtherExpenses(double comparator) {
	// Get all objects that are equal with the greatest value.
	List<IObjectExpense> returnList = new ArrayList<IObjectExpense>();

	// Get all objects that are equal with the greatest value.
	for (IObjectExpense obj : this.otherExpenses) {
	    double total = obj.getCost();
	    if (total == comparator) {
		returnList.add(obj);
	    }
	}
	return returnList;
    }

}


text:
<?php

namespace Domain\Common\UseCase;

/**
 * Class ResponderAwareTrait
 *
 * @package Domain\Common\UseCase
 */
trait ResponderAwareTrait
{
    /**
     * @var ResponderInterface[]
     */
    private $responders = [];

    /**
     * @param ResponderInterface $responder
     */
    public function addResponder(ResponderInterface $responder)
    {
        $this->responders[] = $responder;
    }
}


text:
using System;

namespace NewInTheDotNETFramework
{
    internal class CompatibilitySwitches
    {
        public static void PerformAnOperation()
        {
            //AppContext.SetSwitch("Switch.ThrowOnException", true);

            bool shouldThrow;
            if (!AppContext.TryGetSwitch("Switch.ThrowOnException", out shouldThrow))
            {
                shouldThrow = true;
            }

            if (shouldThrow)
            {
                // old code
            }
            else
            {
                // new code
            }
        }
    }
}


text:
package io.sarl.eclipse.launching.dialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;

import com.google.inject.Injector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationTabGroupViewer;
import org.eclipse.debug.internal.ui.launchConfigurations.LaunchConfigurationsDialog;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup;
import org.eclipse.debug.ui.CommonTab;
import org.eclipse.debug.ui.EnvironmentTab;
import org.eclipse.debug.ui.ILaunchConfigurationDialog;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
import org.eclipse.debug.ui.sourcelookup.SourceLookupTab;
import org.eclipse.jdt.debug.ui.launchConfigurations.JavaClasspathTab;
import org.eclipse.jdt.debug.ui.launchConfigurations.JavaDependenciesTab;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.xtext.xbase.lib.Functions.Function1;

import io.sarl.eclipse.SARLEclipseConfig;
import io.sarl.eclipse.SARLEclipsePlugin;

/**
 * Abstract tab group for run configurations of a SARL element.
 *
 *
This class provides the tools for helping to build a tab group for running SARL agents and SARL applications.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 0.7
 */
public abstract class AbstractSARLLaunchConfigurationTabGroup extends AbstractLaunchConfigurationTabGroup {

	@Inject
	private Injector injector;

	/** Constructor.
	 */
	public AbstractSARLLaunchConfigurationTabGroup() {
		//
	}

	/** {@inheritDoc}
	 *
	 *
This function is overridden in order to inject the members of the tabs.
	 *
	 * @param tabs the tabs to add into the panel.
	 */
	@Override
	protected void setTabs(ILaunchConfigurationTab... tabs) {
		//Override the function for automatic injection within the tabs.
		if (this.injector != null) {
			for (final ILaunchConfigurationTab tab : tabs) {
				this.injector.injectMembers(tab);
			}
		}
		//
		super.setTabs(tabs);
	}

	/** Build the list of the tabs to be inserted into the launch configuration panel.
	 *
	 *
This function adds the panels that are provided by the given {@code builder}, and
	 * the panels that are provided by the plugin contributions.
	 *
	 *
The {@code builder} is invoked with an empty list of panels.
	 * The panels that are given by extension points are added after.
	 * If the boolean value replied by {@code builder} is evaluated to {@code true}, the following standard panels
	 * are automatically added to the launch configuration after the ones provided by the extension points:

	 *
the class-path tab,

	 *
the source look-up tab,

	 *
the environment variable tab,

	 *
the common tab.

	 *

	 *
	 * @param dialog is the reference to the launch configuration dialog box.
	 * @param mode the running mode.
	 * @param builder the builder that is able to fill out the list of panels. The parameter of the procedure
	 *     is the list to fill with the panels.
	 * @return the list of tabs to be added into the panel, before they are injected.
	 * @since 0.12
	 * @see #setTabs(ILaunchConfigurationTab...)
	 */
	protected ILaunchConfigurationTab[] buildTabList(
			ILaunchConfigurationDialog dialog,
			String mode,
			Function1<List<ILaunchConfigurationTab>, Boolean> builder) {
		assert builder != null;
		final List<ILaunchConfigurationTab> list = new ArrayList<>();

		final Boolean addStandardPanels = builder.apply(list);

		// Find the SARL run-time environment tab
		ISarlRuntimeEnvironmentTab runtimeTab = null;
		for (final ILaunchConfigurationTab tab : list) {
			if (tab instanceof ISarlRuntimeEnvironmentTab) {
				runtimeTab = (ISarlRuntimeEnvironmentTab) tab;
				break;
			}
		}

		final List<ISarlLaunchConfigurationPanelFactory> factories = getFactoriesFromExtension();
		for (final ISarlLaunchConfigurationPanelFactory factory : factories) {
			if (factory.canCreatePanel(dialog, mode, list, runtimeTab)) {
				final ILaunchConfigurationTab panel = factory.newLaunchConfigurationPanel(dialog, mode, list, runtimeTab);
				if (panel != null) {
					list.add(panel);
					if (panel instanceof ISreChangeListener) {
						runtimeTab.addSreChangeListener((ISreChangeListener) panel);
					}
				}
			}
		}

		if (addStandardPanels == null || addStandardPanels.booleanValue()) {
			list.add(getClasspathTab(dialog));
			list.add(new SourceLookupTab());
			list.add(new EnvironmentTab());
			list.add(new CommonTab());
		}

		final ILaunchConfigurationTab[] array = new ILaunchConfigurationTab[list.size()];
		list.toArray(array);
		return array;
	}

	private static List<ISarlLaunchConfigurationPanelFactory> getFactoriesFromExtension() {
		final IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(
				SARLEclipsePlugin.PLUGIN_ID,
				SARLEclipseConfig.EXTENSION_POINT_LAUNCH_CONFIGURATION_PANEL_FACTORY);
		if (extensionPoint != null) {
			final List<ISarlLaunchConfigurationPanelFactory> factories = new ArrayList<>();
			for (final IConfigurationElement element : extensionPoint.getConfigurationElements()) {
				try {
					final Object obj = element.createExecutableExtension("class"); //$NON-NLS-1$
					if (obj instanceof ISarlLaunchConfigurationPanelFactory) {
						factories.add((ISarlLaunchConfigurationPanelFactory) obj);
					} else {
						SARLEclipsePlugin.getDefault().logErrorMessage(
								"Cannot instance extension point: " + element.getName()); //$NON-NLS-1$
					}
				} catch (CoreException e) {
					SARLEclipsePlugin.getDefault().log(e);
				}
			}
			return factories;
		}
		return Collections.emptyList();
	}

	/** Register the given SRE listener on any change of SRE selection into the run-time environment tab.
	 * This function does nothing if there is no tab for the run-time environment into the given list.
	 *
	 * @param listOfTabs is the list of the registered tabs.
	 * @param listeners is the list of the objects to register as listener on the SRE selection changes.
	 * @since 0.12
	 */
	protected static void addSreChangeListeners(List<ILaunchConfigurationTab> listOfTabs, ISreChangeListener... listeners) {
		if (listOfTabs != null && listeners != null) {
			for (final ILaunchConfigurationTab tab : listOfTabs) {
				if (tab instanceof ISarlRuntimeEnvironmentTab) {
					final ISarlRuntimeEnvironmentTab runtimeTab = (ISarlRuntimeEnvironmentTab) tab;
					for (final ISreChangeListener listener : listeners) {
						runtimeTab.addSreChangeListener(listener);
					}
				}
			}
		}
	}

	/** Replies the preferred tab for configuring the classpath.
	 * The tab may be the standard {@link JavaClasspathTab} or its specialization
	 * {@link JavaDependenciesTab}.
	 *
	 * @param dialog the dialog that will contains the tab.
	 * @return the tab instance, never {@code null}.
	 */
	protected static JavaClasspathTab getClasspathTab(ILaunchConfigurationDialog dialog) {
		JavaClasspathTab tab = null;
		if (dialog instanceof LaunchConfigurationsDialog) {
			final LaunchConfigurationTabGroupViewer tabViewer = ((LaunchConfigurationsDialog) dialog).getTabViewer();
			if (tabViewer != null) {
				final Object input = tabViewer.getInput();
				if (input instanceof ILaunchConfiguration) {
					final ILaunchConfiguration configuration = (ILaunchConfiguration) input;
					if (JavaRuntime.isModularConfiguration(configuration)) {
						tab = new JavaDependenciesTab();
					}
				}
			}
		}
		if (tab == null) {
			tab = new JavaClasspathTab();
		}
		return tab;
	}

}


text:
<?php

namespace Magento\Sales\Model\Order;

use Magento\TestFramework\Helper\Bootstrap;

class AddressTest extends \PHPUnit_Framework_TestCase
{
    /** @var Address */
    protected $_model;

    protected function setUp()
    {
        $this->_model = Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order\Address');
    }

    /**
     * @magentoDataFixture Magento/Sales/_files/order.php
     * @magentoDataFixture Magento/Customer/_files/customer.php
     * @magentoDataFixture Magento/Customer/_files/customer_address.php
     */
    public function testSave()
    {
        /** @var \Magento\Sales\Model\Order $order */
        $order = Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order');
        $order->loadByIncrementId('100000001');
        $this->_model->setOrder($order);
        $this->_model->setEmail('co@co.co');
        $this->_model->setPostcode('12345');
        $this->_model->setLastname('LastName');
        $this->_model->setStreet('Street');
        $this->_model->setCity('City');
        $this->_model->setTelephone('123-45-67');
        $this->_model->setCountryId(1);
        $this->_model->setFirstname('FirstName');
        $this->_model->setAddressType('billing');
        $this->_model->setRegionId(1);
        $this->_model->save();
        $this->assertEquals($order->getId(), $this->_model->getParentId());
    }
}


text:
$(document).ready(function () {
    $('#btn-signin-irods').on('click', function () {
        if (sessionStorage.IRODS_username) {
            $("#username").val(sessionStorage.IRODS_username);
        }
        if (sessionStorage.IRODS_password) {
            $("#password").val(sessionStorage.IRODS_password);
        }
        if (sessionStorage.IRODS_host) {
            $("#host").val(sessionStorage.IRODS_host);
        }
        if (sessionStorage.IRODS_port) {
            $("#port").val(sessionStorage.IRODS_port);
        }
        if (sessionStorage.IRODS_zone) {
            $("#zone").val(sessionStorage.IRODS_zone);
        }
    });

    $('#btn-signout-irods').on('click', function () {
        if ($("#irods-group").length) {
            // Logic for resource landing page
            $("#irods-group > .btn > span:first-child").text("iRODS");
            $("#btn-signin-irods").toggleClass("hidden", false);
            $("#btn-select-irods-file").toggleClass("hidden", true);
            $("#btn-signout-irods").toggleClass("hidden", true);
            $("#irods-group .divider").toggleClass("hidden", true);
        }
        else {
            // Logic for Create Resource page
            $("#sign-in-name").text('');
            $("#sign-in-info").removeClass();
            $("#sign-in-info").addClass("hidden");
            sessionStorage.IRODS_signininfo = '';
            $("#btn-select-irods-file").toggleClass("hidden", true);
            $("#log-into-irods").show();
            $("#btn-signout-irods").toggleClass("hidden", true);
            $('#irods-copy-move').hide();
        }
    });

    function irods_login() {
        $("#irodsSignin .btn-primary").text("Signing in...");
        $("#irodsSignin .btn-primary").toggleClass("disabled", true);
        $("#irodsLogin .modal-body .alert").remove();
        $.ajax({
            url: "/irods/login/",
            type: "POST",
            data: {
                username: $('#username').val(),
                password: $('#password').val(),
                zone: $('#zone').val(),
                host: $('#host').val(),
                port: $('#port').val()
            },
            success: function (json) {
                if (json.irods_loggedin) {
                    if ($("#irods-group").length) {
                        // Logic for resource landing page
                        $("#irods-group > .btn > span:first-child").text("iRODS: " + json.user);
                        $("#btn-signin-irods").toggleClass("hidden", true);
                        $("#btn-select-irods-file").toggleClass("hidden", false);
                        $("#btn-signout-irods").toggleClass("hidden", false);
                        $("#irods-group .divider").toggleClass("hidden", false);
                    }
                    else {
                        // Logic for Create Resource page
                        var signInStr = "Signed in as " + json.user;
                        $("#sign-in-info").removeClass();
                        $("#sign-in-info").addClass("alert alert-info");
                        $("#sign-in-name").text(signInStr);
                        $("#irods_content_label").text(json.user);
                        $('#root_store').val(json.datastore);
                        $("#log-into-irods").hide();
                        $("#btn-signout-irods").toggleClass("hidden", false);
                        $("#btn-select-irods-file").toggleClass("hidden", false);
                    }

                    sessionStorage.IRODS_signininfo = signInStr;
                    sessionStorage.IRODS_datastore = json.datastore;
                    sessionStorage.IRODS_username = json.user;
                    sessionStorage.IRODS_password = json.password;
                    sessionStorage.IRODS_port = json.port;
                    sessionStorage.IRODS_host = json.host;
                    sessionStorage.IRODS_zone = json.zone;
                }
                else {
                    if ($("#irods-group").length) {
                        // Logic for resource landing page
                        $("#irods-group > .btn > span:first-child").text("iRODS");
                        $("#btn-signin-irods").toggleClass("hidden", false);
                        $("#btn-select-irods-file").toggleClass("hidden", true);
                        $("#btn-signout-irods").toggleClass("hidden", true);
                        $("#irods-group .divider").toggleClass("hidden", true);
                    }
                    else {
                        // Logic for Create Resource page
                        $("#sign-in-name").text('iRODS login failed');
                        $("#sign-in-info").removeClass();
                        $("#sign-in-info").addClass("alert alert-danger");
                        sessionStorage.IRODS_signininfo = '';
                        $("#btn-select-irods-file").toggleClass("hidden", true);
                    }
                }
                $('#irodsSignin').modal('hide');
                $("#irodsSignin .btn-primary").text("Sign in");
                $("#irodsSignin .btn-primary").toggleClass("disabled", false);
            },
            error: function (xhr, errmsg, err) {
                console.log(xhr.status + ": " + xhr.responseText + ". Error message: " + errmsg);
                sessionStorage.IRODS_signininfo = 'iRODS login failed';
                sessionStorage.IRODS_datastore = '';
                sessionStorage.IRODS_username = '';
                sessionStorage.IRODS_password = '';
                sessionStorage.IRODS_port = '1247';
                sessionStorage.IRODS_host = '';
                sessionStorage.IRODS_zone = '';

                if ($("#irods-group").length) {
                    $("#irodsLogin .modal-body").append("
iRODS login failed
");
                }
                else {
                    $("#sign-in-name").text('iRODS login failed');
                    $("#sign-in-info").removeClass();
                    $("#sign-in-info").addClass("alert alert-danger");
                    $("#btn-select-irods-file").toggleClass("hidden", true);
                    $('#irodsSignin').modal('hide');
                    $("#irodsSignin .btn-primary").text("Sign in");
                    $("#irodsSignin .btn-primary").toggleClass("disabled", false);
                }
                $("#irodsSignin .btn-primary").text("Sign in");
                $("#irodsSignin .btn-primary").toggleClass("disabled", false);
            }
        });
    }

    $('#irodsLogin').on('submit', function (event) {
        event.preventDefault();
        irods_login();
    });
});


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.datamigration.v1beta1.model;

/**
 * Settings for creating a Cloud SQL database instance.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Database Migration API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class CloudSqlSettings extends com.google.api.client.json.GenericJson {

  /**
   * The activation policy specifies when the instance is activated; it is applicable only when the
   * instance state is 'RUNNABLE'. Valid values: 'ALWAYS': The instance is on, and remains so even
   * in the absence of connection requests. `NEVER`: The instance is off; it is not activated, even
   * if a connection request arrives.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String activationPolicy;

  /**
   * [default: ON] If you enable this setting, Cloud SQL checks your available storage every 30
   * seconds. If the available storage falls below a threshold size, Cloud SQL automatically adds
   * additional storage capacity. If the available storage repeatedly falls below the threshold
   * size, Cloud SQL continues to add storage until it reaches the maximum of 30 TB.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean autoStorageIncrease;

  /**
   * The storage capacity available to the database, in GB. The minimum (and default) size is 10GB.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long dataDiskSizeGb;

  /**
   * The type of storage: `PD_SSD` (default) or `PD_HDD`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String dataDiskType;

  /**
   * The database flags passed to the Cloud SQL instance at startup. An object containing a list of
   * "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> databaseFlags;

  /**
   * The database engine type and version (such as `MYSQL_5_7` / `POSTGRES_9_6`).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String databaseVersion;

  /**
   * The settings for IP Management. This allows to enable or disable the instance IP and manage
   * which external networks can connect to the instance. The IPv4 address cannot be disabled.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private SqlIpConfig ipConfig;

  /**
   * Input only. Initial root password.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String rootPassword;

  /**
   * Output only. Indicates If this connection profile root password is stored.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean rootPasswordSet;

  /**
   * The Database Migration Service source connection profile ID, in the format:
   * `projects/my_project_name/locations/us-central1/connectionProfiles/connection_profile_ID`
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String sourceId;

  /**
   * The maximum size to which storage capacity can be automatically increased. The default value is
   * 0, which specifies that there is no limit.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long storageAutoResizeLimit;

  /**
   * The tier (or machine type) for this instance, for example: `db-n1-standard-1` (MySQL instances)
   * or `db-custom-1-3840` (PostgreSQL instances). For more information, see [Cloud SQL Instance
   * Settings](https://cloud.google.com/sql/docs/mysql/instance-settings).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String tier;

  /**
   * The resource labels for a Cloud SQL instance to use to annotate any related underlying
   * resources such as Compute Engine VMs. An object containing a list of "key": "value" pairs.
   * Example: `{ "name": "wrench", "mass": "18kg", "count": "3" }`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> userLabels;

  /**
   * The Google Cloud Platform zone where your Cloud SQL datdabse instance is located.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String zone;

  /**
   * The activation policy specifies when the instance is activated; it is applicable only when the
   * instance state is 'RUNNABLE'. Valid values: 'ALWAYS': The instance is on, and remains so even
   * in the absence of connection requests. `NEVER`: The instance is off; it is not activated, even
   * if a connection request arrives.
   * @return value or {@code null} for none
   */
  public java.lang.String getActivationPolicy() {
    return activationPolicy;
  }

  /**
   * The activation policy specifies when the instance is activated; it is applicable only when the
   * instance state is 'RUNNABLE'. Valid values: 'ALWAYS': The instance is on, and remains so even
   * in the absence of connection requests. `NEVER`: The instance is off; it is not activated, even
   * if a connection request arrives.
   * @param activationPolicy activationPolicy or {@code null} for none
   */
  public CloudSqlSettings setActivationPolicy(java.lang.String activationPolicy) {
    this.activationPolicy = activationPolicy;
    return this;
  }

  /**
   * [default: ON] If you enable this setting, Cloud SQL checks your available storage every 30
   * seconds. If the available storage falls below a threshold size, Cloud SQL automatically adds
   * additional storage capacity. If the available storage repeatedly falls below the threshold
   * size, Cloud SQL continues to add storage until it reaches the maximum of 30 TB.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getAutoStorageIncrease() {
    return autoStorageIncrease;
  }

  /**
   * [default: ON] If you enable this setting, Cloud SQL checks your available storage every 30
   * seconds. If the available storage falls below a threshold size, Cloud SQL automatically adds
   * additional storage capacity. If the available storage repeatedly falls below the threshold
   * size, Cloud SQL continues to add storage until it reaches the maximum of 30 TB.
   * @param autoStorageIncrease autoStorageIncrease or {@code null} for none
   */
  public CloudSqlSettings setAutoStorageIncrease(java.lang.Boolean autoStorageIncrease) {
    this.autoStorageIncrease = autoStorageIncrease;
    return this;
  }

  /**
   * The storage capacity available to the database, in GB. The minimum (and default) size is 10GB.
   * @return value or {@code null} for none
   */
  public java.lang.Long getDataDiskSizeGb() {
    return dataDiskSizeGb;
  }

  /**
   * The storage capacity available to the database, in GB. The minimum (and default) size is 10GB.
   * @param dataDiskSizeGb dataDiskSizeGb or {@code null} for none
   */
  public CloudSqlSettings setDataDiskSizeGb(java.lang.Long dataDiskSizeGb) {
    this.dataDiskSizeGb = dataDiskSizeGb;
    return this;
  }

  /**
   * The type of storage: `PD_SSD` (default) or `PD_HDD`.
   * @return value or {@code null} for none
   */
  public java.lang.String getDataDiskType() {
    return dataDiskType;
  }

  /**
   * The type of storage: `PD_SSD` (default) or `PD_HDD`.
   * @param dataDiskType dataDiskType or {@code null} for none
   */
  public CloudSqlSettings setDataDiskType(java.lang.String dataDiskType) {
    this.dataDiskType = dataDiskType;
    return this;
  }

  /**
   * The database flags passed to the Cloud SQL instance at startup. An object containing a list of
   * "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getDatabaseFlags() {
    return databaseFlags;
  }

  /**
   * The database flags passed to the Cloud SQL instance at startup. An object containing a list of
   * "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.
   * @param databaseFlags databaseFlags or {@code null} for none
   */
  public CloudSqlSettings setDatabaseFlags(java.util.Map<String, java.lang.String> databaseFlags) {
    this.databaseFlags = databaseFlags;
    return this;
  }

  /**
   * The database engine type and version (such as `MYSQL_5_7` / `POSTGRES_9_6`).
   * @return value or {@code null} for none
   */
  public java.lang.String getDatabaseVersion() {
    return databaseVersion;
  }

  /**
   * The database engine type and version (such as `MYSQL_5_7` / `POSTGRES_9_6`).
   * @param databaseVersion databaseVersion or {@code null} for none
   */
  public CloudSqlSettings setDatabaseVersion(java.lang.String databaseVersion) {
    this.databaseVersion = databaseVersion;
    return this;
  }

  /**
   * The settings for IP Management. This allows to enable or disable the instance IP and manage
   * which external networks can connect to the instance. The IPv4 address cannot be disabled.
   * @return value or {@code null} for none
   */
  public SqlIpConfig getIpConfig() {
    return ipConfig;
  }

  /**
   * The settings for IP Management. This allows to enable or disable the instance IP and manage
   * which external networks can connect to the instance. The IPv4 address cannot be disabled.
   * @param ipConfig ipConfig or {@code null} for none
   */
  public CloudSqlSettings setIpConfig(SqlIpConfig ipConfig) {
    this.ipConfig = ipConfig;
    return this;
  }

  /**
   * Input only. Initial root password.
   * @return value or {@code null} for none
   */
  public java.lang.String getRootPassword() {
    return rootPassword;
  }

  /**
   * Input only. Initial root password.
   * @param rootPassword rootPassword or {@code null} for none
   */
  public CloudSqlSettings setRootPassword(java.lang.String rootPassword) {
    this.rootPassword = rootPassword;
    return this;
  }

  /**
   * Output only. Indicates If this connection profile root password is stored.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getRootPasswordSet() {
    return rootPasswordSet;
  }

  /**
   * Output only. Indicates If this connection profile root password is stored.
   * @param rootPasswordSet rootPasswordSet or {@code null} for none
   */
  public CloudSqlSettings setRootPasswordSet(java.lang.Boolean rootPasswordSet) {
    this.rootPasswordSet = rootPasswordSet;
    return this;
  }

  /**
   * The Database Migration Service source connection profile ID, in the format:
   * `projects/my_project_name/locations/us-central1/connectionProfiles/connection_profile_ID`
   * @return value or {@code null} for none
   */
  public java.lang.String getSourceId() {
    return sourceId;
  }

  /**
   * The Database Migration Service source connection profile ID, in the format:
   * `projects/my_project_name/locations/us-central1/connectionProfiles/connection_profile_ID`
   * @param sourceId sourceId or {@code null} for none
   */
  public CloudSqlSettings setSourceId(java.lang.String sourceId) {
    this.sourceId = sourceId;
    return this;
  }

  /**
   * The maximum size to which storage capacity can be automatically increased. The default value is
   * 0, which specifies that there is no limit.
   * @return value or {@code null} for none
   */
  public java.lang.Long getStorageAutoResizeLimit() {
    return storageAutoResizeLimit;
  }

  /**
   * The maximum size to which storage capacity can be automatically increased. The default value is
   * 0, which specifies that there is no limit.
   * @param storageAutoResizeLimit storageAutoResizeLimit or {@code null} for none
   */
  public CloudSqlSettings setStorageAutoResizeLimit(java.lang.Long storageAutoResizeLimit) {
    this.storageAutoResizeLimit = storageAutoResizeLimit;
    return this;
  }

  /**
   * The tier (or machine type) for this instance, for example: `db-n1-standard-1` (MySQL instances)
   * or `db-custom-1-3840` (PostgreSQL instances). For more information, see [Cloud SQL Instance
   * Settings](https://cloud.google.com/sql/docs/mysql/instance-settings).
   * @return value or {@code null} for none
   */
  public java.lang.String getTier() {
    return tier;
  }

  /**
   * The tier (or machine type) for this instance, for example: `db-n1-standard-1` (MySQL instances)
   * or `db-custom-1-3840` (PostgreSQL instances). For more information, see [Cloud SQL Instance
   * Settings](https://cloud.google.com/sql/docs/mysql/instance-settings).
   * @param tier tier or {@code null} for none
   */
  public CloudSqlSettings setTier(java.lang.String tier) {
    this.tier = tier;
    return this;
  }

  /**
   * The resource labels for a Cloud SQL instance to use to annotate any related underlying
   * resources such as Compute Engine VMs. An object containing a list of "key": "value" pairs.
   * Example: `{ "name": "wrench", "mass": "18kg", "count": "3" }`.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getUserLabels() {
    return userLabels;
  }

  /**
   * The resource labels for a Cloud SQL instance to use to annotate any related underlying
   * resources such as Compute Engine VMs. An object containing a list of "key": "value" pairs.
   * Example: `{ "name": "wrench", "mass": "18kg", "count": "3" }`.
   * @param userLabels userLabels or {@code null} for none
   */
  public CloudSqlSettings setUserLabels(java.util.Map<String, java.lang.String> userLabels) {
    this.userLabels = userLabels;
    return this;
  }

  /**
   * The Google Cloud Platform zone where your Cloud SQL datdabse instance is located.
   * @return value or {@code null} for none
   */
  public java.lang.String getZone() {
    return zone;
  }

  /**
   * The Google Cloud Platform zone where your Cloud SQL datdabse instance is located.
   * @param zone zone or {@code null} for none
   */
  public CloudSqlSettings setZone(java.lang.String zone) {
    this.zone = zone;
    return this;
  }

  @Override
  public CloudSqlSettings set(String fieldName, Object value) {
    return (CloudSqlSettings) super.set(fieldName, value);
  }

  @Override
  public CloudSqlSettings clone() {
    return (CloudSqlSettings) super.clone();
  }

}


text:
\chapter{Making Tiled MIP-Map Texture Files With \maketx or \oiiotool}
\label{chap:maketx}
\indexapi{maketx}
\index{Texture System!making textures with maketx}

\section{Overview}

The \TextureSystem (Chapter~\ref{chap:texturesystem}) will exhibit much
higher performance if the image files it uses as textures are tiled (versus
scanline) orientation, have multiple subimages at different resolutions
(MIP-mapped), and include a variety of header or metadata fields
appropriately set for texture maps. Any image that you intend to use as
input to \TextureSystem, therefore, should first be converted to have these
properties. An ordinary image will work as a texture, but without this
additional step, it will be drastically less efficient in terms of memory,
disk or network I/O, and time.

This can be accomplished programmatically using the \ImageBufAlgo\ {\cf
make_texture()} function (see Section~\ref{sec:iba:importexport} for C++ and
Section~\ref{sec:iba:py:importexport} for Python).

\product includes two command-line utilities capable of converting
ordinary images into texture files: \maketx and \oiiotool.\footnote{Why
are there two programs? Historical artifact -- \maketx existed first,
and much later \oiiotool was extended to be capable of directly writing
texture files. If you are simply converting an image into
a texture, \maketx is more straightforward and foolproof, in that you
can't accidentally forget to turn it into a texture, as you might do
with \oiiotool. On the other hand, \oiiotool is the way to go if you have
a complex series of image processing operations and want the end result
to be a texture, without having to write an intermediate file to feed
separately to \maketx.}

\section{\maketx}
\label{sec:maketx}

The \maketx program will convert ordinary images to efficient
textures. The \maketx utility is invoked as follows:

\medskip

\hspace{0.25in} {\cf maketx} [\emph{options}] \emph{input}... {\cf -o} \emph{output}

\medskip

Where \emph{input} and \emph{output} name the input image and desired
output filename.  The input files may be of any image format recognized by
\product (i.e., for which \ImageInput plugins are available).  The file
format of the output image will be inferred from the file extension of
the output filename (e.g., \qkw{foo.tif} will write a TIFF file).

\medskip
\newpage

\noindent Command-line arguments are:

\apiitem{--help}
Prints usage information to the terminal.
\apiend

\apiitem{-v}
Verbose status messages, including runtime statistics and timing.
\apiend

\apiitem{--runstats}
Print runtime statistics and timing.
\apiend

\apiitem{-o {\rm \emph{outputname}}}
Sets the name of the output texture.
\apiend

\apiitem{--threads \emph{n}}
Use \emph{n} execution threads if it helps to speed up image operations.
The default (also if $n=0$) is to use as many threads as there are cores
present in the hardware.
\apiend

\apiitem{--format {\rm \emph{formatname}}}
Specifies the image format of the output file (e.g., ``tiff'',
``OpenEXR'', etc.).  If {\cf --format} is not used, \maketx will
guess based on the file extension of the output filename; if it
is not a recognized format extension, TIFF will be used by default.
\apiend

\apiitem{-d {\rm \emph{datatype}}}
Attempt to sets the output pixel data type to one of: {\cf uint8},
{\cf sint8}, {\cf uint16}, {\cf sint16}, {\cf half}, {\cf float},
{\cf double}.

If the {\cf -d} option is not supplied, the output data type will
be the same as the data format of the input file.

In either case, the output file format itself (implied by the file
extension of the output filename) may trump the request if the file
format simply does not support the requested data type.
\apiend

\apiitem{--tile {\rm \emph{x}} {\rm \emph{y}}}
Specifies the tile size of the output texture.  If not specified,
\maketx will make $64 \times 64$ tiles.
\apiend

\apiitem{--separate}
Forces ``separate'' (e.g., RRR...GGG...BBB) packing of channels in the
output file.  Without this option specified, ``contiguous'' (e.g.,
RGBRGBRGB...) packing of channels will be used for those file formats
that support it.
\apiend

\apiitem{--compression {\rm \emph{method}}}
Sets the compression method for the output image (the default is to try
to use \qkw{zip} compression, if it is available).
\apiend

\apiitem{-u}
Ordinarily, textures are created unconditionally (which could take
several seconds for large input files if read over a network) and will
be stamped with the current time.

The {\cf -u} option enables \emph{update mode}: if the output file
already exists, and has the same time stamp as the input file, and
the command-lie arguments that created it are identical to the
current ones, then the texture will be left alone and not be recreated.
If the output file does not exist, or has
a different time stamp than the input file, or was created using different
command line arguments, then the texture will be created
and given the time stamp of the input file.
\apiend

\apiitem{--wrap {\rm \emph{wrapmode}} \\
--swrap {\rm \emph{wrapmode}} --twrap {\rm \emph{wrapmode}}}
Sets the default \emph{wrap mode} for the texture, which determines
the behavior when the texture is sampled outside the $[0,1]$ range.
Valid wrap modes are: {\cf black}, {\cf clamp}, {\cf periodic},
{\cf mirror}.  The default, if none is set, is {\cf black}.  The
{\cf --wrap} option sets the wrap mode in both directions
simultaneously, while the {\cf --swrap} and {\cf --twrap} may be used to
set them individually in the $s$ (horizontal) and $t$ (vertical)
diretions.

Although this sets the default wrap mode for a texture, note that
the wrap mode may have an override specified in the texture lookup
at runtime.
\apiend

\apiitem{--resize}
Causes the highest-resolution level of the MIP-map to be a
power-of-two resolution in each dimension
(by rounding up the resolution of the input image).  There is no
good reason to do this for the sake of OIIO's texture system, but
some users may require it in order to create MIP-map images
that are compatible with both OIIO and other texturing systems that
require power-of-2 textures.
\apiend

\apiitem{--filter {\rm \emph{name}}}
By default, the resizing step that generates successive MIP levels
uses a triangle filter to bilinearly combine pixels (for MIP levels
with even number of pixels, this is also equivalent to a box filter,
which merely averages groups of 4 adjacent pixels).  This is fast,
but for source images with high frequency content, can result in
aliasing or other artifacts in the lower-resolution MIP levels.

The {\cf --filter} option selects a high-quality filter to use when
resizing to generate successive MIP levels.  Choices include
{\cf lanczos3} (our best recommendation for highest-quality filtering, a
3-lobe Lanczos filter), {\cf box}, {\cf triangle}, {\cf catrom},
{\cf blackman-harris}, {\cf gaussian}, {\cf mitchell}, {\cf bspline},
\qkw{cubic}, \qkw{keys}, \qkw{simon},
\qkw{rifman}, {\cf radial-lanczos3}, {\cf disk}, {\cf sinc}.

If you select a filter with negative lobes (including
{\cf lanczos3}, {\cf sinc}, {\cf lanczos3}, {\cf keys}, {\cf simon},
{\cf rifman}, or {\cf catrom}), and your
source image is an HDR image with very high contrast regions that
include pixels with values $>1$, you may also wish to use the
{\cf --rangecompress} option to avoid ringing artifacts.
\apiend

\apiitem{--hicomp}
Perform highlight compensation.  When HDR input data with high-contrast
highlights is turned into a MIP-mapped texture using a high-quality
filter with negative lobes (such as {\cf lanczos3}), objectionable
ringing could appear near very high-contrast regions with pixel values
$>1$. This option improves those areas by using range compression
(transforming values from a linear to a logarithmic scale that greatly
compresses the values $> 1$) prior to each
image filtered-resize step, and then expanded back to a linear format
after the resize, and also clamping resulting pixel values to be
non-negative.  This can result in some loss of energy, but often this is
a preferable alternative to ringing artifacts in your upper MIP levels.
\apiend

\apiitem{--sharpen {\rm \emph{contrast}}}
EXPERIMENTAL: USE AT YOUR OWN RISK!

This option will run an additional sharpening filter
when creating the successive MIP-map levels. It uses an unsharp mask
(much like in Section~\ref{sec:iba:unsharpmask}) to emphasize high-frequency
details to make features ``pop'' visually even at high MIP-map levels.
The \emph{contrast} controls the degree to which it does this. Probably
a good value to enhance detail but not go overboard is 0.5 or even 0.25.
A value of 1.0 may make strage artifacts at high MIP-map levels. Also, if
you simultaneously use {\cf --filter unsharp-median}, a slightly different
variant of unsharp masking will be used that employs a median filter to
separate out the low-frequencies, this may tend to help emphasize small
features while not over-emphasizing large edges.
\apiend

\apiitem{--nomipmap}
Causes the output to \emph{not} be MIP-mapped, i.e., only will have
the highest-resolution level.
\apiend

\apiitem{--nchannels {\rm \emph{n}}}
Sets the number of output channels.  If \emph{n} is less than the
number of channels in the input image, the extra channels will simply
be ignored.  If \emph{n} is greater than the number of channels in the
input image, the additional channels will be filled with 0 values.
\apiend

\apiitem{--chnames {\rm \emph{a,b,...}}}
Renames the channels of the output image.  All the channel names are
concatenated together, separated by commas.  A ``blank'' entry will cause
the channel to retain its previous value (for example, {\cf --chnames ,,,A}
will rename channel 3 to be \qkw{A} and leave channels 0--2 as they were.
\apiend

\apiitem{--checknan}
Checks every pixel of the input image to ensure that no NaN or Inf
values are present.  If such non-finite pixel values are found,
an error message will be printed and {\cf maketx} will terminate without
writing the output image (returning an error code).
\apiend

\apiitem{--fixnan {\rm \emph{streategy}}}
Repairs any pixels in the input image that contained {\cf NaN} or
{\cf Inf} values (hereafter referred to collectively as ``nonfinite'').
If \emph{strategy} is {\cf black}, nonfinite values will be replaced
with {\cf 0}.  If \emph{strategy} is {\cf box3}, nonfinite values will
be replaced by the average of all the finite values within a $3 \times 3$
region surrounding the pixel.
\apiend

\apiitem{--fullpixels}
Resets the ``full'' (or ``display'') pixel range to be the ``data''
range.  This is used to deal with input images that appear, in their
headers, to be crop windows or overscanned images, but you want to treat
them as full 0--1 range images over just their defined pixel data.
\apiend

%\apiitem{--ingamma {\rm \emph{value}} \\
%--outgamma {\rm \emph{value}}}
%Not currently implemented
%\apiend

\apiitem{--Mcamera {\rm \emph{...16 floats...}} \\
--Mscreen {\rm \emph{...16 floats...}}}
Sets the camera and screen matrices (sometimes called {\cf Nl} and
{\cf NP}, respectively, by some renderers) in the texture file,
overriding any such matrices that may be in the input image (and would
ordinarily be copied to the output texture).
\apiend

\apiitem{--prman-metadata}
Causes metadata \qkw{PixarTextureFormat} to be set, which is useful if
you intend to create an OpenEXR texture or environment map that can be
used with PRMan as well as OIIO.
\apiend

\apiitem{--attrib {\rm \emph{name value}}}
Adds or replaces metadata with the given \emph{name} to have the
specified \emph{value}.

It will try to infer the type of the metadata from the value: if the
value contains only numerals (with optional leading minus sign), it will
be saved as {\cf int} metadata; if it also contains a decimal point, it
will be saved as {\cf float} metadata; otherwise, it will be saved as
a {\cf string} metadata.

For example, you could explicitly set the IPTC location metadata fields
with:
\begin{code}
        oiiotool --attrib "IPTC:City" "Berkeley" in.jpg out.jpg
\end{code}
\apiend

\apiitem{--sattrib {\rm \emph{name value}}}
Adds or replaces metadata with the given \emph{name} to have the
specified \emph{value}, forcing it to be interpreted as a {\cf string}.
This is helpful if you want to set a {\cf string} metadata to a value
that the {\cf --attrib} command would normally interpret as a number.
\apiend

\apiitem{--sansattrib}
When set, this edits the command line inserted in the \qkw{Software} and
\qkw{ImageHistory} metadata to omit any verbose {\cf --attrib} and
{\cf --sattrib} commands.
\apiend

\apiitem{--constant-color-detect}
Detects images in which all pixels are identical, and outputs the
texture at a reduced resolution equal to the tile size, rather than
filling endless tiles with the same constant color.  That is, by
substituting a low-res texture for a high-res texture if it's a constant
color, you could save a lot of save disk space, I/O, and texture cache size.
It also sets the \qkw{ImageDescription} to contain a
special message of the form \qkw{ConstantColor=[r,g,...]}.
\apiend

\apiitem{--monochrome-detect}
Detects multi-channel images in which all color components are
identical, and outputs the texture as a single-channel image instead.
That is, it changes RGB images that are gray into single-channel gray
scale images.

Use with caution!  This is a great optimization if such textures will
only have their first channel accessed, but may cause unexpected behavior
if the ``client'' application will attempt to access those other
channels that will no longer exist.
\apiend

\apiitem{--opaque-detect}
Detects images that have a designated alpha channel for which the alpha value
for all pixels is 1.0 (fully opaque), and omits the alpha channel from
the output texture.  So, for example, an RGBA input texture where A=1
for all pixels will be output just as RGB.  The purpose is to save disk
space, texture I/O bandwidth, and texturing time for those textures
where alpha was present in the input, but clearly not necessary.

Use with caution!  This is a great optimization only if your use of such
textures will assume that missing alpha channels are equivalent to
textures whose alpha is 1.0 everywhere.
\apiend

\apiitem{--ignore-unassoc}
Ignore any header tags in the input images that indicate that the
input has ``unassociated'' alpha.  When this option is used, color
channels with unassociated alpha will not be automatically multiplied
by alpha to turn them into associated alpha. This is also a good way
to fix input images that really are associated alpha, but whose headers
incorrectly indicate that they are unassociated alpha.
\apiend

\apiitem{--prman}
PRMan is will crash in strange ways if given textures that don't have
its quirky set of tile sizes and other specific metadata.  If you want
\maketx to generate textures that may be used with either \OpenImageIO
or PRMan, you should use the {\cf --prman} option, which will set
several options to make PRMan happy, overriding any contradictory
settings on the command line or in the input texture.

Specifically, this option sets the tile size (to 64x64 for 8 bit,
64x32 for 16 bit integer, and 32x32 for float or {\cf half} images),
uses ``separate'' planar configuration ({\cf --separate}), and sets
PRMan-specific metadata ({\cf --prman-metadata}).  It also outputs
sint16 textures if uint16 is requested (because PRMan for some reason
does not accept true uint16 textures), and in the case of TIFF files will
omit the Exif directory block which will not be recognized by the older
version of libtiff used by PRMan.

\OpenImageIO will happily accept textures that conform to PRMan's
expectations, but not vice versa.  But \OpenImageIO's \TextureSystem
has better performance with textures that use \maketx's default settings
rather than these oddball choices.  You have been warned!
\apiend

\apiitem{--oiio}
This sets several options that we have determined are the
optimal values for \OpenImageIO's \TextureSystem, overriding any
contradictory settings on the command line or in the input texture.

Specifically, this is the equivalent to using \\
 {\cf --separate --tile 64 64}.
\apiend

\apiitem{--colorconvert {\rm \emph{inspace outspace}}}
Convert the color space of the input image from \emph{inspace} to
\emph{tospace}.  If OpenColorIO is installed and finds a valid
configuration, it will be used for the color conversion.  If OCIO
is not enabled (or cannot find a valid configuration, OIIO will at
least be able to convert among linear, sRGB, and Rec709.
\apiend

\apiitem{--unpremult}
When undergoing some color conversions, it is helpful to
``un-premultiply'' the alpha before converting color channels, and then
re-multiplying by alpha.  Caveat emptor -- if you don't know exactly
when to use this, you probably shouldn't be using it at all.
\apiend

\apiitem{--mipimage {\rm \emph{filename}}}
Specifies the name of an image file to use as a custom MIP-map level,
instead of simply downsizing the last one.  This option may be used
multiple times to specify multiple levels.  For example:
\begin{code}
    maketx 256.tif --miplevel 128.tif --miplevel 64.tif -o out.tx
\end{code}
This will make a texture with the first MIP level taken from {\cf 256.tif},
the second level from {\cf 128.tif}, the third from {\cf 64.tif}, and
then subsequent levels will be the usual downsizings of {\cf 64.tif}.
\apiend

\apiitem{--envlatl}
Creates a latitude-longitude environment map, rather than an ordinary
texture map.
\apiend

\apiitem{--lightprobe}
Creates a latitude-longitude environment map, but in contrast to
{\cf --envlatl}, the original input image is assumed to be formatted
as a \emph{light probe} image\footnote{See
{\cf http://www.pauldebevec.com/Probes/} for examples and an explanation
of the geometric layout.}.
\apiend

% --shadow --shadcube
% --volshad --envlatl --envcube --lightprobe --latl2envcube --vertcross
% --fov
% --opaquewidth

\begin{comment}

\subsection{{\cf maketx} Recipes}

% FIXME

This section will give quick examples of common uses of {\cf maketx}.

\subsection*{Converting between file formats}

It's a snap to converting among image formats supported by \product
(i.e., for which \ImageInput and \ImageOutput plugins can be found).
The {\cf maketx} utility will simply infer the file format from the
file extension. The following example converts a PNG image to JPEG:

\begin{code}
    maketx lena.png lena.jpg
\end{code}

\end{comment}

\section{\oiiotool}
\label{sec:oiiotooltex}

The \oiiotool utility (Chapter~\ref{chap:oiiotool}) is capable of writing
textures using the {\cf -otex} option, and lat-long environment maps using
the {\cf -oenv} option. Roughly speaking,

\medskip

\hspace{0.25in} {\cf maketx} [\emph{maketx-options}] \emph{input} {\cf -o} \emph{output}

\medskip

\noindent is equivalent to

\medskip

\hspace{0.25in} {\cf oiiotool} \emph{input} [\emph{oiiotool-options}] {\cf -otex} \emph{output}

\medskip

\noindent and

\medskip

\hspace{0.25in} {\cf maketx -envlatl} [\emph{maketx-options}] \emph{input} {\cf -o} \emph{output}

\medskip

\noindent is equivalent to

\medskip

\hspace{0.25in} {\cf oiiotool} \emph{input} [\emph{oiiotool-options}] {\cf -oenv} \emph{output}

\medskip

\noindent However, the notation for the various options are not identical
between the two programs, as will be explained by the remainder of this
section.

The most important difference between \oiiotool and \maketx is that
\oiiotool can do so much more than convert an existing input image to a
texture -- literally any image creation or manipulation you can do via
\oiiotool may be output directly as a full texture file using {\cf -otex}
(or as a lat-long environment map using {\cf -oenv}).

Note that it is vitally important that you use one of the texture output
commands ({\cf -otex} or {\cf -oenv}) when creating textures with \oiiotool
--- if you inadvertently forget and use an ordinary {\cf -o}, you will end
up with an output image that is much less efficient to use as a texture.

\subsubsection*{Command line arguments useful when creating textures}

As with any use of \oiiotool, you may use the following to control the
run generally:

\apiitem{{--help \\
-v \\
--runstats \\
--threads} \emph{n}}
\apiend

\noindent and as with any use of \oiiotool, you may use the following
command-line options to control aspects of the any output files (including
those from {\cf -otex} and {\cf -oenv}, as well as {\cf -o}). Only brief
descriptions are given below, please consult Chapter~\ref{chap:oiiotool} for
detailed explanations.

\apiitem{{-d} {\rm \emph{datatype}}}
Specify the pixel data type ({\cf uint8}, {\cf uint16}, {\cf half}, {\cf float},
etc.) if you wish to override the default of writing the same data type as
the first input file read.
\apiend

\apiitem{{--tile} {\rm \emph{x}} {\rm \emph{y}}}
Explicitly override the tile size (though you are strongly urged to use
the default, and not use this command).
\apiend

\apiitem{{--compression} {\rm \emph{method}}}
Explicitly override the default compression methods when writing
the texture file.
\apiend

\apiitem{--ch {\rm \emph{channellist}}}
Shuffle, add, delete, or rename channels (see \ref{sec:oiiotool:ch}).
\apiend

\apiitem{--chnames {\rm \emph{a,b,...}}}
Renames the channels of the output image.
\apiend

\apiitem{--fixnan {\rm \emph{stretegy}}}
Repairs any pixels in the input image that contained {\cf NaN} or
{\cf Inf} values (if the \emph{strategy} is {\cf box3} or {\cf black}),
or to simply abort with an error message (if the \emph{strategy} is {\cf error}).
\apiend

\apiitem{--fullpixels}
Resets the ``full'' (or ``display'') pixel range to be the ``data'' range.
\apiend

\apiitem{--planarconfig separate}
Forces ``separate'' (e.g., RRR...GGG...BBB) packing of channels in the
output texture.  This is almost always a bad choice, unless you know that
the texture file must be readable by PRMan, in which case it is required.
\apiend

\apiitem{--attrib {\rm \emph{name ~ value}}}
\oiiotool's {\cf --attrib} command may be used to set attributes
in the metadata of the output texture.
\apiend

\apiitem{--attrib:type=matrix worldtocam {\rm \emph{...16 comma-separated floats...}} \\
--attrib:type=matrix screentocam {\rm \emph{...16 comma-separated floats...}}}
Set/override the camera and screen matrices.
\apiend

\subsubsection*{Optional arguments to {\cf -otex} and {\cf -oenv}}

As with many \oiiotool commands, the {\cf -otex} and {\cf -oenv} may
have various optional arguments appended, in the form {\cf :name=value}
(see Section~\ref{sec:oiiotooloptionalargs}).

Optional arguments supported by {\cf -otex} and {\cf -oenv} include all
the same options as {\cf -o} (Section~\ref{sec:oiiotool:o}) and also the
following (explanations are brief, please consult Section~\ref{sec:maketx}
for more detailed explanations of each, for the corresponding \maketx
option):

\medskip

\noindent \begin{tabular}{p{2in} p{3in}}
Appended Option & \maketx equivalent \\ \hline
{\cf wrap=}\emph{string} & {\cf --wrap} \\
{\cf swrap=}\emph{string} & {\cf --swrap} \\
{\cf twrap=}\emph{string} & {\cf --twrap} \\[.5ex]
{\cf resize=1} & {\cf --resize} \\
{\cf nomipmap=1} & {\cf --nomipmap} \\
{\cf updatemode=1} & {\cf -u} \\
{\cf monochrome_detect=1} & {\cf --monochrome-detect} \\
{\cf opaque_detect=1} & {\cf --opaque-detect} \\
{\cf unpremult=1} & {\cf --unpremult} \\
{\cf incolorspace=}\emph{name} & {\cf --incolorspace} \\
{\cf outcolorspace=}\emph{name} & {\cf --outcolorspace} \\
{\cf hilightcomp=1} & {\cf --hicomp} \\
{\cf sharpen=}\emph{float} & {\cf --sharpen} \\
{\cf filter=}\emph{string} & {\cf --filter} \\
%{\cf oiio_options=1} &  {\cf --oiio} \\
{\cf prman_metadata=1} & {\cf --prman} \\
{\cf prman_options=1} & {\cf --prman-metadata} \\
\end{tabular}

\subsubsection*{Examples}

\begin{code}
oiiotool in.tif -otex out.tx

oiiotool in.jpg --colorconvert sRGB linear -d uint16 -otex out.tx

oiiotool --pattern:checker 512x512 3 -d uint8 -otex:wrap=periodic checker.tx

oiiotool in.exr -otex:hilightcomp=1:sharpen=0.5 out.exr
\end{code}