text:
To enable stackdriver adapter:

1.  Download istio/installer repo:

    ```bash
    git clone https://github.com/istio/installer && cd installer
    ```

1.  Render and apply Stackdriver adapter manifest:

    ```bash
    helm template istio-telemetry/mixer-telemetry --execute=templates/stackdriver.yaml -f global.yaml --set mixer.adapters.stackdriver.enabled=true --namespace istio-system | kubectl apply -f -
    ```

The full Stackdriver adapter template can be found [here](https://github.com/istio/installer/blob/master/istio-telemetry/mixer-telemetry/templates/stackdriver.yaml) with several values to set:

```yaml
mixer:
  stackdriver:
    enabled: false

  auth:
    appCredentials: false
    apiKey: ""
    serviceAccountPath: ""

  tracer:
    enabled: false
    sampleProbability: 1
```


text:
namespace Microsoft.Azure.Management.Network
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// Extension methods for SubnetsOperations.
    /// </summary>
    public static partial class SubnetsOperationsExtensions
    {
            /// <summary>
            /// The delete subnet operation deletes the specified subnet.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            public static void Delete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
            {
                Task.Factory.StartNew(s => ((ISubnetsOperations)s).DeleteAsync(resourceGroupName, virtualNetworkName, subnetName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// The delete subnet operation deletes the specified subnet.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task DeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
            {
                await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// The delete subnet operation deletes the specified subnet.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            public static void BeginDelete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
            {
                Task.Factory.StartNew(s => ((ISubnetsOperations)s).BeginDeleteAsync(resourceGroupName, virtualNetworkName, subnetName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// The delete subnet operation deletes the specified subnet.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task BeginDeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
            {
                await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false);
            }

            /// <summary>
            /// The Get subnet operation retrieves information about the specified subnet.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='expand'>
            /// expand references resources.
            /// </param>
            public static Subnet Get(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string))
            {
                return Task.Factory.StartNew(s => ((ISubnetsOperations)s).GetAsync(resourceGroupName, virtualNetworkName, subnetName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// The Get subnet operation retrieves information about the specified subnet.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='expand'>
            /// expand references resources.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Subnet> GetAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, expand, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// The Put Subnet operation creates/updates a subnet in the specified virtual
            /// network
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='subnetParameters'>
            /// Parameters supplied to the create/update Subnet operation
            /// </param>
            public static Subnet CreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
            {
                return Task.Factory.StartNew(s => ((ISubnetsOperations)s).CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// The Put Subnet operation creates/updates a subnet in the specified virtual
            /// network
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='subnetParameters'>
            /// Parameters supplied to the create/update Subnet operation
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Subnet> CreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// The Put Subnet operation creates/updates a subnet in the specified virtual
            /// network
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='subnetParameters'>
            /// Parameters supplied to the create/update Subnet operation
            /// </param>
            public static Subnet BeginCreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
            {
                return Task.Factory.StartNew(s => ((ISubnetsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// The Put Subnet operation creates/updates a subnet in the specified virtual
            /// network
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='subnetName'>
            /// The name of the subnet.
            /// </param>
            /// <param name='subnetParameters'>
            /// Parameters supplied to the create/update Subnet operation
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Subnet> BeginCreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// The List subnets operation retrieves all the subnets in a virtual network.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            public static IPage<Subnet> List(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName)
            {
                return Task.Factory.StartNew(s => ((ISubnetsOperations)s).ListAsync(resourceGroupName, virtualNetworkName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// The List subnets operation retrieves all the subnets in a virtual network.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group.
            /// </param>
            /// <param name='virtualNetworkName'>
            /// The name of the virtual network.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<Subnet>> ListAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// The List subnets operation retrieves all the subnets in a virtual network.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static IPage<Subnet> ListNext(this ISubnetsOperations operations, string nextPageLink)
            {
                return Task.Factory.StartNew(s => ((ISubnetsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
            }

            /// <summary>
            /// The List subnets operation retrieves all the subnets in a virtual network.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<Subnet>> ListNextAsync(this ISubnetsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef SKUI_CSS_GRAMMAR_COLOR_STOP_H
#define SKUI_CSS_GRAMMAR_COLOR_STOP_H

#include "css/angle.h++"
#include "css/color_stop.h++"

#include "css/grammar/angle.h++"
#include "css/grammar/color.h++"
#include "css/grammar/length.h++"

#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/home/x3.hpp>

BOOST_FUSION_ADAPT_STRUCT(skui::css::color_stop<skui::css::length>,
                          color, stop)
BOOST_FUSION_ADAPT_STRUCT(skui::css::color_stop<skui::css::angle>,
                          color, stop)

namespace skui::css::grammar
{
  namespace x3 = boost::spirit::x3;

  const auto linear_color_stop = x3::rule<struct linear_color_stop_, css::linear_color_stop>{"linear-color-stop"}
                               = color >> (-length_percentage | x3::attr(std::optional<css::length>{}));

  const auto angular_color_stop = x3::rule<struct angular_color_stop_, css::angular_color_stop>{"angular-color-stop"}
                                = color >> (-angle | x3::attr(std::optional<css::angle>{}));
}

#endif


text:
package vos;

import org.codehaus.jackson.annotate.JsonProperty;

public class Zona{

	@JsonProperty(value="nombre")
	private String nombre;

	@JsonProperty(value="capacidad")
	private int capacidad;

	@JsonProperty(value="abierto")
	private int abierto;

	@JsonProperty(value="aptoDiscapacidad")
	private int aptoDiscapacidad;

	@JsonProperty(value="descripcionTecnica")
	private String descripcionTecnica;

	public Zona(@JsonProperty(value="nombre")String nombre,@JsonProperty(value="capacidad") int capacidad, @JsonProperty(value="abierto")int abierto,
			@JsonProperty(value="aptoDiscapacidad")int aptoDiscapacidad, @JsonProperty(value="descripcionTecnica")String descripcionTecnica) {
		super();
		this.nombre = nombre;
		this.capacidad = capacidad;
		this.abierto = abierto;
		this.aptoDiscapacidad = aptoDiscapacidad;
		this.descripcionTecnica = descripcionTecnica;
	}

	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

	public int getCapacidad() {
		return capacidad;
	}

	public void setCapacidad(int capacidad) {
		this.capacidad = capacidad;
	}

	public int getAbierto() {
		return abierto;
	}

	public void setAbierto(int abierto) {
		this.abierto = abierto;
	}

	public int getAptoDiscapacidad() {
		return aptoDiscapacidad;
	}

	public void setAptoDiscapacidad(int aptoDiscapacidad) {
		this.aptoDiscapacidad = aptoDiscapacidad;
	}

	public String getDescripcionTecnica() {
		return descripcionTecnica;
	}

	public void setDescripcionTecnica(String descripcionTecnica) {
		this.descripcionTecnica = descripcionTecnica;
	}

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Linn. Soc. London 28:66. 1872 ("1871")

#### Original name
null

### Remarks
null


text:
package edu.chalmers.dat255.group09.Alarmed.modules.mathModule.model.constants;

/**
 * An Enum representing different difficulty's in MathProblemTypes.
 *
 * @author Joakim Persson
 *
 */
public enum Difficulty {
	EASY, MEDIUM, HARD;
}


text:
/**
 * @file Manages asynchronous method response cache
 * @author Shinichi Tomita <shinichi.tomita@gmail.com>
 */

'use strict';

var events = require('events'),
    inherits = require('inherits'),
    _      = require('underscore')._;

/**
 * Class for managing cache entry
 *
 * @private
 * @class
 * @constructor
 * @template T
 */
var CacheEntry = function() {
  this.fetching = false;
};

inherits(CacheEntry, events.EventEmitter);

/**
 * Get value in the cache entry
 *
 * @param {Callback.<T>} [callback] - Callback function callbacked the cache entry updated
 * @returns {T|undefined}
 */
CacheEntry.prototype.get = function(callback) {
  if (!callback) {
    return this._value;
  } else {
    this.once('value', callback);
    if (!_.isUndefined(this._value)) {
      this.emit('value', this._value);
    }
  }
};

/**
 * Set value in the cache entry
 *
 * @param {T} [value] - A value for caching
 */
CacheEntry.prototype.set = function(value) {
  this._value = value;
  this.emit('value', this._value);
};

/**
 * Clear cached value
 */
CacheEntry.prototype.clear = function() {
  this.fetching = false;
  delete this._value;
};

/**
 * Caching manager for async methods
 *
 * @class
 * @constructor
 */
var Cache = function() {
  this._entries = {};
};

/**
 * retrive cache entry, or create if not exists.
 *
 * @param {String} [key] - Key of cache entry
 * @returns {CacheEntry}
 */
Cache.prototype.get = function(key) {
  if (key && this._entries[key]) {
    return this._entries[key];
  } else {
    var entry = new CacheEntry();
    this._entries[key] = entry;
    return entry;
  }
};

/**
 * clear cache entries prefix matching given key
 * @param {String} [key] - Key prefix of cache entry to clear
 */
Cache.prototype.clear = function(key) {
  for (var k in this._entries) {
    if (!key || k.indexOf(key) === 0) {
      this._entries[k].clear();
    }
  }
};

/**
 * create and return cache key from namespace and serialized arguments.
 * @private
 */
function createCacheKey(namespace, args) {
  args = Array.prototype.slice.apply(args);
  return namespace + '(' + _.map(args, function(a){ return JSON.stringify(a); }).join(',') + ')';
}

/**
 * Enable caching for async call fn to intercept the response and store it to cache.
 * The original async calll fn is always invoked.
 *
 * @protected
 * @param {Function} fn - Function to covert cacheable
 * @param {Object} [scope] - Scope of function call
 * @param {Object} [options] - Options
 * @return {Function} - Cached version of function
 */
Cache.prototype.makeResponseCacheable = function(fn, scope, options) {
  var cache = this;
  options = options || {};
  return function() {
    var args = Array.prototype.slice.apply(arguments);
    var callback = args.pop();
    if (!_.isFunction(callback)) {
      args.push(callback);
      callback = null;
    }
    var key = _.isString(options.key) ? options.key :
              _.isFunction(options.key) ? options.key.apply(scope, args) :
              createCacheKey(options.namespace, args);
    var entry = cache.get(key);
    entry.fetching = true;
    if (callback) {
      args.push(function(err, result) {
        entry.set({ error: err, result: result });
        callback(err, result);
      });
    }
    var ret, error;
    try {
      ret = fn.apply(scope || this, args);
    } catch(e) {
      error = e;
    }
    if (ret && _.isFunction(ret.then)) { // if the returned value is promise
      if (!callback) {
        return ret.then(function(result) {
          entry.set({ error: undefined, result: result });
          return result;
        }, function(err) {
          entry.set({ error: err, result: undefined });
          throw err;
        });
      } else {
        return ret;
      }
    } else {
      entry.set({ error: error, result: ret });
      if (error) { throw error; }
      return ret;
    }
  };
};

/**
 * Enable caching for async call fn to lookup the response cache first, then invoke original if no cached value.
 *
 * @protected
 * @param {Function} fn - Function to covert cacheable
 * @param {Object} [scope] - Scope of function call
 * @param {Object} [options] - Options
 * @return {Function} - Cached version of function
 */
Cache.prototype.makeCacheable = function(fn, scope, options) {
  var cache = this;
  options = options || {};
  var $fn = function() {
    var args = Array.prototype.slice.apply(arguments);
    var callback = args.pop();
    if (!_.isFunction(callback)) {
      args.push(callback);
    }
    var key = _.isString(options.key) ? options.key :
              _.isFunction(options.key) ? options.key.apply(scope, args) :
              createCacheKey(options.namespace, args);
    var entry = cache.get(key);
    if (!_.isFunction(callback)) { // if callback is not given in last arg, return cached result (immediate).
      var value = entry.get();
      if (!value) { throw new Error('Function call result is not cached yet.'); }
      if (value.error) { throw value.error; }
      return value.result;
    }
    entry.get(function(value) {
      callback(value.error, value.result);
    });
    if (!entry.fetching) { // only when no other client is calling function
      entry.fetching = true;
      args.push(function(err, result) {
        entry.set({ error: err, result: result });
      });
      fn.apply(scope || this, args);
    }
  };
  $fn.clear = function() {
    var key = _.isString(options.key) ? options.key :
              _.isFunction(options.key) ? options.key.apply(scope, arguments) :
              createCacheKey(options.namespace, arguments);
    cache.clear(key);
  };
  return $fn;
};

module.exports = Cache;


text:
'use strict';

angular.module('umm3601ursamajorApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('main', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainCtrl'
      });
  });


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bulletin Labor. Orto Bot. de R. Univ. Siena 5: 46 (1902)

#### Original name
Diplodina hyoscyami Vestergr.

### Remarks
null


text:
package org.codehaus.groovy.control;

import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.Verifier;

import java.math.BigDecimal;

/**
 * Visitor to resolve constants in annotation definitions.
 *
 * @author Paul King
 */
public class AnnotationConstantsVisitor extends ClassCodeVisitorSupport {
    private SourceUnit source;
    private boolean inAnnotationDef;

    public void visitClass(ClassNode node, SourceUnit source) {
        this.source = source;
        this.inAnnotationDef = node.isAnnotationDefinition();
        super.visitClass(node);
        this.inAnnotationDef = false;
    }

    @Override
    protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) {
        if (!inAnnotationDef) return;
        visitStatement(node.getFirstStatement(), node.getReturnType());
    }

    private void visitStatement(Statement statement, ClassNode returnType) {
        if (statement instanceof ReturnStatement) {
            // normal path
            ReturnStatement rs = (ReturnStatement) statement;
            rs.setExpression(transformConstantExpression(rs.getExpression(), returnType));
        } else if (statement instanceof ExpressionStatement) {
            // path for JavaStubGenerator
            ExpressionStatement es = (ExpressionStatement) statement;
            es.setExpression(transformConstantExpression(es.getExpression(), returnType));
        }
    }

    private Expression transformConstantExpression(Expression val, ClassNode returnType) {
        ClassNode returnWrapperType = ClassHelper.getWrapper(returnType);
        if (val instanceof ConstantExpression) {
            Expression result = revertType(val, returnWrapperType);
            if (result != null) {
                return result;
            }
            return val;
        }
        if (val instanceof CastExpression) {
            CastExpression castExp = (CastExpression) val;
            Expression castee = castExp.getExpression();
            if (castee instanceof ConstantExpression) {
                if (ClassHelper.getWrapper(castee.getType()).isDerivedFrom(returnWrapperType)) {
                    return castee;
                }
                Expression result = revertType(castee, returnWrapperType);
                if (result != null) {
                    return result;
                }
                return castee;
            }
        }
        return val;
    }

    private Expression revertType(Expression val, ClassNode returnWrapperType) {
        ConstantExpression ce = (ConstantExpression) val;
        if (ClassHelper.Character_TYPE.equals(returnWrapperType) && ClassHelper.STRING_TYPE.equals(val.getType())) {
            return configure(val, Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) val));
        }
        ClassNode valWrapperType = ClassHelper.getWrapper(val.getType());
        if (ClassHelper.Integer_TYPE.equals(valWrapperType)) {
            Integer i = (Integer) ce.getValue();
            if (ClassHelper.Character_TYPE.equals(returnWrapperType)) {
                return configure(val, new ConstantExpression((char) i.intValue(), true));
            }
            if (ClassHelper.Short_TYPE.equals(returnWrapperType)) {
                return configure(val, new ConstantExpression(i.shortValue(), true));
            }
            if (ClassHelper.Byte_TYPE.equals(returnWrapperType)) {
                return configure(val, new ConstantExpression(i.byteValue(), true));
            }
        }
        if (ClassHelper.BigDecimal_TYPE.equals(valWrapperType)) {
            BigDecimal bd = (BigDecimal) ce.getValue();
            if (ClassHelper.Float_TYPE.equals(returnWrapperType)) {
                return configure(val, new ConstantExpression(bd.floatValue(), true));
            }
            if (ClassHelper.Double_TYPE.equals(returnWrapperType)) {
                return configure(val, new ConstantExpression(bd.doubleValue(), true));
            }
        }
        return null;
    }

    private Expression configure(Expression orig, Expression result) {
        result.setSourcePosition(orig);
        return result;
    }

    protected SourceUnit getSourceUnit() {
        return source;
    }
}


text:
__author__ = 'stephen'
#===============================================================================
# GLOBAL IMPORTS:
import os, sys
import numpy as np
import time
import random
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.metrics.pairwise import pairwise_distances_argmin
from sklearn.utils.validation import check_is_fitted
from sklearn.metrics import pairwise_distances
# ==============================================
#===============================================================================
# LOCAL IMPORTS:
HK_DataMiner_Path = os.path.relpath(os.pardir)
sys.path.append(HK_DataMiner_Path)
#===============================================================================

def density_peaks_clustering(X, n_clusters=3, rho_cutoff=1.0, delta_cutoff=1.0, percent=0.1,
                     metric='eculidean', parallel=True):
    """Adaptive Partitioning by Local Density-peaks (density_peaks)
    We present an efficient density-based adaptive-resolution clustering method density_peaks
    for analyzing large-scale molecular dynamics (MD) trajectories. density_peaks performs the
    k-nearest-neighbors search to estimate the density of MD conformations in a local fashion,
    which can group MD conformations in the same high-density region into a cluster.
    density_peaks greatly improves the popular density peaks algorithm by reducing the running
    time and the memory usage by 2-3 orders of magnitude for systems ranging from alanine
    dipeptide to a 370-residue Maltose-binding protein.  In addition, we demonstrate that
    density_peaks can produce clusters with various sizes that are adaptive to the underlying density
    (i.e. larger clusters at low density regions, while smaller clusters at high density regions),
    which is a clear advantage over other popular clustering algorithms including k-centers and
    k-medoids. We anticipate that density_peaks can be widely applied to split ultra-large MD datasets
    containing millions of conformations for subsequent construction of Markov State Models.

    Parameters
    ----------
    X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \
        array of shape (n_samples, n_samples)
        A feature array, or array of distances between samples if
        ``metric='precomputed'``.

    rho_cutoff : float, optional
        The cut-off of the local density rho

    delta_cutoff : float, optional
        The cut-off of the distance delta from points of higher density
    percent : float, optional
        Average percentage of neighbours
    n_neighbors : int, optional
        The number of samples (or total weight) in a neighborhood for a point
        to be considered as a core point. This includes the point itself.
    metric : string, or callable
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string or callable, it must be one of
        the options allowed by metrics.pairwise.calculate_distance for its
        metric parameter.
        If metric is "precomputed", X is assumed to be a distance matrix and
        must be square.
    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
        The algorithm to be used by the NearestNeighbors module
        to compute pointwise distances and find nearest neighbors.

    Returns
    ----------
    cluster_centers_ : array, [n_clusters, n_features]
        Coordinates of cluster centers.
    labels_ :
        Labels of each point.

    Notes
    ----------
    NONE

    References
    ----------
    Song Liu, Lizhe Zhu and Xuhui Huang, "Adaptive Partitioning by Local
    ensity-peaks (density_peaks): An efficient density-based clustering algorithm
    for analyzing molecular dynamics trajectories". Journal of Computational
    Chemistry XX/XX/2016: Vol.XXX No. XXX pp. XXXX-XXXX
    DOI: XXXX

    Alex Rodriguez, Alessandro Laio, "Clustering by fast search and find
    of density_peakss". Science 27 June 2014: Vol. 344 no. 6191 pp. 1492-1496
    DOI: 10.1126/science.1242072
    """

    if rho_cutoff < 0.0:
        raise ValueError("rho must be non negative!")
    if delta_cutoff < 0.0 and not delta_cutoff == None:
        raise ValueError("delta must be non negative!")

    X_len = len(X)
    # Calculate distance and find dc
    distances_ = pairwise_distances(X, X, metric=metric, n_jobs=1)

    sorted_dist = np.sort(distances_)

    index = int(round(X_len * percent))
    dc = sorted_dist[index]

    # ----Cal rho: Gaussian kernel with neighbors
    # Calculating Rho using Gaussian kernel.

    rho = np.zeros(X_len, dtype=np.float32)
    dc_2 = dc ** 2

    for i in xrange(0, X_len-1):
        for j in xrange(i+1, X_len):
            dist = distances_[i, j]
            gaussian = np.math.exp(-(dist ** 2 / dc_2))
            rho[i] += gaussian
            rho[j] += gaussian

    # Calculating Highest Rho and Max Distance.
    rho_argsorted = np.argsort(rho)[::-1]
    max_rho = rho[rho_argsorted[0]]
    max_dist = np.max(distances_)

    if delta_cutoff == None:
        delta_cutoff = max_dist
    delta = [max_dist for i in xrange(X_len)]
    nneigh = [i for i in xrange(X_len)]

    # Calculating Delta.
    for i in xrange(0, X_len-1):
        for j in xrange(i, X_len):
            if rho[j] > rho[i]:
                delta[i] = distances_[i, j]
                nneigh[i] = j
                break

    # Clustering Data.
    # Initially, all samples are noise.

    ratio = delta * rho
    ratio_argsorted = np.argsort(ratio)[::-1]
    cut_index = ratio_argsorted[n_clusters-1]

    rho_cut = rho[cut_index]
    delta_cut = delta[cut_index]
    print "rho_cut:", rho_cut, cut_index
    print "delta_cut", delta_cut, cut_index

    labels_ = -np.ones(X_len, dtype=np.intp)
    cluster_centers_list = []
    cluster = 0

    for i in xrange(len(rho_argsorted)):
        index = rho_argsorted[i]
        if labels_[index] == -1 and delta[index] >= delta_cut and rho[index] > rho_cut:
            labels_[index] = cluster
            cluster_centers_list.append(index)
            cluster += 1
        else:
            if labels_[index] == -1 and labels_[nneigh[index]] != -1:
                labels_[index] = labels_[nneigh[index]]

    cluster_centers_ = cluster_centers_list
    return cluster_centers_, labels_

class density_peaks(BaseEstimator, ClusterMixin):
    """Adaptive Partitioning by Local Density-peaks (density_peaks)
    We present an efficient density-based adaptive-resolution clustering method density_peaks
    for analyzing large-scale molecular dynamics (MD) trajectories. density_peaks performs the
    k-nearest-neighbors search to estimate the density of MD conformations in a local fashion,
    which can group MD conformations in the same high-density region into a cluster.
    density_peaks greatly improves the popular density peaks algorithm by reducing the running
    time and the memory usage by 2-3 orders of magnitude for systems ranging from alanine
    dipeptide to a 370-residue Maltose-binding protein.  In addition, we demonstrate that
    density_peaks can produce clusters with various sizes that are adaptive to the underlying density
    (i.e. larger clusters at low density regions, while smaller clusters at high density regions),
    which is a clear advantage over other popular clustering algorithms including k-centers and
    k-medoids. We anticipate that density_peaks can be widely applied to split ultra-large MD datasets
    containing millions of conformations for subsequent construction of Markov State Models.

    Parameters
    ----------
    rho_cutoff : float, optional
       The cut-off of the local density rho

    delta_cutoff : float, optional
        The cut-off of the distance delta from points of higher density
    percent : float, optional
        Average percentage of neighbours
    n_neighbors : int, optional
        The number of samples (or total weight) in a neighborhood for a point
        to be considered as a core point. This includes the point itself.
    metric : string, or callable
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string or callable, it must be one of
        the options allowed by metrics.pairwise.calculate_distance for its
        metric parameter.
        If metric is "precomputed", X is assumed to be a distance matrix and
        must be square.
    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional
        The algorithm to be used by the NearestNeighbors module
        to compute pointwise distances and find nearest neighbors.

    Returns
    ----------
    cluster_centers_ : array, [n_clusters, n_features]
        Coordinates of cluster centers.
    labels_ :
        Labels of each point.

    Notes
    ----------
    NONE

    References
    ----------
    Song Liu, Lizhe Zhu and Xuhui Huang, "Adaptive Partitioning by Local
    ensity-peaks (density_peaks): An efficient density-based clustering algorithm
    for analyzing molecular dynamics trajectories". Journal of Computational
    Chemistry XX/XX/2016: Vol.XXX No. XXX pp. XXXX-XXXX
    DOI: XXXX

    Alex Rodriguez, Alessandro Laio, "Clustering by fast search and find
    of density_peakss". Science 27 June 2014: Vol. 344 no. 6191 pp. 1492-1496
    DOI: 10.1126/science.1242072
    """

    def __init__(self, n_clusters=3, rho_cutoff=1.0, delta_cutoff=1.0, percent=0.2,
                 metric='rmsd', parallel=True):
        self.rho_cutoff = rho_cutoff
        self.delta_cutoff = delta_cutoff
        self.percent = percent
        self.metric = metric
        self.parallel = parallel
        self.n_clusters = n_clusters

    def fit(self, X, weight=None):
        """Perform clustering.
        Parameters
        -----------
        X : array-like, shape=[n_samples, n_features]
            Samples to cluster.
        """
        #        X = check_array(X)
        print "Doing density_peaks clustering..."
        t0 = time.time()
        self.cluster_centers_, self.labels_ = \
            density_peaks_clustering(X, n_clusters=self.n_clusters, rho_cutoff=self.rho_cutoff, delta_cutoff=self.delta_cutoff,
                             percent=self.percent, metric=self.metric, parallel=self.parallel)
        t1 = time.time()
        print "density_peaks Time Cost:", t1 - t0
        return self

    def predict(self, X):
        """Predict the closest cluster each sample in X belongs to.
        Parameters
        ----------
        X : {array-like, sparse matrix}, shape=[n_samples, n_features]
            New data to predict.
        Returns
        -------
        labels : array, shape [n_samples,]
            Index of the cluster each sample belongs to.
        """
        check_is_fitted(self, "cluster_centers_")

        return pairwise_distances_argmin(X, self.cluster_centers_)


text:
/*
 * Implemented on LinkedList
 */
public class PriorityQueue {

	public class PriorityItem implements Comparable<PriorityItem>{
		int priority;
		Object o;

		public PriorityItem(int priority, Object o) {
			this.priority = priority;
			this.o = o;
		}

		@Override
		public int compareTo(PriorityItem item) {
			if(this.priority != item.priority) {
				return this.priority - item.priority;
			}
			if( o instanceof Number) {
				return(((Number)this.o).intValue() - ((Number)item.o).intValue());
			}
			return 0;
		}

	}
	private LinkedList l = new LinkedList();
	public PriorityQueue() {

	}

	public void push(PriorityItem o) {
		LinkedList.Node p = (LinkedList.Node)l.getFirstNode();
		if(p == null) {
			l.add(o);
			return;
		}
		while(((PriorityItem)p.value).compareTo(o) < 0 && p.next != null) {
			p = p.next;
		}
		l.addAfter(o,  p);
	}

	// remove from front of linked list
	public PriorityItem pop() {

		PriorityItem o = (PriorityItem)l.getFirst();
		l.remove(0);
		return o;
	}

}


text:
AndroidDownloader
=====

[English][13] | 中文

[![](https://jitpack.io/v/com.ixuea/AndroidDownloader.svg)](https://jitpack.io/#com.ixuea/AndroidDownloader)
![License](https://img.shields.io/github/license/ixuea/AndroidDownloader.svg)

[提交一个Issue][10], iOS和macOS平台使用[CocoaDownloader][12].

Android Downloader是一个开源的多线程,多任务下载框架。

更多功能和使用方法可以查看这个[APK][20].

下载
=======

你能从Github[releases page][40]下载jar包.

或者使用Gradle:

在根项目的build.gradle文件中添加仓库地址:

```
allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}
```

添加依赖:

```gradle
dependencies {
  compile 'com.ixuea:AndroidDownloader:latest'
}
```

如果要使用Snapshot版本, 请查看[Snapshots][50]wiki页面.

ProGuard
=======

如果你的项目使用了ProGuard,你需要添加下面的配置信息到项目的proguard-rules.pro文件中

```pro
-keep public class * implements com.ixuea.android.downloader.db.DownloadDBController
```

如果使用?
=======

更多的信息可以查看[GitHub wiki][200]和[Javadocs][201].

0.添加网络访问权限
-------

```xml
<uses-permission android:name="android.permission.INTERNET" />
```

1.配置下载服务
--------------------------------

```xml
<service android:name="com.ixuea.android.downloader.DownloadService">
  <intent-filter>
    <action android:name="com.ixuea.android.downloader.DOWNLOAD_SERVICE" />
  </intent-filter>
</service>
```

2.创建DownloadManager实例
-----------------------------------

```java
downloadManager = DownloadService.getDownloadManager(context.getApplicationContext());
```

3.下载一个文件
-----------------

```java
//create download info set download uri and save path.
final DownloadInfo downloadInfo = new DownloadInfo.Builder().setUrl("http://example.com/a.apk")
    .setPath("/sdcard/a.apk")
    .build();

//set download callback.
downloadInfo.setDownloadListener(new DownloadListener() {

  @Override
  public void onStart() {
    tv_download_info.setText("Prepare downloading");
  }

  @Override
  public void onWaited() {
    tv_download_info.setText("Waiting");
    bt_download_button.setText("Pause");
  }

  @Override
  public void onPaused() {
    bt_download_button.setText("Continue");
    tv_download_info.setText("Paused");
  }

  @Override
  public void onDownloading(long progress, long size) {
    tv_download_info
        .setText(FileUtil.formatFileSize(progress) + "/" + FileUtil
            .formatFileSize(size));
    bt_download_button.setText("Pause");
  }

  @Override
  public void onRemoved() {
    bt_download_button.setText("Download");
    tv_download_info.setText("");
    downloadInfo = null;
  }

  @Override
  public void onDownloadSuccess() {
    bt_download_button.setText("Delete");
    tv_download_info.setText("Download success");
  }

  @Override
  public void onDownloadFailed(DownloadException e) {
    e.printStackTrace();
    tv_download_info.setText("Download fail:" + e.getMessage());
  }
});

//submit download info to download manager.
downloadManager.download(downloadInfo);
```

更多信息请查看Demo.

兼容
=======

* **Android SDK**: 要求最新Android SDK为API 10.

实例代码
=======

可以看到该[Build][60]文档配置开发环境:

```gradle
./gradlew :samples:run
```

你也可以在releases界面找到Demo APK.

## 更多帮助信息

请查看Demo项目.

## 作者

Smile - @ixueadev on GitHub, Email is ixueadev@163.com, See more ixuea([http://www.ixuea.com][100])

Android开发交流群QQ群: 702321063.

[10]: https://github.com/ixuea/AndroidDownloader/issues/new
[12]: http://a.ixuea.com/8
[13]: https://github.com/ixuea/AndroidDownloader
[14]: https://github.com/ixuea/AndroidDownloader/blob/master/docs/zh.md
[20]: https://i.woblog.cn

[30]: https://raw.github.com/ixuea/AndroidDownloader/master/samples/art/download-a-file.png
[31]: https://raw.github.com/ixuea/AndroidDownloader/master/samples/art/use-in-list.png
[32]: https://raw.github.com/ixuea/AndroidDownloader/master/samples/art/download-manager-downloading.png
[33]: https://raw.github.com/ixuea/AndroidDownloader/master/samples/art/download-manager-downloaded.png

[40]: https://github.com/ixuea/AndroidDownloader/releases
[50]: https://github.com/ixuea/AndroidDownloader/releases
[60]: https://github.com/ixuea/AndroidDownloader#build

[100]: http://a.ixuea.com/3

[200]: https://github.com/ixuea/AndroidDownloader/wiki
[201]: http://i.woblog.cn/AndroidDownloader/javadocs/2.0.0/


text:
Tags: continuous deployment, разработка ПО, CI/CD, DevOps, системы сборки, gradle
PAA: ???
Labels:  gradle, kotlin

# Building projects (CI/CD), instruments

In some projects, the build script is playing the role of Cinderella. The team focuses its main effort on code development. And the build process itself could be handled by people who are far from development (for example, those responsible for operation or deployment). If the build script works somehow, then everyone prefers not to touch it, and no one ever is thinking about optimization. However, in large heterogeneous projects, the build process could be quite complex, and it is possible to approach it as an independent project.If you treat the build script as a secondary unimportant project, then the result will be an indigestible imperative script, the support of which will be rather difficult.

In this note we will take look at the criteria by which we chose the toolkit, and in [the next one](build-systems-2-gradle-howto-en.md) - how we use this toolkit.

[![CI/CD (opensource.com)](https://opensource.com/sites/default/files/uploads/devops_pipeline_pipe-2.png)](https://opensource.com/article/19/7/cicd-pipeline-rule-them-all)

<cut/>

## General model of project assembly

Project build model in all considered tools is a ([DAG](https://en.wikipedia.org/wiki/Directed_acyclic_graph)), and not a structural approach (when a procedure calls other procedures and then uses the results). This is due to the fact that during the development of the project, frequently minor changes are made and most no assembly operations required. That is, the organization of the project in the form of a digraph is the basis for performing only those actions which are necessary for the immediate task, thereby frequently used operations will execute promptly.

The nodes in the graph are either goals or tasks. Goals are the results to be achieved, and tasks are operations that need to be performed in order to achieve the current goal. A task can be executed only when all dependencies are satisfied.

Higher-level models are implemented on top of this basic model in some build tools.

## Tool selection

In the beginning of a project, it is sometimes possible to predict how complex the integration of the project will be. In our case, it turned out that it was required to build several node.js modules, several go-lang modules, and deploy multiple interconnected terraform modules. None of the subprojects were JVM-based.

Other similar projects that have been evolving "organically" build is performed using `make`. In `Makefile`s one could find `bash`, `perl`, `curl`, `php` and other dedicated utilities. Such build mechanism is error prone, difficult to maintain, and it has rather poor performance.

For a new integration project we decided to try to find an alternative build tool. The following options were considered:

- make,
- maven,
- sbt,
- gradle/groovy,
- gradle/kotlin.

### Make

This is a mature widespread program and allows implementing build scripts of large and complex projects.

Pros
- competence;
- similarity to shell script;

Cons
- only basic model of goals and tasks is supported; no notion of a project;
- cumbersome syntax;
- global states;
- no plugins support, it's difficult to reuse code;
- no way to describe the build in a declarative way, only imperative.

When there are no constraints, one may find in build scripts:
- code generation from templates using `perl`,
- automatic installation of executable files by downloading and executing `.sh` scripts from
  Internet on each build run,
- recursive call of make-files for subprojects with surprising target names,
- absence of consistent error handling.

These factors make maintenance more difficult and also make build process an unsafe operation.

### Maven

Maven revolutionized build systems when it was first introduced. Ideas of declarative descriptions of projects, wide use of conventions, code reuse via plugins, storing artifacts in repositories, the use of an identification system, including versions - all this provided recognition and widespread use in many JVM projects to this day.

Pros
- competence (part of the team has extensive experience working with Maven projects);
- developed model of projects and subprojects;
- plugin support;
- declarative model;
- maven wrapper.

Cons
- weak support for other technologies;
- the presence of difficult-to-overcome restrictions;
- the complexity of implementing plugins;
- lack of convenient implementation of imperative scripts;
- rigid lifecycle structure;
- not a very convenient XML format.

The lack of imperative scripts is both a plus and a minus. On the one hand, the declarative approach provides a strict separation of code and model, on the other hand, build tasks often require some small snippets of imperative logic, and solving such tasks in maven is painful.

### Sbt

Sbt is a tool for building Scala projects. Appeared around the same time as gradle.

Pros
- developed language;
- support for plugins and imperative snippets;
- incremental build support;
- support for continuous rebuilds as you change any file;
- parallel execution of independent tasks.

Cons
- unexpected model (instead of tasks — "settings");
- implicit dependencies via `. value`;
- weak support for other technologies (go, node.js);
- unexpected syntax.

Sbt looks more like a niche tool for building Scala project rather than a universal tool for any project.

### Gradle

Gradle appeared in 2007 as a response to the major limitations of Maven — the lack of imperative code, the difficulty of implementing plugins, and the inconvenience of performing non-standard operations. Gradle is based on the ideas proposed by Maven, develops them and changes the emphasis. The main parts of the gradle model are the following:
- task — operation performed, node of the dependency graph, name + description;
- project — logical unit of code organization, set and scope of tasks, plug-in connection point;
- plugin — a feature or feature that is added to the project. Among other things — a set of tasks;
- dependencies, up-to-date check.

An important improvement was the use of DSL (domain specific language). The DSL is based on an imperative language, but actually provides the declarative model. Imperative tasks are of course easily solved due to the underlying language.

Pros
- support for project model;
- support for a declarative (model-based) and imperative approach at the same time;
- incremental build support;
- unparalleled flexibility;
- excellent documentation (for two dialects at once);
- very fast operation (even task definitions are performed only when necessary);
- cross-platform — it works everywhere;
- gradle wrapper — a small script to download and run the correct version of gradle; developers do not need to manually configure the utilities and update when the version changes in the repository;
- user-friendly and intuitive DSL.

Cons
- lack of competence (gradle has not been widely used by team members before);
- as far as I know, there is no mechanism to protect against excessive use of imperative code. You need to be disciplined and follow the recommended practices when developing build scripts, and avoid writing spagetti code;
- there is no dependency mechanism other than JVM-based (maven-repository, ivy2);
- the need to put certain effort to ensure that each task supports an up-to-date check (useful for incremental builds). In particular, for each task, you need to describe the input and output data. Basically, the usual DAG capabilities are available effortlessly, but gradle allows you to achieve even higher speed of operations provided configuration for inputs and outputs.

#### Dialect selection — gradle/groovy or gradle/kotlin

Gradle was originally used with groovy-DSL. Later Kotlin-based DSL was developed.

Kotlin pros
- compiled strongly-typed language:
  - protection against errors at the compilation stage
  - support for intelli-sense,
  - safe refactoring,
- good DSL support;
- simple syntax, less boilerplate, compared to Java;
- quite a lot of sugar.

Cons
- most of the examples out there are for groovy. Initially it might be difficult to figure out, how to rewrite the example in kotlin;
- gradle/groovy DSL was implemented in the first place, so some elements are represented in kotlin imperfectly ('extra`, string task names,...);
- the entry barrier is slightly increased due to the need to learn a new language.

## Conclusion

Based on the results of comparison of the available project build tools, we decided to try to implement the build and CI/CD in our project using gradle/kotlin. This option has a number of advantages in comparison with the implementation of the project build based on make/shell.

### Gradle/kotlin vs make

Below are the comparative advantages of gradle/kotlin with respect to make:

Advantages:
- the highest speed of operation. The Gradle team puts continuous effort to improve the speed and implement features that facilitate the implementation of high-speed scripts. It is possible to ensure that all tasks, those that are not required for the execution will be skipped. And the tasks that need to be completed are executed only for the changed files.
- unification of the language. All tasks are solved within the framework of one strongly-typed compiled language with a consistent and well-thought-out syntax - Kotlin. There is no need to study the features of make modes, differences in shell interpreter versions, and options for processing command-line parameters in different utilities; separate programming languages for templates (php?, perl?). Due to the use of a modern language with static typing, many classes of errors pertinent to scripting languages are eliminated altogether.
- declarative model of projects/subprojects and plugins on top of a declarative digraph of tasks. In make there are only imperative tasks.
- the ability to combine a declarative and imperative approach. Despite the fact that the declarative approach provides clarity and purity of code, ease of support, ability to combine components, imperative approach can be indispensable because of its flexibility. One can create new tasks initially in an imperative way (ad-hoc), and then generalize and abstract away in the form of declarative configurable plugins.
- ability to create reusable plugins. Writing such plugins does is not very difficult, there is a convenient API with extensive features for writing plugins. In the case of make, there is no standard mechanism, which causes code duplication and the re-invention of bicycles.
- a JVM platform on which there exists plenty of platform-independent libraries for all needs.  In make, some tasks require the installation of platform-specific applications.

Disadvantages:
- it is inconvenient to call shell commands. For each command, you have to create and configure a task. Though it might not be needed much.
- higher requirements for engineering culture - language with static type system, declarative  project model, using advanced concepts (properties, dependency inference, up-to-date checks).

In the next part, we'll look at some of the features of using gradle/kotlin to build non-JVM projects.

### Acknowledgements

I would like to thank @nolequen, @Starcounter, @tovarischzhukov for constructive criticism of the draft article.


text:
namespace armnn
{

class IMemoryManager
{
protected:
    IMemoryManager() {}

public:
    virtual void Acquire() = 0;
    virtual void Release() = 0;

    virtual ~IMemoryManager() {}
};

using IMemoryManagerUniquePtr = std::unique_ptr<IMemoryManager>;

} // namespace armnn


text:
package com.jie.book.work.view;

import java.util.LinkedList;
import java.util.Queue;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;

@SuppressLint("DrawAllocation")
public class HorizontalListView extends AdapterView<ListAdapter> {

	public boolean mAlwaysOverrideTouch = true;
	protected ListAdapter mAdapter;
	private int mLeftViewIndex = -1;
	private int mRightViewIndex = 0;
	protected int mCurrentX;
	protected int mNextX;
	private int mMaxX = Integer.MAX_VALUE;
	private int mDisplayOffset = 0;
	protected Scroller mScroller;
	private GestureDetector mGesture;
	private Queue<View> mRemovedViewQueue = new LinkedList<View>();
	private OnItemSelectedListener mOnItemSelected;
	private OnItemClickListener mOnItemClicked;
	private boolean mDataChanged = false;

	public HorizontalListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView();
	}

	public HorizontalListView(Context context) {
		super(context);
		initView();
	}

	public HorizontalListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView();
	}

	private synchronized void initView() {
		mLeftViewIndex = -1;
		mRightViewIndex = 0;
		mDisplayOffset = 0;
		mCurrentX = 0;
		mNextX = 0;
		mMaxX = Integer.MAX_VALUE;
		mScroller = new Scroller(getContext());
		mGesture = new GestureDetector(getContext(), mOnGesture);
	}

	@Override
	public void setOnItemSelectedListener(OnItemSelectedListener listener) {
		mOnItemSelected = listener;
	}

	@Override
	public void setOnItemClickListener(OnItemClickListener listener) {
		mOnItemClicked = listener;
	}

	private DataSetObserver mDataObserver = new DataSetObserver() {

		@Override
		public void onChanged() {
			synchronized (HorizontalListView.this) {
				mDataChanged = true;
			}
			invalidate();
			requestLayout();
		}

		@Override
		public void onInvalidated() {
			reset();
			invalidate();
			requestLayout();
		}

	};

	@Override
	public ListAdapter getAdapter() {
		return mAdapter;
	}

	@Override
	public View getSelectedView() {
		// TODO: implement
		return null;
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		if (mAdapter != null) {
			mAdapter.unregisterDataSetObserver(mDataObserver);
		}
		mAdapter = adapter;
		mAdapter.registerDataSetObserver(mDataObserver);
		reset();
	}

	private synchronized void reset() {
		initView();
		removeAllViewsInLayout();
		requestLayout();
	}

	@Override
	public void setSelection(int position) {
		// TODO: implement
	}

	@SuppressWarnings("deprecation")
	private void addAndMeasureChild(final View child, int viewPos) {
		LayoutParams params = child.getLayoutParams();
		if (params == null) {
			params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		}

		addViewInLayout(child, viewPos, params, true);
		child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
				MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
	}

	@Override
	protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) {
		super.onLayout(changed, left, top, right, bottom);

		if (mAdapter == null) {
			return;
		}

		if (mDataChanged) {
			int oldCurrentX = mCurrentX;
			initView();
			removeAllViewsInLayout();
			mNextX = oldCurrentX;
			mDataChanged = false;
		}

		if (mScroller.computeScrollOffset()) {
			int scrollx = mScroller.getCurrX();
			mNextX = scrollx;
		}

		if (mNextX <= 0) {
			mNextX = 0;
			mScroller.forceFinished(true);
		}
		if (mNextX >= mMaxX) {
			mNextX = mMaxX;
			mScroller.forceFinished(true);
		}

		int dx = mCurrentX - mNextX;

		removeNonVisibleItems(dx);
		fillList(dx);
		positionItems(dx);

		mCurrentX = mNextX;

		if (!mScroller.isFinished()) {
			post(new Runnable() {
				@Override
				public void run() {
					requestLayout();
				}
			});

		}
	}

	private void fillList(final int dx) {
		int edge = 0;
		View child = getChildAt(getChildCount() - 1);
		if (child != null) {
			edge = child.getRight();
		}
		fillListRight(edge, dx);

		edge = 0;
		child = getChildAt(0);
		if (child != null) {
			edge = child.getLeft();
		}
		fillListLeft(edge, dx);

	}

	private void fillListRight(int rightEdge, final int dx) {
		while (rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount()) {

			View child = mAdapter.getView(mRightViewIndex, mRemovedViewQueue.poll(), this);
			addAndMeasureChild(child, -1);
			rightEdge += child.getMeasuredWidth();

			if (mRightViewIndex == mAdapter.getCount() - 1) {
				mMaxX = mCurrentX + rightEdge - getWidth();
			}

			if (mMaxX < 0) {
				mMaxX = 0;
			}
			mRightViewIndex++;
		}

	}

	private void fillListLeft(int leftEdge, final int dx) {
		while (leftEdge + dx > 0 && mLeftViewIndex >= 0) {
			View child = mAdapter.getView(mLeftViewIndex, mRemovedViewQueue.poll(), this);
			addAndMeasureChild(child, 0);
			leftEdge -= child.getMeasuredWidth();
			mLeftViewIndex--;
			mDisplayOffset -= child.getMeasuredWidth();
		}
	}

	private void removeNonVisibleItems(final int dx) {
		View child = getChildAt(0);
		while (child != null && child.getRight() + dx <= 0) {
			mDisplayOffset += child.getMeasuredWidth();
			mRemovedViewQueue.offer(child);
			removeViewInLayout(child);
			mLeftViewIndex++;
			child = getChildAt(0);

		}

		child = getChildAt(getChildCount() - 1);
		while (child != null && child.getLeft() + dx >= getWidth()) {
			mRemovedViewQueue.offer(child);
			removeViewInLayout(child);
			mRightViewIndex--;
			child = getChildAt(getChildCount() - 1);
		}
	}

	private void positionItems(final int dx) {
		if (getChildCount() > 0) {
			mDisplayOffset += dx;
			int left = mDisplayOffset;
			for (int i = 0; i < getChildCount(); i++) {
				View child = getChildAt(i);
				int childWidth = child.getMeasuredWidth();
				child.layout(left, 0, left + childWidth, child.getMeasuredHeight());
				left += childWidth;
			}
		}
	}

	public synchronized void scrollTo(int x) {
		mScroller.startScroll(mNextX, 0, x - mNextX, 0);
		requestLayout();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN || ev.getAction() == MotionEvent.ACTION_MOVE) {
			// 通知父组建不要拦截本子组建事件
			if (getParent() != null) {
				getParent().requestDisallowInterceptTouchEvent(true);
			}
		} else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
			// 通知父组建拦截子组建事件
			if (getParent() != null) {
				getParent().requestDisallowInterceptTouchEvent(false);
			}
		}
		return mGesture.onTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
			// 通知父组建不要拦截本子组建事件
			if (getParent() != null) {
				getParent().requestDisallowInterceptTouchEvent(true);
			}
		} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
			// 通知父组建拦截子组建事件
			if (getParent() != null) {
				getParent().requestDisallowInterceptTouchEvent(false);
			}
		}
		return mGesture.onTouchEvent(event);
	}

	protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		synchronized (HorizontalListView.this) {
			mScroller.fling(mNextX, 0, (int) -velocityX, 0, 0, mMaxX, 0, 0);
		}
		requestLayout();

		return true;
	}

	protected boolean onDown(MotionEvent e) {
		mScroller.forceFinished(true);
		return true;
	}

	private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {

		@Override
		public boolean onDown(MotionEvent e) {
			return HorizontalListView.this.onDown(e);
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			return HorizontalListView.this.onFling(e1, e2, velocityX, velocityY);
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
			synchronized (HorizontalListView.this) {
				mNextX += (int) distanceX;
			}
			requestLayout();

			return true;
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			Rect viewRect = new Rect();
			for (int i = 0; i < getChildCount(); i++) {
				View child = getChildAt(i);
				int left = child.getLeft();
				int right = child.getRight();
				int top = child.getTop();
				int bottom = child.getBottom();
				viewRect.set(left, top, right, bottom);
				if (viewRect.contains((int) e.getX(), (int) e.getY())) {
					if (mOnItemClicked != null) {
						mOnItemClicked.onItemClick(HorizontalListView.this, child, mLeftViewIndex + 1 + i,
								mAdapter.getItemId(mLeftViewIndex + 1 + i));
					}
					if (mOnItemSelected != null) {
						mOnItemSelected.onItemSelected(HorizontalListView.this, child, mLeftViewIndex + 1 + i,
								mAdapter.getItemId(mLeftViewIndex + 1 + i));
					}
					break;
				}

			}
			return true;
		}

	};
}


text:
$(function(){
	$('#container').prepend('

');
	$('#reglement a').click(function(){
		showpopin($(this));
		return false;
	});

});

function showpopin(link){
	$('#popin').load(link.attr('href')+' #terms',function(){
		$('#popin #terms').addClass('scroll-pane');

		$('.fb-target a').each(function() {
			$(this).attr('target', '_blank');
		});

		$('#overlay').fadeIn();
		$('#wrap-popin').fadeIn();
		//$('.scroll-pane').jScrollPane();
		$('.scroll-pane').each(function(){
			$(this).jScrollPane({
				showArrows: $(this).is('.arrow')
			});
			var api = $(this).data('jsp');
			var throttleTimeout;
			$(window).bind('resize', function(){
				if ($.browser.msie) {
					// IE fires multiple resize events while you are dragging the browser window which
					// causes it to crash if you try to update the scrollpane on every one. So we need
					// to throttle it to fire a maximum of once every 50 milliseconds...
					if (!throttleTimeout) {
						throttleTimeout = setTimeout(function(){
							api.reinitialise();
							throttleTimeout = null;
						}, 50);
					}
				} else {
					api.reinitialise();
				}
			});
		})
	});

	$('#close, #overlay').click(function(){
		$('#wrap-popin').fadeOut();
		$('#overlay').fadeOut();
	})
}


text:
FLOAT_PRECISION = 4

import re, types
import sys
typeRE = re.compile("<type '(.*)'>")
classRE = re.compile("<class '(.*)'>")

import inspect

is_python3 = (sys.version_info[0] == 3)
if is_python3:
  long = None # Avoid NameError when evaluating "long"

def is_class(dat):
  """Return whether dat is a class."""
  if is_python3:
    return isinstance(dat, type)
  else:
    return type(dat) in (types.ClassType, types.TypeType)

def is_instance(dat):
  """Return whether dat is an instance of a class."""
  if is_python3:
    return isinstance(type(dat), type) and not isinstance(dat, type)
  else:
    # ugh, classRE match is a bit of a hack :(
    return type(dat) == types.InstanceType or classRE.match(str(type(dat)))

def get_name(obj):
  """Return the name of an object."""
  return obj.__name__ if hasattr(obj, '__name__') else get_name(type(obj))

# Note that this might BLOAT MEMORY CONSUMPTION since we're holding on
# to every reference ever created by the program without ever releasing
# anything!
class ObjectEncoder:
  def __init__(self):
    # Key: canonicalized small ID
    # Value: encoded (compound) heap object
    self.encoded_heap_objects = {}

    self.id_to_small_IDs = {}
    self.cur_small_ID = 1

  def get_heap(self):
    return self.encoded_heap_objects

  def reset_heap(self):
    # VERY IMPORTANT to reassign to an empty dict rather than just
    # clearing the existing dict, since get_heap() could have been
    # called earlier to return a reference to a previous heap state
    self.encoded_heap_objects = {}

  def set_function_parent_frame_ID(self, ref_obj, enclosing_frame_id):
    assert ref_obj[0] == 'REF'
    func_obj = self.encoded_heap_objects[ref_obj[1]]
    assert func_obj[0] == 'FUNCTION'
    func_obj[-1] = enclosing_frame_id

  # return either a primitive object or an object reference;
  # and as a side effect, update encoded_heap_objects
  def encode(self, dat, get_parent):
    """Encode a data value DAT using the GET_PARENT function for parent ids."""
    # primitive type
    if type(dat) in (int, long, float, str, bool, type(None)):
      if type(dat) is float:
        return round(dat, FLOAT_PRECISION)
      else:
        return dat

    # compound type - return an object reference and update encoded_heap_objects
    else:
      my_id = id(dat)

      try:
        my_small_id = self.id_to_small_IDs[my_id]
      except KeyError:
        my_small_id = self.cur_small_ID
        self.id_to_small_IDs[my_id] = self.cur_small_ID
        self.cur_small_ID += 1

      del my_id # to prevent bugs later in this function

      ret = ['REF', my_small_id]

      # punt early if you've already encoded this object
      if my_small_id in self.encoded_heap_objects:
        return ret

      # major side-effect!
      new_obj = []
      self.encoded_heap_objects[my_small_id] = new_obj

      typ = type(dat)

      if typ == list:
        new_obj.append('LIST')
        for e in dat:
          new_obj.append(self.encode(e, get_parent))
      elif typ == tuple:
        new_obj.append('TUPLE')
        for e in dat:
          new_obj.append(self.encode(e, get_parent))
      elif typ == set:
        new_obj.append('SET')
        for e in dat:
          new_obj.append(self.encode(e, get_parent))
      elif typ == dict:
        new_obj.append('DICT')
        for (k, v) in dat.items():
          # don't display some built-in locals ...
          if k not in ('__module__', '__return__', '__locals__'):
            new_obj.append([self.encode(k, get_parent), self.encode(v, get_parent)])
      elif typ in (types.FunctionType, types.MethodType):
        if is_python3:
          argspec = inspect.getfullargspec(dat)
        else:
          argspec = inspect.getargspec(dat)

        printed_args = [e for e in argspec.args]
        if argspec.varargs:
          printed_args.append('*' + argspec.varargs)

        if is_python3:
          if argspec.varkw:
            printed_args.append('**' + argspec.varkw)
          if argspec.kwonlyargs:
            printed_args.extend(argspec.kwonlyargs)
        else:
          if argspec.keywords:
            printed_args.append('**' + argspec.keywords)

        func_name = get_name(dat)
        pretty_name = func_name + '(' + ', '.join(printed_args) + ')'
        encoded_val = ['FUNCTION', pretty_name, None]
        if get_parent:
          enclosing_frame_id = get_parent(dat)
          encoded_val[2] = enclosing_frame_id
        new_obj.extend(encoded_val)
      elif typ is types.BuiltinFunctionType:
        pretty_name = get_name(dat) + '(...)'
        new_obj.extend(['FUNCTION', pretty_name, None])
      elif is_class(dat) or is_instance(dat):
        self.encode_class_or_instance(dat, new_obj)
      elif typ is types.ModuleType:
        new_obj.extend(['module', dat.__name__])
      else:
        typeStr = str(typ)
        m = typeRE.match(typeStr)

        if not m:
          m = classRE.match(typeStr)

        assert m, typ
        new_obj.extend([m.group(1), str(dat)])

      return ret

  def encode_class_or_instance(self, dat, new_obj):
    """Encode dat as a class or instance."""
    if is_instance(dat):
      if hasattr(dat, '__class__'):
        # common case ...
        class_name = get_name(dat.__class__)
      else:
        # super special case for something like
        # "from datetime import datetime_CAPI" in Python 3.2,
        # which is some weird 'PyCapsule' type ...
        # http://docs.python.org/release/3.1.5/c-api/capsule.html
        class_name = get_name(type(dat))

      new_obj.extend(['INSTANCE', class_name])
      # don't traverse inside modules, or else risk EXPLODING the visualization
      if class_name == 'module':
        return
    else:
      superclass_names = [e.__name__ for e in dat.__bases__ if e is not object]
      new_obj.extend(['CLASS', get_name(dat), superclass_names])

    # traverse inside of its __dict__ to grab attributes
    # (filter out useless-seeming ones):
    hidden = ('__doc__', '__module__', '__return__', '__dict__',
        '__locals__', '__weakref__')
    if hasattr(dat, '__dict__'):
      user_attrs = sorted([e for e in dat.__dict__ if e not in hidden])
    else:
      user_attrs = []

    for attr in user_attrs:
      new_obj.append([self.encode(attr, None), self.encode(dat.__dict__[attr], None)])


text:
layout: page
title: "CHEN 4803: Metabolic Engineering Statistics"
comments: true
description: "blanks"
keywords: "CHEN,4803,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 4.7%

**Percent incomplete**: 2.78%

**Average grade** (4.0 scale): 3.22

**Standard deviation in grades** (4.0 scale): 0.15

**Average workload** (raw): 2.18

**Standard deviation in workload** (raw): 0.19

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 4.9

**Standard deviation in course rating** (6 point scale): 0.55

**Average instructor rating** (6 point scale): 5.14

**Standard deviation in instructor rating** (6 point scale): 0.65

**Instructors**: Nanette Regina Boyle, Anushree Chatterjee, Ryan Gill

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2012, Spring 2015, Fall 2016

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 3

**Department**: CHEN

**College**: College of Engineering and Applied Science

**Level**: Upper

**Activity**: LEC - Lecture


text:
ES5Harness.registerTest({
    id: "15.2.3.7-5-b-183",

    path: "TestCases/chapter15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-183.js",

    description: "Object.defineProperties - value of 'writable' property of 'descObj' is RegExp object (8.10.5 step 6.b)",

    test: function testcase() {
        var obj = {};

        Object.defineProperties(obj, {
            property: {
                writable: new RegExp()
            }
        });

        obj.property = "isWritable";

        return obj.property === "isWritable";
    },

    precondition: function prereq() {
        return fnExists(Object.defineProperties);
    }
});


text:
#if !NOSOCKET
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NBitcoin.Protocol
{
	public class NodeEventArgs : EventArgs
	{
		public NodeEventArgs(Node node, bool added)
		{
			_Added = added;
			_Node = node;
		}

		private readonly bool _Added;
		public bool Added
		{
			get
			{
				return _Added;
			}
		}
		private readonly Node _Node;
		public Node Node
		{
			get
			{
				return _Node;
			}
		}
	}
	public class NodesCollection : IEnumerable<Node>
	{
		class Bridge : MessageListener<IncomingMessage>
		{
			MessageProducer<IncomingMessage> _Prod;
			public Bridge(MessageProducer<IncomingMessage> prod)
			{
				_Prod = prod;
			}
			#region MessageListener<IncomingMessage> Members

			public void PushMessage(IncomingMessage message)
			{
				_Prod.PushMessage(message);
			}

			#endregion
		}
		Bridge bridge;
		public NodesCollection()
		{
			bridge = new Bridge(_MessageProducer);
		}

		MessageProducer<IncomingMessage> _MessageProducer = new MessageProducer<IncomingMessage>();
		public MessageProducer<IncomingMessage> MessageProducer
		{
			get
			{
				return _MessageProducer;
			}
		}

		ConcurrentDictionary<Node, Node> _Nodes = new ConcurrentDictionary<Node, Node>();

		public int Count
		{
			get
			{
				return _Nodes.Count;
			}
		}
		public bool Add(Node node)
		{
			if(node == null)
				throw new ArgumentNullException("node");
			if(_Nodes.TryAdd(node, node))
			{
				node.MessageProducer.AddMessageListener(bridge);
				OnNodeAdded(node);
				return true;
			}
			return false;
		}

		public void Remove(Node node)
		{
			Node old;
			if(_Nodes.TryRemove(node, out old))
			{
				node.MessageProducer.RemoveMessageListener(bridge);
				OnNodeRemoved(old);
			}
		}

		public event EventHandler<NodeEventArgs> Added;
		public event EventHandler<NodeEventArgs> Removed;

		private void OnNodeAdded(Node node)
		{
			var added = Added;
			if(added != null)
				added(this, new NodeEventArgs(node, true));
		}

		public void OnNodeRemoved(Node node)
		{
			var removed = Removed;
			if(removed != null)
				removed(this, new NodeEventArgs(node, false));
		}

		public Node FindLocal()
		{
			return FindByIp(IPAddress.Loopback);
		}

		public Node FindByIp(IPAddress ip)
		{
			ip = ip.EnsureIPv6();
			return _Nodes.Where(n => Match(ip, null, n.Key)).Select(s => s.Key).FirstOrDefault();
		}

		public Node FindByEndpoint(IPEndPoint endpoint)
		{
			var ip = endpoint.Address.EnsureIPv6();
			int port = endpoint.Port;
			return _Nodes.Select(n => n.Key).FirstOrDefault(n => Match(ip, port, n));
		}

		private static bool Match(IPAddress ip, int? port, Node n)
		{
			if(port.HasValue)
			{
				return (n.State > NodeState.Disconnecting && n.RemoteSocketAddress.Equals(ip) && n.RemoteSocketPort == port.Value) ||
						(n.PeerVersion.AddressFrom.Address.Equals(ip) && n.PeerVersion.AddressFrom.Port == port.Value);
			}
			else
			{
				return (n.State > NodeState.Disconnecting && n.RemoteSocketAddress.Equals(ip)) ||
						n.PeerVersion.AddressFrom.Address.Equals(ip);
			}
		}

		#region IEnumerable<Node> Members

		public IEnumerator<Node> GetEnumerator()
		{
			return _Nodes.Select(n => n.Key).AsEnumerable().GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		#endregion

		public void DisconnectAll(CancellationToken cancellation = default(CancellationToken))
		{
			foreach(var node in _Nodes)
				node.Key.DisconnectAsync();
		}

		public void Clear()
		{
			_Nodes.Clear();
		}
	}
}
#endif


text:
import getpass
import urllib2

import datetime
import argparse
import json

import datetime

import sys

try:
    import dev_appserver
    dev_appserver.fix_sys_path()
    sys.path.insert(1, 'lib')
except ImportError:
    print('Please make sure the App Engine SDK is in your PYTHONPATH.')
    raise

from google.appengine.ext import ndb
from google.appengine.ext.remote_api import remote_api_stub

from models.award import Award
from models.district import District
from models.event import Event
from models.event_team import EventTeam
from models.event_details import EventDetails
from models.match import Match
from models.team import Team

from helpers.award_manipulator import AwardManipulator
from helpers.event_manipulator import EventManipulator
from helpers.event_team_manipulator import EventTeamManipulator
from helpers.event_details_manipulator import EventDetailsManipulator
from helpers.district_manipulator import DistrictManipulator
from helpers.team_manipulator import TeamManipulator
from helpers.match_manipulator import MatchManipulator

EVENT_DATE_FORMAT_STR = '%Y-%m-%d'
BASE_URL = 'https://www.thebluealliance.com/api/v3/{}'
APP_HEADER = 'X-TBA-Auth-Key'
AUTH_TOKEN = ''

def store_district(data):
    district = District(id=data['key'])
    district.year = data['year']
    district.abbreviation = data['abbreviation']
    district.display_name = data['display_name']

    return DistrictManipulator.createOrUpdate(district)

def store_event(data):
    event = Event(id=data['key'])
    event.name = data['name']
    event.short_name = data['short_name']
    event.event_short = data['event_code']
    event.event_type_enum = data['event_type']
    event.year = data['year']
    event.timezone_id = data['timezone']
    event.website = data['website']
    event.start_date = datetime.datetime.strptime(data['start_date'], EVENT_DATE_FORMAT_STR) if data['start_date'] else None
    event.end_date = datetime.datetime.strptime(data['end_date'], EVENT_DATE_FORMAT_STR) if data['end_date'] else None
    event.webcast_json = json.dumps(data['webcasts'])
    event.venue = data['location_name']
    event.city = data['city']
    event.state_prov = data['state_prov']
    event.country = data['country']
    event.playoff_type = data['playoff_type']
    event.parent_event = ndb.Key(Event, data['parent_event_key']) if data['parent_event_key'] else None
    event.divisions = [ndb.Key(Event, div_key) for div_key in data['division_keys']] if data['division_keys'] else []

    district = store_district(data['district']) if data['district'] else None
    event.district_key = district.key if district else None

    return EventManipulator.createOrUpdate(event)

def store_team(data):
    team = Team(id=data['key'])
    team.team_number = data['team_number']
    team.nickname = data['nickname']
    team.name = data['name']
    team.website = data['website']
    team.rookie_year = data['rookie_year']
    team.motto = data['motto']
    team.city = data['city']
    team.state_prov = data['state_prov']
    team.country = data['country']
    team.school_name = data['school_name']

    TeamManipulator.createOrUpdate(team)
    return team

def store_match(data):
    match = Match(id=data['key'])
    match.event = ndb.Key(Event, data['event_key'])
    match.year = int(data['key'][:4])
    match.comp_level = data['comp_level']
    match.set_number = data['set_number']
    match.match_number = data['match_number']
    if data.get('time'):
        match.time = datetime.datetime.fromtimestamp(int(data['time']))

    if data.get('actual_time'):
        match.actual_time = datetime.datetime.fromtimestamp(int(data['actual_time']))

    if data.get('predicted_time'):
        match.predicted_time = datetime.datetime.fromtimestamp(int(data['predicted_time']))

    if data.get('post_result_time'):
        match.post_result_time = datetime.datetime.fromtimestamp(int(data['post_result_time']))
    match.score_breakdown_json = json.dumps(data['score_breakdown'])

    team_key_names = []
    for alliance in ['red', 'blue']:
        team_key_names += data['alliances'][alliance]['team_keys']
        data['alliances'][alliance]['teams'] = data['alliances'][alliance].pop('team_keys')
        data['alliances'][alliance]['surrogates'] = data['alliances'][alliance].pop('surrogate_team_keys')
        data['alliances'][alliance]['dqs'] = data['alliances'][alliance].pop('dq_team_keys')
    match.alliances_json = json.dumps(data['alliances'])
    match.team_key_names = team_key_names

    youtube_videos = []
    for video in data['videos']:
        if video['type'] == 'youtube':
            youtube_videos.append(video['key'])
    match.youtube_videos = youtube_videos

    return MatchManipulator.createOrUpdate(match)

def store_eventteam(team, event):
    eventteam = EventTeam(id="{}_{}".format(event.key_name, team.key_name))
    eventteam.event = event.key
    eventteam.team = team.key
    eventteam.year = event.year

    return EventTeamManipulator.createOrUpdate(eventteam)

def store_eventdetail(event, type, data):
    detail = EventDetails(id=event.key_name)
    setattr(detail, type, data)

    return EventDetailsManipulator.createOrUpdate(detail)

def store_award(data, event):
    award = Award(id=Award.render_key_name(data['event_key'], data['award_type']))
    award.event = ndb.Key(Event, data['event_key'])
    award.award_type_enum = data['award_type']
    award.year = data['year']
    award.name_str = data['name']
    award.event_type_enum = event.event_type_enum

    recipient_list_fixed = []
    team_keys = []
    for recipient in data['recipient_list']:
        if recipient['team_key']:
            team_keys.append(ndb.Key(Team, recipient['team_key']))
        recipient_list_fixed.append(json.dumps({
            'awardee': recipient['awardee'],
            'team_number': recipient['team_key'][3:] if recipient['team_key'] else None,
        }))
    award.recipient_json_list = recipient_list_fixed
    return AwardManipulator.createOrUpdate(award)

def fetch_endpoint(endpoint):
    full_url = BASE_URL.format(endpoint)
    print "Fetching {}".format(full_url)
    url = urllib2.Request(full_url, headers={APP_HEADER: AUTH_TOKEN, 'User-agent': 'Mozilla/5.0'})
    response = urllib2.urlopen(url)
    return json.loads(response.read())

def fetch_team(team_key):
    return fetch_endpoint("team/{}".format(team_key))

def fetch_event(event_key):
    return fetch_endpoint("event/{}".format(event_key))

def fetch_match(match_key):
    return fetch_endpoint("match/{}".format(match_key))

def fetch_event_detail(event_key, detail):
    return fetch_endpoint("event/{}/{}".format(event_key, detail))

def local_auth_func():
    # Credentials don't matter on the local devserver
    return 'user', 'pass'

def update_event(key):
    event_data = fetch_event(key)
    event = store_event(event_data)

    event_teams = fetch_event_detail(key, 'teams')
    teams = map(store_team, event_teams)
    map(lambda t: store_eventteam(t, event), teams)

    event_matches = fetch_event_detail(key, 'matches')
    map(store_match, event_matches)

    event_rankings = fetch_event_detail(key, 'rankings')
    store_eventdetail(event, 'rankings2', event_rankings['rankings'] if event_rankings else [])

    event_alliances = fetch_event_detail(key, 'alliances')
    store_eventdetail(event, 'alliance_selections', event_alliances)

    event_awards = fetch_event_detail(key, 'awards')
    map(lambda t: store_award(t, event), event_awards)

def main(key, url):
    print "Configuring GAE Remote API on {} to import {}".format(url, key)
    if 'localhost' in url:
        remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api', local_auth_func, url)
    else:
        remote_api_stub.ConfigureRemoteApiForOAuth(url, '/_ah/remote_api')

    print "Loading data from The Blue Alliance requires an API key"
    print "Please go to https://www.thebluealliance.com/account and generate a read API key"
    apiv3_key = raw_input("Enter your API key: ")

    global AUTH_TOKEN
    AUTH_TOKEN = apiv3_key

    if Match.validate_key_name(key):
        match_data = fetch_match(key)
        store_match(match_data)

    elif Event.validate_key_name(key):
        update_event(key)
    elif Team.validate_key_name(key):
        team_data = fetch_team(key)
        store_team(team_data)
    elif key.isdigit():
        event_keys = [event['key'] for event in fetch_endpoint('events/{}'.format(key))]
        for event in event_keys:
            update_event(event)
    else:
        print "Unknown key :("

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Bootstrap a TBA Development Instance")
    parser.add_argument("key", help="Event, Team, or Match key to import")
    parser.add_argument("--url", help="App Engine Remote API URL", required=True)
    args = parser.parse_args()

    main(args.key, args.url)


text:
<?php
/**
 * @package WordPress
 * @subpackage Green Marinee
 */

$themecolors = array(
	'bg' => 'ffffff',
	'text' => '3f3f3f',
	'link' => '7da721',
	'border' => 'fcfef4',
	'url' => 'ace149',
);

$content_width = 475;

register_sidebar( array(
	'name'          => __('Sidebar'),
	'id'            => 'sidebar',
	'before_widget' => '',
	'after_widget'  => '

',
	'before_title'  => '
',
	'after_title'   => '
' )
);

add_theme_support( 'automatic-feed-links' );

add_custom_background();

function greenmarinee_custom_background() {
	if ( '' != get_background_color() || '' != get_background_image() ) { ?>

	<?php }
}
add_action( 'wp_head', 'greenmarinee_custom_background' );

function green_marinee_comment($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment;
	extract($args, EXTR_SKIP);
?>
<li <?php comment_class(empty( $args['has_children'] ) ? '' : 'parent') ?> id="comment-<?php comment_ID() ?>">
	<div id="div-comment-<?php comment_ID() ?>">

		<?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['avatar_size'] ); ?>

			<?php comment_author_link() ?> <?php _e('said','greenmarinee'); ?>,

	<?php if ($comment->comment_approved == '0') : ?>
	<?php _e('Your comment is awaiting moderation.','greenmarinee'); ?>
	<?php endif; ?>

<?php _e('on','greenmarinee'); ?> <?php comment_date() ?> <?php _e('on','greenmarinee'); ?> <?php comment_time() ?>

	<?php comment_text() ?>

		<?php comment_reply_link(array_merge( $args, array('add_below' => 'div-comment', 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?>

<?php
}


text:
package views.disposal_of_vehicle

/**
 * The following are used to deduplicate code across views and tests; they are not used in view-model mappings.
 */
object VehicleLookupFailure {
  final val VehicleLookupId = "vehiclelookup"
  final val BeforeYouStartId = "beforeyoustart"
}


text:
package com.hartwig.healthchecks.common.io.path;

import static java.util.stream.Collectors.toCollection;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import org.jetbrains.annotations.NotNull;

@FunctionalInterface
public interface PathsExtensionFinder {

    String FILE_NOT_FOUND_MSG = "File %s not found in path %s";

    @NotNull
    List<Path> findPaths(@NotNull String path, @NotNull String extension) throws IOException;

    @NotNull
    static PathsExtensionFinder build() {
        return (path, extension) -> {
            final List<Path> searchedFile = getPath(path, extension);
            if (searchedFile.isEmpty()) {
                throw new FileNotFoundException(String.format(FILE_NOT_FOUND_MSG, extension, path));
            }
            return searchedFile;
        };
    }

    @NotNull
    static List<Path> getPath(@NotNull final String path, @NotNull final String extension) throws IOException {
        try (Stream<Path> paths = Files.walk(new File(path).toPath())) {
            return paths.filter(filePath -> filePath.getFileName().toString().endsWith(extension)).sorted()
                            .collect(toCollection(ArrayList<Path>::new));
        }
    }
}


text:
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;

using Newtonsoft.Json;

namespace DynamicRestProxy.PortableHttpClient
{
    static class ContentFactory
    {
        public static HttpContent CreateContent(HttpMethod method, IEnumerable<object> unnamedArgs, IEnumerable<KeyValuePair<string, object>> namedArgs)
        {
            // if there are unnamed args they represent the request body
            if (unnamedArgs.Any())
            {
                return Create(unnamedArgs);
            }

            // otherwise we assume that the named args that don't go on the url represent form encoded request body
            // for post requests pass any params as form-encoded - unless forced on the query string
            // also filter out named args where the value is null
            var localNamedArgs = namedArgs.Where(kvp => kvp.Value != null && !(kvp.Value is PostUrlParam));
            if (method == HttpMethod.Post && localNamedArgs.Any())
            {
                return Create(localNamedArgs);
            }

            return null;
        }

        private static HttpContent Create(IEnumerable<KeyValuePair<string, object>> args)
        {
            return new StringContent(args.AsQueryString(""), Encoding.UTF8, "application/x-www-form-urlencoded");
        }

        private static HttpContent Create(IEnumerable<object> contents)
        {
            Debug.Assert(contents != null);
            Debug.Assert(contents.Any(o => o != null));

            // if only 1 object in the collection, just create as normal
            if (contents.Count() == 1)
            {
                return Create(contents.First());
            }

            // otherwise package everything as multipart content
            var content = new MultipartFormDataContent();
            foreach (var o in contents)
            {
                content.Add(Create(o));
            }

            return content;
        }

        private static HttpContent Create(object content)
        {
            Debug.Assert(content != null);

            if (content is HttpContent) // if caller went to the trouble of passing HttpContent, just use it
            {
                return (HttpContent)content;
            }

            // check for a set of sentinal types that will serialize in a specific manner
            if (content is Stream)
            {
                return new StreamContent((Stream)content);
            }

            if (content is byte[])
            {
                return new ByteArrayContent((byte[])content);
            }

            if (content is string)
            {
                return new StringContent((string)content);
            }

            if (content is ContentInfo)
            {
                return Create((ContentInfo)content);
            }

            // primitive types (int, float etc) types get serialized as a string
            if (content.GetType().GetTypeInfo().IsPrimitive)
            {
                return new StringContent(content.ToString());
            }

            // all other types get serialized as json
            var json = JsonConvert.SerializeObject(content);
            return new StringContent(json, Encoding.UTF8, "application/json");
        }

        private static HttpContent Create(ContentInfo info)
        {
            // create content object as normal
            var content = Create(info.Content);

            // set any additional headers
            if (!string.IsNullOrEmpty(info.MimeType))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue(info.MimeType);
            }

            foreach (var kvp in info.ContentHeaders)
            {
                content.Headers.Add(kvp.Key, kvp.Value);
            }

            return content;
        }
    }
}


text:
package imageprocessing;

import base.Film;
import base.Spectrum;

/**
 * Created by simplaY on 04.01.2015.
 */
public class BoxfilterFilm implements Film {

    private final Spectrum[][] image;
    private final int width;
    private final int height;
    private final Spectrum[][] unnormalized;
    private final float nSamples[][];

    public BoxfilterFilm(int width, int height) {
        this.width = width;
        this.height = height;
        image = new Spectrum[width][height];
        unnormalized = new Spectrum[width][height];
        nSamples = new float[width][height];
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                image[i][j] = new Spectrum();
                unnormalized[i][j] = new Spectrum();
                nSamples[i][j] = 0.0f;
            }
        }
    }

    @Override
    public void addSample(double x, double y, Spectrum s) {
        if (isWithinRange(x, y)) {
            unnormalized[(int) x][(int) y].r += s.r;
            unnormalized[(int) x][(int) y].g += s.g;
            unnormalized[(int) x][(int) y].b += s.b;
            nSamples[(int) x][(int) y]++;
            image[(int) x][(int) y].r = unnormalized[(int) x][(int) y].r / nSamples[(int) x][(int) y];
            image[(int) x][(int) y].g = unnormalized[(int) x][(int) y].g / nSamples[(int) x][(int) y];
            image[(int) x][(int) y].b = unnormalized[(int) x][(int) y].b / nSamples[(int) x][(int) y];
        }
    }

    private boolean isWithinRange(double x, double y) {
        return (int) x >= 0 && (int) x < width && (int) y >= 0 && (int) y < height;
    }

    @Override
    public Spectrum[][] getImage() {
        return image;
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public int getHeight() {
        return height;
    }
}