text:
#include "h/mh.h"
#include "m_name.h"
#include "seq_save.h"
#include "m_backup.h"
#include "ext_hook.h"
#include "folder_delmsgs.h"
#include "context_save.h"
#include "arglist.h"
#include "error.h"
#include "h/utils.h"
#include "m_mktemp.h"

/*
 * 1) If we are using an external rmmproc, then exec it.
 * 2) Else if unlink_msgs is non-zero, then unlink the
 *    SELECTED messages.
 * 3) Else rename SELECTED messages by prefixing name
 *    with a standard prefix.
 *
 * If there is an error, return -1, else return 0.
 */

int
folder_delmsgs (struct msgs *mp, int unlink_msgs, int nohook)
{
    pid_t pid;
    int msgnum, vecp, retval = 0;
    char buf[100], *dp, **vec, *prog;
    char	msgpath[BUFSIZ];

    /*
     * If "rmmproc" is defined, exec it to remove messages.
     */
    if (rmmproc) {
	/* Unset the EXISTS flag for each message to be removed */
	for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	    if (is_selected (mp, msgnum))
		unset_exists (mp, msgnum);
	}

	/* Mark that the sequence information has changed */
	mp->msgflags |= SEQMOD;

	/*
	 * Write out the sequence and context files; this will release
	 * any locks before the rmmproc is called.
	 */

	seq_save (mp);
	context_save ();

	vec = argsplit(rmmproc, &prog, &vecp);

	/*
	 * argsplit allocates a MAXARGS vector by default,  If we need
	 * something bigger, allocate it ourselves
	 */

	if (mp->numsel + vecp + 1 > MAXARGS)
	    vec = mh_xrealloc(vec, (mp->numsel + vecp + 1) * sizeof *vec);
	for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	    if (is_selected (mp, msgnum) &&
		!(vec[vecp++] = strdup (m_name (msgnum))))
		die("strdup failed");
	}
	vec[vecp] = NULL;

	fflush (stdout);

	switch (pid = fork()) {
	case -1:
	    advise ("fork", "unable to");
	    return -1;

	case 0:
	    execvp (prog, vec);
	    fprintf (stderr, "unable to exec ");
	    perror (rmmproc);
	    _exit(1);

	default:
	    arglist_free(prog, vec);
	    return pidwait(pid, -1);
	}
    }

    /*
     * Either unlink or rename the SELECTED messages
     */
    for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	if (is_selected (mp, msgnum)) {
	    /* unselect message */
	    unset_selected (mp, msgnum);
	    mp->numsel--;

	    /*
	     *	Run the external hook on the message if one was specified in the context.
	     *	All we have is the message number; we have changed to the directory
	     *	containing the message.  So, we need to extract that directory to form
	     *	the complete path.  Note that the caller knows the directory, but has
	     *	no way of passing that to us.
	     */

	    if (!nohook) {
		    (void)snprintf(msgpath, sizeof (msgpath), "%s/%d", mp->foldpath, msgnum);
		    (void)ext_hook("del-hook", msgpath, NULL);
		}

	    dp = m_name (msgnum);

	    if (unlink_msgs) {
		/* just unlink the messages */
		if (m_unlink (dp) == -1) {
		    admonish (dp, "unable to unlink");
		    retval = -1;
		    continue;
		}
	    } else {
		/* or rename messages with standard prefix */
		strncpy (buf, m_backup (dp), sizeof(buf));
		if (rename (dp, buf) == -1) {
		    admonish (buf, "unable to rename %s to", dp);
		    retval = -1;
		    continue;
		}
	    }

	    /* If removal was successful, decrement message count */
	    unset_exists (mp, msgnum);
	    mp->nummsg--;
	}
    }

    /* Sanity check */
    if (mp->numsel != 0)
	die("oops, mp->numsel should be 0");

    /* Mark that the sequence information has changed */
    mp->msgflags |= SEQMOD;

    /*
     * Write out sequence and context files
     */

    seq_save (mp);
    context_save ();

    return retval;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\models\Village;
use common\models\DateReadyDistrict;
use kartik\file\FileInput;

/* @var $this yii\web\View */
/* @var $model common\models\District */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'options'=>['enctype'=>'multipart/form-data']
    ]);
    ?>

    <?= $form->field($model, 'village_id')->dropDownList(ArrayHelper::map(Village::find()->all(), 'id', 'name'), ['prompt='>'- Choose Your Permissions -']) ?>

    <?= $form->field($model, 'number')->textInput() ?>

    <?= $form->field($model, 'size')->textInput() ?>

    <?= $form->field($model, 'price')->textInput() ?>

    <?= $form->field($model, 'is_sold')->checkbox() ?>

    <?= $form->field($model, 'is_house')->checkbox() ?>

    <?= $form->field($model, 'date_ready')->dropDownList(ArrayHelper::map(DateReadyDistrict::find()->all(), 'id',
        'date'),
        ['prompt='>'- Choose Your Permissions -']) ?>

    <?= FileInput::widget([
        'options'=>['accept'=>'image/*'],
        'model' => $model,
        'attribute' => 'image',
        'pluginOptions' => [
            'initialPreview'=>$model->image ? [
                 Html::img($model->thumburl),
            ] : false,
            'overwriteInitial'=>true
        ]
    ]);?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
{% extends "auth_base.html" %}
{% load staticfiles %}
{% block title %}{{ shed }} Details{% endblock %}
{% block ShedsNav %} active {% endblock %}
{% block auth-content %}

{{ shed }} Details

                Owner

                {{ shed.owner.get_full_name }}

                Registered On

                {{ shed.registered_on|date }}

                Address

                {{ shed.address.get_multi_line }}

        {% if request.user == shed.owner %}
            <form action="{% url 'shed:delete' shed.pk %}" method="POST">
                {% csrf_token %}

                                <button type="button" class="close" data-dismiss="modal">×Close</button>

Delete Community Shed

                                Are you sure you want to delete this community shed?

                                <button type="button" aria-hidden="true" data-dismiss="modal" class="btn btn-link">No
                                </button>
                                <button type="submit" class="btn btn-primary">Yes</button>

            </form>

                    Update
                    <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#confirm-modal">
                        Delete
                    </button>

        {% endif %}

Tools In This Community Shed

            {% if tools %}
                {% for tool in tools %}

                                                {% if tool.1 == 0 %}
                                                     Available
                                                    Tool is available!
                                                {% elif tool.1 == 1 %}
                                                     {{ tool.0.get_next_available_date }}
                                                    Tool will be available starting tomorrow!
                                                {% elif tool.1 > 1 %}
                                                     {{ tool.0.get_next_available_date }}
                                                    Tool will be available in {{ tool.1 }} days!
                                                {% endif %}

{{ tool.0.name }}

                {% endfor %}
            {% else %}

                        There are no tools in the community shed.

            {% endif %}

        {% if tools.paginator.num_pages > 1 %}

                             « First Page

                        {% if tools.has_previous %}

                                 ‹ Previous

                        {% else %}

                                 ‹ Previous

                        {% endif %}

                             Page {{ tools.number }} of {{ tools.paginator.num_pages }}

                        {% if tools.has_next %}

                                 Next ›

                        {% else %}

                                 Next ›

                        {% endif %}

                             Last Page »

        {% endif %}

{% endblock %}


text:
package no.kantega.publishing.admin.content.spellcheck;

import junit.framework.TestCase;

/**
 *
 */
public class SpellcheckerServiceImplTest extends TestCase {

    public void testSpellcheck() {
//        SpellcheckerService spellcheckerService = new SpellcheckerServiceImpl();
//
//        List<String> words = new ArrayList<String>();
//        words.add("beleived");
//        words.add("country");
//        words.add("color");
//        words.add("colour");
//        List<String> returnedWords = spellcheckerService.spellcheck(words);
//
//        assertEquals(2, returnedWords.size());
//        assertEquals("beleived", returnedWords.get(0));
//        assertEquals("colour", returnedWords.get(1));
    }

}


text:
var context = require.context('./src', true, /-test\.js(x?)$/);
context.keys().forEach(context);


text:
'use strict';

const {Obj} = require('./object');

function traverseAndCheck(obj, type, results) {
  if (obj instanceof type) {
    results.push(obj);
  }

  if (obj instanceof Node) {
    obj.findAll(type, results);
  }
}

class Node extends Obj {
  init(lineno, colno, ...args) {
    this.lineno = lineno;
    this.colno = colno;

    this.fields.forEach((field, i) => {
      // The first two args are line/col numbers, so offset by 2
      var val = arguments[i + 2];

      // Fields should never be undefined, but null. It makes
      // testing easier to normalize values.
      if (val === undefined) {
        val = null;
      }

      this[field] = val;
    });
  }

  findAll(type, results) {
    results = results || [];

    if (this instanceof NodeList) {
      this.children.forEach(child => traverseAndCheck(child, type, results));
    } else {
      this.fields.forEach(field => traverseAndCheck(this[field], type, results));
    }

    return results;
  }

  iterFields(func) {
    this.fields.forEach((field) => {
      func(this[field], field);
    });
  }
}

// Abstract nodes
class Value extends Node {
  get typename() { return 'Value'; }
  get fields() {
    return ['value'];
  }
}

// Concrete nodes
class NodeList extends Node {
  get typename() { return 'NodeList'; }
  get fields() { return ['children']; }

  init(lineno, colno, nodes) {
    super.init(lineno, colno, nodes || []);
  }

  addChild(node) {
    this.children.push(node);
  }
}

const Root = NodeList.extend('Root');
const Literal = Value.extend('Literal');
const Symbol = Value.extend('Symbol');
const Group = NodeList.extend('Group');
const ArrayNode = NodeList.extend('Array');
const Pair = Node.extend('Pair', { fields: ['key', 'value'] });
const Dict = NodeList.extend('Dict');
const LookupVal = Node.extend('LookupVal', { fields: ['target', 'val'] });
const If = Node.extend('If', { fields: ['cond', 'body', 'else_'] });
const IfAsync = If.extend('IfAsync');
const InlineIf = Node.extend('InlineIf', { fields: ['cond', 'body', 'else_'] });
const For = Node.extend('For', { fields: ['arr', 'name', 'body', 'else_'] });
const AsyncEach = For.extend('AsyncEach');
const AsyncAll = For.extend('AsyncAll');
const Macro = Node.extend('Macro', { fields: ['name', 'args', 'body'] });
const Caller = Macro.extend('Caller');
const Import = Node.extend('Import', { fields: ['template', 'target', 'withContext'] });

class FromImport extends Node {
  get typename() { return 'FromImport'; }
  get fields() { return ['template', 'names', 'withContext']; }

  init(lineno, colno, template, names, withContext) {
    super.init(lineno, colno, template, names || new NodeList(), withContext);
  }
}

const FunCall = Node.extend('FunCall', { fields: ['name', 'args'] });
const Filter = FunCall.extend('Filter');
const FilterAsync = Filter.extend('FilterAsync', { fields: ['name', 'args', 'symbol'] });
const KeywordArgs = Dict.extend('KeywordArgs');
const Block = Node.extend('Block', { fields: ['name', 'body'] });
const Super = Node.extend('Super', { fields: ['blockName', 'symbol'] });
const TemplateRef = Node.extend('TemplateRef', { fields: ['template'] });
const Extends = TemplateRef.extend('Extends');
const Include = Node.extend('Include', { fields: ['template', 'ignoreMissing'] });
const Set = Node.extend('Set', { fields: ['targets', 'value'] });
const Switch = Node.extend('Switch', { fields: ['expr', 'cases', 'default'] });
const Case = Node.extend('Case', { fields: ['cond', 'body'] });
const Output = NodeList.extend('Output');
const Capture = Node.extend('Capture', { fields: ['body'] });
const TemplateData = Literal.extend('TemplateData');
const UnaryOp = Node.extend('UnaryOp', { fields: ['target'] });
const BinOp = Node.extend('BinOp', { fields: ['left', 'right'] });
const In = BinOp.extend('In');
const Is = BinOp.extend('Is');
const Or = BinOp.extend('Or');
const And = BinOp.extend('And');
const Not = UnaryOp.extend('Not');
const Add = BinOp.extend('Add');
const Concat = BinOp.extend('Concat');
const Sub = BinOp.extend('Sub');
const Mul = BinOp.extend('Mul');
const Div = BinOp.extend('Div');
const FloorDiv = BinOp.extend('FloorDiv');
const Mod = BinOp.extend('Mod');
const Pow = BinOp.extend('Pow');
const Neg = UnaryOp.extend('Neg');
const Pos = UnaryOp.extend('Pos');
const Compare = Node.extend('Compare', { fields: ['expr', 'ops'] });
const CompareOperand = Node.extend('CompareOperand', { fields: ['expr', 'type'] });
const CallExtension = Node.extend('CallExtension', {
  init(ext, prop, args, contentArgs) {
    this.parent();
    this.extName = ext.__name || ext;
    this.prop = prop;
    this.args = args || new NodeList();
    this.contentArgs = contentArgs || [];
    this.autoescape = ext.autoescape;
  },
  fields: ['extName', 'prop', 'args', 'contentArgs']
});
const CallExtensionAsync = CallExtension.extend('CallExtensionAsync');

// This is hacky, but this is just a debugging function anyway
function print(str, indent, inline) {
  var lines = str.split('\n');

  lines.forEach((line, i) => {
    if (line && ((inline && i > 0) || !inline)) {
      process.stdout.write((' ').repeat(indent));
    }
    const nl = (i === lines.length - 1) ? '' : '\n';
    process.stdout.write(`${line}${nl}`);
  });
}

// Print the AST in a nicely formatted tree format for debuggin
function printNodes(node, indent) {
  indent = indent || 0;

  print(node.typename + ': ', indent);

  if (node instanceof NodeList) {
    print('\n');
    node.children.forEach((n) => {
      printNodes(n, indent + 2);
    });
  } else if (node instanceof CallExtension) {
    print(`${node.extName}.${node.prop}\n`);

    if (node.args) {
      printNodes(node.args, indent + 2);
    }

    if (node.contentArgs) {
      node.contentArgs.forEach((n) => {
        printNodes(n, indent + 2);
      });
    }
  } else {
    let nodes = [];
    let props = null;

    node.iterFields((val, fieldName) => {
      if (val instanceof Node) {
        nodes.push([fieldName, val]);
      } else {
        props = props || {};
        props[fieldName] = val;
      }
    });

    if (props) {
      print(JSON.stringify(props, null, 2) + '\n', null, true);
    } else {
      print('\n');
    }

    nodes.forEach(([fieldName, n]) => {
      print(`[${fieldName}] =>`, indent + 2);
      printNodes(n, indent + 4);
    });
  }
}

module.exports = {
  Node: Node,
  Root: Root,
  NodeList: NodeList,
  Value: Value,
  Literal: Literal,
  Symbol: Symbol,
  Group: Group,
  Array: ArrayNode,
  Pair: Pair,
  Dict: Dict,
  Output: Output,
  Capture: Capture,
  TemplateData: TemplateData,
  If: If,
  IfAsync: IfAsync,
  InlineIf: InlineIf,
  For: For,
  AsyncEach: AsyncEach,
  AsyncAll: AsyncAll,
  Macro: Macro,
  Caller: Caller,
  Import: Import,
  FromImport: FromImport,
  FunCall: FunCall,
  Filter: Filter,
  FilterAsync: FilterAsync,
  KeywordArgs: KeywordArgs,
  Block: Block,
  Super: Super,
  Extends: Extends,
  Include: Include,
  Set: Set,
  Switch: Switch,
  Case: Case,
  LookupVal: LookupVal,
  BinOp: BinOp,
  In: In,
  Is: Is,
  Or: Or,
  And: And,
  Not: Not,
  Add: Add,
  Concat: Concat,
  Sub: Sub,
  Mul: Mul,
  Div: Div,
  FloorDiv: FloorDiv,
  Mod: Mod,
  Pow: Pow,
  Neg: Neg,
  Pos: Pos,
  Compare: Compare,
  CompareOperand: CompareOperand,

  CallExtension: CallExtension,
  CallExtensionAsync: CallExtensionAsync,

  printNodes: printNodes
};


text:
<?php

namespace wbarcovsky\yii2\request_docs\models\apiDocJs\Tags;

use phpDocumentor\Reflection\DocBlock\DescriptionFactory;
use phpDocumentor\Reflection\DocBlock\Tags\BaseTag;
use phpDocumentor\Reflection\DocBlock\Tags\Factory\StaticMethod;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context;
use Webmozart\Assert\Assert;

class Api extends BaseTag implements StaticMethod
{
    /** @var string $name */
    protected $name = 'api';
    /** @var string $method HTTP method */
    protected $method;
    /** @var string $path Request Path */
    protected $path;
    /** @var string $title A short title */
    protected $title = '';

    /**
     * @param string $method HTTP method
     * @param string $path Request Path
     * @param string $title A short title
     */
    public function __construct($method, $path, $title = '')
    {
        Assert::oneOf($method, ['{get}', '{head}', '{post}', '{put}', '{delete}', '{trace}', '{options}', '{connect}', '{patch}']);
        Assert::stringNotEmpty($path);

        preg_match('~\{(?<method>.+)\}~u', $method, $matches);
        $method = mb_convert_case($matches['method'], MB_CASE_UPPER);

        $this->method = $method;
        $this->path = $path;
        $this->title = $title;
    }

    /**
     * HTTP метод в верхнем регистре.
     * @return string
     */
    public function getMethod()
    {
        return $this->method;
    }

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * {@inheritdoc}
     */
    public static function create($body)
    {
        Assert::stringNotEmpty($body);

        $parts = preg_split('~(\s+)~Su', $body, 3);
        Assert::greaterThanEq(count($parts), 2, 'method or path not set');
        $method = $parts[0];
        $path = $parts[1];
        $title = $parts[2] ? $parts[2] : '';

        return new static($method, $path, $title);
    }

    /**
     * Returns a string representation for this tag.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->method . ' '
            . $this->path
            . ($this->title ? ' ' . $this->title : '');
    }
}


text:
namespace Cofoundry.Domain.Data.Internal;

public static class IEntityPublishableExtensions
{
    /// <summary>
    /// Updates the <see cref="IEntityPublishable.PublishStatusCode"/> and
    /// publish date properties to mark the entity as published.
    /// </summary>
    /// <typeparam name="TEntity">Type of entity to act on.</typeparam>
    /// <param name="entity">Entity to act on.</param>
    /// <param name="currentDate">The current date and time, typically passed from the execution context in the domain layer.</param>
    /// <param name="publishDate">
    /// Optional time that the entity should be published and made public. If
    /// this is left <see langword="null"/> then the publish date is set to the current
    /// date and the page is made immediately available.
    /// </param>
    /// <returns>
    /// Returns <see langword="true"/> if the entity status has changed. If the entity was already published and
    /// no change needed to be made, then <see langword="false"/> is returned.
    /// </returns>
    public static bool SetPublished<TEntity>(this TEntity entity, DateTime currentDate, DateTime? publishDate = null)
        where TEntity : IEntityPublishable
    {
        ArgumentNullException.ThrowIfNull(entity);
        ArgumentEmptyException.ThrowIfDefault(currentDate);

        bool hasPublishStatusChanged = false;

        if (entity.PublishStatusCode != PublishStatusCode.Published)
        {
            hasPublishStatusChanged = true;
            entity.PublishStatusCode = PublishStatusCode.Published;
        }

        UpdatePublishDate(entity, currentDate, publishDate);

        return hasPublishStatusChanged;
    }

    private static void UpdatePublishDate<TEntity>(TEntity entity, DateTime currentDate, DateTime? publishDate = null)
        where TEntity : IEntityPublishable
    {
        if (publishDate.HasValue)
        {
            // If a specific date has been requested, use it
            entity.PublishDate = publishDate;
        }
        else if (!entity.PublishDate.HasValue)
        {
            // Otheriwse only set it if it's not been published yet
            entity.PublishDate = currentDate;
        }

        // Always update the last publish date
        entity.LastPublishDate = currentDate;

        // but if the publish date has been requested for the future, reflect that in LastPublishDate
        if (entity.PublishDate > entity.LastPublishDate)
        {
            entity.LastPublishDate = entity.PublishDate;
        }
    }
}


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

    /// <summary>
    /// HierarchySettingsOperations operations.
    /// </summary>
    public partial interface IHierarchySettingsOperations
    {
        /// <summary>
        /// Gets all the hierarchy settings defined at the Management Group
        /// level. Settings can only be set on the root Management Group of the
        /// hierarchy.
        ///
        /// </summary>
        /// <param name='groupId'>
        /// Management Group ID.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<HierarchySettingsList>> ListWithHttpMessagesAsync(string groupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets the hierarchy settings defined at the Management Group level.
        /// Settings can only be set on the root Management Group of the
        /// hierarchy.
        ///
        /// </summary>
        /// <param name='groupId'>
        /// Management Group ID.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<HierarchySettings>> GetWithHttpMessagesAsync(string groupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Creates or updates the hierarchy settings defined at the Management
        /// Group level.
        ///
        /// </summary>
        /// <param name='groupId'>
        /// Management Group ID.
        /// </param>
        /// <param name='createTenantSettingsRequest'>
        /// Tenant level settings request parameter.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<HierarchySettings>> CreateOrUpdateWithHttpMessagesAsync(string groupId, CreateOrUpdateSettingsRequest createTenantSettingsRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Updates the hierarchy settings defined at the Management Group
        /// level.
        ///
        /// </summary>
        /// <param name='groupId'>
        /// Management Group ID.
        /// </param>
        /// <param name='createTenantSettingsRequest'>
        /// Tenant level settings request parameter.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<HierarchySettings>> UpdateWithHttpMessagesAsync(string groupId, CreateOrUpdateSettingsRequest createTenantSettingsRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Deletes the hierarchy settings defined at the Management Group
        /// level.
        ///
        /// </summary>
        /// <param name='groupId'>
        /// Management Group ID.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string groupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
prototypr
====
PHP 5.5+ object prototyping system using traits

[![Build Status](https://travis-ci.org/jgswift/prototypr.png?branch=master)](https://travis-ci.org/jgswift/prototypr)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/jgswift/prototypr/badges/quality-score.png?s=68521f67cca0eea2e8106d27e5ae3109b9405c90)](https://scrutinizer-ci.com/g/jgswift/prototypr/)

## Installation

Install via [composer](https://getcomposer.org/):
```sh
php composer.phar require jgswift/prototypr:dev-master
```

## Usage

Prototypr is a lightweight php trait that enables easy object prototyping with magic methods.
Prototypr aims to add simple prototypal behavior to php without intruding on your domain model

The following is a minimal example
```php
<?php
class Foo
{
    use prototypr\Prototype;
}

Foo::bar(function() {
    return "baz";
});

$foo = new Foo;
var_dump($foo->bar()); // returns "baz"
```

Alternatively methods can be set in a local scope and apply only to an individual object

```php
class Foo
{
    use prototypr\Prototype;
}

$foo = new Foo();
$foo->bar(function() {
    return "baz";
});
var_dump($foo->bar()); // returns "baz"
```

prototypr supports late-binding of multiple closures and will always execute all closures regardless of return conditions

```php
class Foo
{
    use prototypr\Prototype;
}

$count = 0;
Foo::bar(function()use(&$count) {
    $count+=1;
});

Foo::bar(function()use(&$count) {
    $count+=2;
});

$foo = new Foo();
$foo->bar();

var_dump($count); // returns 3
```

prototypr will automatically traverse the class tree to find methods, but you may also specify individual extensions

```php
class Foo
{
    use prototypr\Prototype;
}

Foo::bar(function() {
    return "somethingImportant";
});

class Baz
{
    use prototypr\Prototype;
}

prototypr\Manager::extend('Baz','Foo');

var_dump(count(prototypr\Registry::prototypes('Baz'))); // returns 1

$baz = new Baz;
var_dump($baz->bar()); // returns "somethingImportant"
```


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title> My first chart with Highcharts </title>
  <link rel="stylesheet" href="styles/first_chart.css">

My first chart with Highcharts

By Your Name Here

There is a chart above this paragraph.


text:
#ifndef PACKET_H_
#define PACKET_H_

#include "libssh/wrapper.h"

struct ssh_socket_struct;

/* this structure should go someday */
typedef struct packet_struct {
	int valid;
	uint32_t len;
	uint8_t type;
} PACKET;

/** different state of packet reading. */
enum ssh_packet_state_e {
  /** Packet not initialized, must read the size of packet */
  PACKET_STATE_INIT,
  /** Size was read, waiting for the rest of data */
  PACKET_STATE_SIZEREAD,
  /** Full packet was read and callbacks are being called. Future packets
   * should wait for the end of the callback. */
  PACKET_STATE_PROCESSING
};

int ssh_packet_send(ssh_session session);

#ifdef WITH_SSH1
int ssh_packet_send1(ssh_session session) ;
void ssh_packet_set_default_callbacks1(ssh_session session);

SSH_PACKET_CALLBACK(ssh_packet_disconnect1);
SSH_PACKET_CALLBACK(ssh_packet_smsg_success1);
SSH_PACKET_CALLBACK(ssh_packet_smsg_failure1);
int ssh_packet_socket_callback1(const void *data, size_t receivedlen, void *user);

#endif

SSH_PACKET_CALLBACK(ssh_packet_unimplemented);
SSH_PACKET_CALLBACK(ssh_packet_disconnect_callback);
SSH_PACKET_CALLBACK(ssh_packet_ignore_callback);
SSH_PACKET_CALLBACK(ssh_packet_dh_reply);
SSH_PACKET_CALLBACK(ssh_packet_newkeys);
SSH_PACKET_CALLBACK(ssh_packet_service_accept);

#ifdef WITH_SERVER
SSH_PACKET_CALLBACK(ssh_packet_kexdh_init);
#endif

int ssh_packet_send_unimplemented(ssh_session session, uint32_t seqnum);
int ssh_packet_parse_type(ssh_session session);
//int packet_flush(ssh_session session, int enforce_blocking);

int ssh_packet_socket_callback(const void *data, size_t len, void *user);
void ssh_packet_register_socket_callback(ssh_session session, struct ssh_socket_struct *s);
void ssh_packet_set_callbacks(ssh_session session, ssh_packet_callbacks callbacks);
void ssh_packet_set_default_callbacks(ssh_session session);
void ssh_packet_process(ssh_session session, uint8_t type);

/* PACKET CRYPT */
uint32_t ssh_packet_decrypt_len(ssh_session session, char *crypted);
int ssh_packet_decrypt(ssh_session session, void *packet, unsigned int len);
unsigned char *ssh_packet_encrypt(ssh_session session,
                                  void *packet,
                                  unsigned int len);
int ssh_packet_hmac_verify(ssh_session session,ssh_buffer buffer,
                           unsigned char *mac, enum ssh_hmac_e type);

#endif /* PACKET_H_ */


text:
Mural(selector, \[smooth\], \[immediate\])
------------------------------------------
**Parameters**

**selector**:  *String*,  CSS selector for your canvas element

**[smooth]**:  *boolean*,  turn on image smoothing (default off)

**[immediate]**:  *boolean*,  if true, redraw the image when receiving a change, otherwise wait until redraw is called (default false)

hidePointer()
-------------
hide mouse pointer

showPointer()
-------------
show mouse pointer

getMousePosition()
------------------
**Returns**

*{x: number, y: number*,  } mouse coordinates relative to mural

addPlayArea(x, y, width, height)
--------------------------------
**Parameters**

**x**:  *Number*,

**y**:  *Number*,

**width**:  *Number*,

**height**:  *Number*,

changed()
---------
gets called by children to notify that there has been a visual change

redraw(\[force\])
-----------------
redraw the canvas element if something has changed or if force = true

**Parameters**

**[force]**:  *boolean*,

draw(\[force\])
---------------
make playAreas redraw themselves if changed or if force = true

**Parameters**

**[force]**:  *boolean*,

animate(object)
---------------
add sprite to list of sprites that has to be animated automatically

**Parameters**

**object**:  *Sprite*,

removeAnimation(object)
-----------------------
remove sprite to list of sprites that has to be animated automatically

**Parameters**

**object**:  *Sprite*,


text:
'use strict'

var api = require('../api/volume')
var def = require('../definition/volume/dry-gallon')

var unit = 'dry-gallon'

api.augment(unit, def)

module.exports = api.get(unit)


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Logging;

namespace Microsoft.Xtc.Common.Services.Logging
{
    /// <summary>
    /// Extension methods for the ILogger interface.
    /// </summary>
    public static class LoggerExtensions
    {
        public static void LogTrace(this ILogger logger, EventId eventId, IEnumerable<string> lines)
        {
            logger.LogTrace(eventId, ConcatenateLines(lines));
        }

        public static void LogDebug(this ILogger logger, EventId eventId, IEnumerable<string> lines)
        {
            logger.LogDebug(eventId, ConcatenateLines(lines));
        }

        public static void LogInformation(this ILogger logger, EventId eventId, IEnumerable<string> lines)
        {
            logger.LogInformation(eventId, ConcatenateLines(lines));
        }

        public static void LogWarning(this ILogger logger, EventId eventId, IEnumerable<string> lines)
        {
            logger.LogWarning(eventId, ConcatenateLines(lines));
        }

        public static void LogError(this ILogger logger, EventId eventId, IEnumerable<string> lines)
        {
            logger.LogError(eventId, ConcatenateLines(lines));
        }

        public static void LogCritical(this ILogger logger, EventId eventId, IEnumerable<string> lines)
        {
            logger.LogCritical(eventId, ConcatenateLines(lines));
        }

        private static string ConcatenateLines(IEnumerable<string> lines)
        {
            var result = new StringBuilder();

            foreach (var line in lines)
            {
                if (result.Length > 0)
                    result.AppendLine();

                result.Append(line);
            }

            return result.ToString();
        }

        /// <summary>
        /// Returns string prefix for a given log level. The prefix is the same as default
        /// Console Logger uses. See https://docs.asp.net/en/latest/fundamentals/logging.html
        /// for more information.
        /// </summary>
        public static string GetLogLevelPrefix(LogLevel logLevel)
        {
            switch (logLevel)
            {
                case LogLevel.Critical:
                    return "crit";
                case LogLevel.Error:
                    return "fail";
                case LogLevel.Warning:
                    return "warn";
                case LogLevel.Information:
                    return "info";
                case LogLevel.Debug:
                    return "dbug";
                case LogLevel.Trace:
                    return "trce";
                default:
                    throw new ArgumentException($"Unrecognized LogLevel \"{logLevel}\"", nameof(logLevel));
            }
        }
    }
}


text:
package edu.mayo.phenoportal.client.phenotype.report;

import com.smartgwt.client.widgets.grid.ListGridRecord;

public class SupplementalDataRecord extends ListGridRecord {

    public SupplementalDataRecord() {
        super();

    }

    public SupplementalDataRecord(String oid, String description) {
        super();

        setOid(oid);
        setDescription(description);

    }

    public void setOid(String oid) {
        setAttribute("oid", oid);
    }

    public String getOid() {
        return getAttributeAsString("oid");
    }

    public void setDescription(String description) {
        setAttribute("description", description);
    }

    public String getDescription() {
        return getAttributeAsString("description");
    }

}


text:
using System.Windows;

namespace AssaultBird2454.VPTU.Client.UI
{
    /// <summary>
    ///     Interaction logic for String_Prompt.xaml
    /// </summary>
    public partial class String_Prompt : Window
    {
        public String_Prompt(string Window_Title)
        {
            InitializeComponent();
            Title = Window_Title;
        }

        public string Input { get; private set; }

        private void Sumbit_Button_Click(object sender, RoutedEventArgs e)
        {
            Input = Value.Text;
            DialogResult = true;
            Close();
        }

        private void Cancel_Button_Click(object sender, RoutedEventArgs e)
        {
            Input = "";
            DialogResult = false;
            Close();
        }
    }
}


text:
import { Directive, ElementRef, KeyValueDiffers, Renderer } from '@angular/core';
import { isBlank, isPresent } from '../facade/lang';
export class NgStyle {
    constructor(_differs, _ngEl, _renderer) {
        this._differs = _differs;
        this._ngEl = _ngEl;
        this._renderer = _renderer;
    }
    set rawStyle(v) {
        this._rawStyle = v;
        if (isBlank(this._differ) && isPresent(v)) {
            this._differ = this._differs.find(this._rawStyle).create(null);
        }
    }
    ngDoCheck() {
        if (isPresent(this._differ)) {
            var changes = this._differ.diff(this._rawStyle);
            if (isPresent(changes)) {
                this._applyChanges(changes);
            }
        }
    }
    _applyChanges(changes) {
        changes.forEachAddedItem((record) => { this._setStyle(record.key, record.currentValue); });
        changes.forEachChangedItem((record) => { this._setStyle(record.key, record.currentValue); });
        changes.forEachRemovedItem((record) => { this._setStyle(record.key, null); });
    }
    _setStyle(name, val) {
        this._renderer.setElementStyle(this._ngEl.nativeElement, name, val);
    }
}
/** @nocollapse */
NgStyle.decorators = [
    { type: Directive, args: [{ selector: '[ngStyle]', inputs: ['rawStyle: ngStyle'] },] },
];
/** @nocollapse */
NgStyle.ctorParameters = [
    { type: KeyValueDiffers, },
    { type: ElementRef, },
    { type: Renderer, },
];
//# sourceMappingURL=ng_style.js.map


text:
namespace irr {
namespace core {

// -----------------------------------------------------------------------------
/// Utility class to easily convert a Chrono::Engine vector into an Irrlicht
/// vector3df. Simply create an Irrlicht compatible vector as:
///          myvector=vector3dfCH(mychronovector);
// -----------------------------------------------------------------------------

class ChApiIrr vector3dfCH : public vector3df {
  public:
    vector3dfCH(const chrono::ChVector<>& mch) {
        X = ((f32)mch.x);
        Y = ((f32)mch.y);
        Z = ((f32)mch.z);
    }
    vector3dfCH(chrono::ChVector<>* mch) {
        X = ((f32)mch->x);
        Y = ((f32)mch->y);
        Z = ((f32)mch->z);
    }
};

}  // END_OF_NAMESPACE____
}  // END_OF_NAMESPACE____

namespace irr {

// -----------------------------------------------------------------------------
/// Class with static functions which help with the integration of
/// Chrono::Engine and Irrlicht 3D rendering library.
// -----------------------------------------------------------------------------

class ChApiIrr ChIrrTools {
  public:
    enum eCh_ContactsDrawMode {
        CONTACT_NORMALS = 0,  // draw normals
        CONTACT_DISTANCES,    // draw lines connecting two contact points
        CONTACT_FORCES_N,     // draw contact forces (only normal component) applied to 2nd body
        CONTACT_FORCES,       // draw contact forces applied to 2nd body
        CONTACT_NONE          // draw nothing
    };

    enum eCh_ContactsLabelMode {
        CONTACT_DISTANCES_VAL,  // print distance
        CONTACT_FORCES_VAL,     // print contact forces modulus
        CONTACT_FORCES_N_VAL,   // print contact forces (only normal component)
        CONTACT_FORCES_T_VAL,   // print contact forces (only tangential component)
        CONTACT_TORQUES_VAL,    // print contact torques modulus
        CONTACT_TORQUES_S_VAL,  // print contact torques modulus (only spinning component)
        CONTACT_TORQUES_R_VAL,  // print contact torques modulus (only rolling component)
        CONTACT_NONE_VAL        // print nothing
    };

    enum eCh_LinkDrawMode {
        LINK_REACT_FORCE = 0,  // draw reaction force
        LINK_REACT_TORQUE,     // draw reaction torque
        LINK_NONE              // draw nothing
    };

    enum eCh_LinkLabelMode {
        LINK_REACT_FORCE_VAL = 0,  // print reaction force modulus
        LINK_REACT_FORCE_X,        // print reaction force x
        LINK_REACT_FORCE_Y,        // print reaction force y
        LINK_REACT_FORCE_Z,        // print reaction force z
        LINK_REACT_TORQUE_VAL,     // print reaction torque modulus
        LINK_REACT_TORQUE_X,       // print reaction torque x
        LINK_REACT_TORQUE_Y,       // print reaction torque y
        LINK_REACT_TORQUE_Z,       // print reaction torque z
        LINK_NONE_VAL              // draw nothing
    };

    /// Function to align an Irrlicht object to a Chrono::Engine coordsys.
    static void alignIrrlichtNodeToChronoCsys(scene::ISceneNode* mnode, const chrono::ChCoordsys<>& mcoords);

    /// Easy-to-use function which draws contact points used by a ChSystem in the
    /// current Irrlicht viewer (the IVideoDriver). The contact points are
    /// visually represented with short lines, of length mlen, aligned to contact
    /// normals.
    static int drawAllContactPoints(chrono::ChSystem& mphysicalSystem,
                                    video::IVideoDriver* driver,
                                    double mlen = 1.0,
                                    eCh_ContactsDrawMode drawtype = CONTACT_NORMALS);

    /// Easy-to-use function which draws contact informations as labels at the
    /// contact point
    static int drawAllContactLabels(chrono::ChSystem& mphysicalSystem,
                                    irr::IrrlichtDevice* device,
                                    eCh_ContactsLabelMode labeltype = CONTACT_FORCES_N_VAL,
                                    video::SColor mcol = video::SColor(255, 255, 255, 255));

    /// Easy-to-use function which draws reaction forces in all contacts in
    /// current Irrlicht viewer (the IVideoDriver).
    static int drawAllLinks(chrono::ChSystem& mphysicalSystem,
                            video::IVideoDriver* driver,
                            double mlen = 1.0,
                            eCh_LinkDrawMode drawtype = LINK_REACT_FORCE);

    /// Easy-to-use function which draws contact informations as labels at the
    /// contact point
    static int drawAllLinkLabels(chrono::ChSystem& mphysicalSystem,
                                 irr::IrrlichtDevice* device,
                                 eCh_LinkLabelMode labeltype = LINK_REACT_FORCE_X,
                                 video::SColor mcol = video::SColor(255, 255, 255, 255));

    /// Easy-to-use function which draws collision objects bounding boxes for
    /// rigid bodies - if they have a collision shape.
    static int drawAllBoundingBoxes(chrono::ChSystem& mphysicalSystem, video::IVideoDriver* driver);

    /// Easy-to-use function which draws coordinate systems of ChBody objects.
    static int drawAllCOGs(chrono::ChSystem& mphysicalSystem, video::IVideoDriver* driver, double scale = 0.01);

    /// Easy-to-use function which draws coordinate systems of link frames.
    static int drawAllLinkframes(chrono::ChSystem& mphysicalSystem, video::IVideoDriver* driver, double scale = 0.01);

    /// --
    static void drawHUDviolation(video::IVideoDriver* driver,
                                 IrrlichtDevice* mdevice,
                                 chrono::ChSystem& asystem,
                                 int mx = 10,
                                 int my = 290,
                                 int sx = 300,
                                 int sy = 100,
                                 double spfact = 100.0,
                                 double posfact = 500.0);

    /// --
    static void drawChFunction(IrrlichtDevice* mdevice,
                               chrono::ChFunction* fx,
                               double xmin = 0,
                               double xmax = 1,
                               double ymin = -1,
                               double ymax = 1,
                               int mx = 10,
                               int my = 290,
                               int sx = 300,
                               int sy = 100);

    /// Easy-to-use function to draw segment lines in 3D space, with given color.
    static void drawSegment(video::IVideoDriver* driver,
                            chrono::ChVector<> mstart,
                            chrono::ChVector<> mend,
                            video::SColor mcol = video::SColor(255, 0, 0, 0),
                            bool use_Zbuffer = false);

    /// Easy-to-use function to draw a polyline in 3D space, given the array of
    /// points as a std::vector.
    static void drawPolyline(video::IVideoDriver* driver,
                             std::vector<chrono::ChVector<> > mpoints,
                             video::SColor mcol = video::SColor(255, 0, 0, 0),
                             bool use_Zbuffer = false);

    /// Easy-to-use function to draw a circle line in 3D space, with given color.
    /// Specify the center as coordsys position. Orientation as coordsys
    /// quaternion (default in xy plane)
    static void drawCircle(video::IVideoDriver* driver,
                           double radius,
                           chrono::ChCoordsys<> mpos = chrono::CSYSNORM,
                           video::SColor mcol = video::SColor(255, 0, 0, 0),
                           int mresolution = 36,
                           bool use_Zbuffer = false);

    /// Easy-to-use function to draw a spring in 3D space, with given color.
    /// Specify the radius, the end points in absolute space, the resolution (i.e.
    /// the number of segments approximating the helix) and the number of turns.
    static void drawSpring(video::IVideoDriver* driver,
                           double radius,
                           chrono::ChVector<> start,
                           chrono::ChVector<> end,
                           video::SColor mcol = video::SColor(255, 0, 0, 0),
                           int mresolution = 65,
                           double turns = 5,
                           bool use_Zbuffer = false);

    /// Easy-to-use function to draw grids in 3D space, with given orientation,
    /// color and spacing.
    static void drawGrid(video::IVideoDriver* driver,
                         double ustep = 0.1,
                         double vstep = 0.1,
                         int nu = 20,
                         int nv = 20,
                         chrono::ChCoordsys<> mpos = chrono::CSYSNORM,
                         video::SColor mcol = video::SColor(50, 80, 110, 110),
                         bool use_Zbuffer = false);

    /// --
    static void drawPlot3D(video::IVideoDriver* driver,
                           chrono::ChMatrix<> X,  // x of points, in local csys x
                           chrono::ChMatrix<> Y,  // y of points, in local csys y
                           chrono::ChMatrix<> Z,  // z height map of points, in local csys z
                           chrono::ChCoordsys<> mpos = chrono::CSYSNORM,
                           video::SColor mcol = video::SColor(50, 80, 110, 110),
                           bool use_Zbuffer = false);
};

}  // END_OF_NAMESPACE____

#endif


text:
require File.dirname(__FILE__) + '/../property_helper'

class SetElementSampleProblem < Gecode::Model
  attr :sets
  attr :set
  attr :target
  attr :index

  def initialize
    @sets = set_var_array(3, [], 0..20)
    @set = set_var([], 0...3)
    @target = set_var([], 0..20)
    @index = int_var(0...3)
    branch_on wrap_enum([@index])
    branch_on @sets
  end
end

# Requires everything that composite behaviour spec requires in addition to
# @stub and @expect_constrain_equal .
describe 'element constraint', :shared => true do
  it 'should not disturb normal array access' do
    @sets[0].should be_kind_of(Gecode::SetVar)
  end
end

describe Gecode::SetEnum::Element, ' (int operand)' do
  include GecodeR::Specs::SetHelper

  before do
    @model = SetElementSampleProblem.new
    @sets = @model.sets
    @target = @set = @model.target
    @index = @model.index
    @model.branch_on @model.wrap_enum([@set])
    @stub = @sets[@index]

    @property_types = [:set_enum, :int]
    @select_property = lambda do |set_enum, int|
      set_enum[int]
    end
    @selected_property = @sets[@index]
    @constraint_class = Gecode::BlockConstraint
  end

  it 'should not disturb normal array access' do
    @sets[0].respond_to?(:to_set_var).should be_true
  end

  it 'should constrain the specified element of an enum of sets' do
    @sets[@index].must_be.superset_of([5,7,9])
    @model.solve!
    @sets[@index.value].value.should include(5,7,9)
  end

  it 'should translate into a element constraint' do
    Gecode::Raw.should_receive(:element)
    @sets[@index].must_be.superset_of([5,7,9])
    @model.solve!
  end

  it_should_behave_like 'element constraint'
  it_should_behave_like(
    'property that produces set operand by short circuiting equality')
end

describe Gecode::SetEnum::Element, ' (set operand)' do
  before do
    @model = SetElementSampleProblem.new
    @sets = @model.sets
    @set = @model.set
  end

  it 'should produce a selected set operand' do
    @sets[@set].should be_respond_to(:to_selected_set)
  end
end


text:
/* global Image */
import IMAGE_STATUS from './ImageLoadStatus';
import ImageLoadLocker from './ImageLoadLocker';

const defaultOptions = {
  minRetry: 0,
  maxRetry: 0,
  expiry: 0,
  // set noops as default for events
  onStatusChange: () => null,
  onRetry: () => null,
  onReset: () => null,
  onTimeout: () => null,
};

/**
 * Default factory to test for image
 *
 * @param {String} url
 * @param {function} resolve
 * @param {function} reject
 */
const defaultImageFactory = (url, resolve, reject) => {
  const img = new Image();
  img.onload = resolve;
  img.onerror = reject;
  img.src = url;
};

class ImageLoadActionHandler {
  constructor(options, factory = defaultImageFactory) {
    this.options = { ...defaultOptions, ...options };
    this.factory = factory;
  }

  /**
   * Entry point to the main loop
   *
   * @param {String} url - URL to load
   * @return {Promise}|{null} - Promise, or null if not able to attempt
   */
  loadImage(url) {
    // If retry is disabled
    if (!this.options.minRetry) {
      return null;
    }

    // Attempt to lock this url, but return if already locked by another process
    if (!ImageLoadLocker.lock(url)) {
      return null;
    }

    return this.loadImageLoop(url, this.options.minRetry);
  }

  /**
   * Attempt request to asset
   *
   * @param {String} url - URL to load
   * @param {Number} retryAfter - Delay after which we should retry, if this fails
   * @return {Promise}
   */
  loadImageLoop(url, retryAfter) {
    // Set status to loading
    this.options.onStatusChange(url, IMAGE_STATUS.LOADING);

    // Begin loading image
    return new Promise((resolve, reject) => this.factory(url, resolve, reject))
      .then(() => this.handleSuccess(url))
      .catch(() => this.handleError(url, retryAfter));
  }

  /**
   * Mark a file as reset (default status)
   *
   * @param {String} url
   * @param {Function} resolve - Resolution handler for promise
   */
  handleReset(url, resolve) {
    this.options.onReset(url);
    resolve();
  }

  /**
   * Setup a timeout delay and trigger an event
   *
   * @param {Function} callback
   * @param {Number} delay
   * @return {Number} id
   */
  handleTimeout(callback, delay) {
    const id = setTimeout(callback, delay);
    this.options.onTimeout(id, delay);
    return id;
  }

  /**
   * When we have finally loaded an image
   *
   * @param {String} url
   */
  handleSuccess(url) {
    // Unlock after success
    ImageLoadLocker.unlock(url);
    this.options.onStatusChange(url, IMAGE_STATUS.SUCCESS);
  }

  /**
   * When we have exhausted all possible attempts mark as failed
   *
   * @param {String} url
   * @return {Promise|null}
   */
  handleFailure(url) {
    // Unlock after final failure
    ImageLoadLocker.unlock(url);
    this.options.onStatusChange(url, IMAGE_STATUS.FAILED);

    // Allow failure to expire if configured
    if (this.options.expiry) {
      return new Promise((resolve) => {
        this.handleTimeout(
          () => this.handleReset(url, resolve),
          this.options.expiry * 1000
        );
      });
    }

    // Otherwise, stop further attempts
    return null;
  }

  /**
   * On failure we want to temporarily mark as failed, and retry later
   *
   * @param {String} url
   * @param {Number} retryAfter
   * @return {Promise}|{null}
   */
  handleError(url, retryAfter) {
    // Check if we should expire
    if (retryAfter > this.options.maxRetry) {
      return this.handleFailure(url);
    }

    // Set waiting status during timeout
    this.options.onStatusChange(url, IMAGE_STATUS.WAITING);

    // Wait for the specified retryAfter seconds, then repeat the loop
    // with a new retryAfter
    return this.handleRetry(url, retryAfter);
  }

  /**
   * Begin a retry
   *
   * @param {String} url - URL to load
   * @param {Number} retryAfter - Number of seconds to retry after
   * @return {Promise}
   */
  handleRetry(url, retryAfter) {
    const promise = new Promise((resolve) => {
      this.handleTimeout(
        () => resolve(this.loadImageLoop(url, retryAfter * 2)),
        retryAfter * 1000
      );
    });
    this.options.onRetry(url, retryAfter, promise);
    return promise;
  }

  /**
   * Register event for a retry being started
   *
   * @param {Function} callback
   */
  setOnRetry(callback) {
    this.options.onRetry = callback;
  }

  /**
   * Register event for a file being reset
   *
   * @param {Function} callback
   */
  setOnReset(callback) {
    this.options.onReset = callback;
  }

  /**
   * Register event for a status change
   *
   * @param {Function} callback
   */
  setOnStatusChange(callback) {
    this.options.onStatusChange = callback;
  }

  /**
   * Register event for a tick action
   *
   * @param {Function} callback
   */
  setOnTimeout(callback) {
    this.options.onTimeout = callback;
  }
}

export { defaultImageFactory };

export default ImageLoadActionHandler;


text:
FROM y12elk/base
MAINTAINER Y12STUDIO <y12studio@gmail.com>

# add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added
RUN groupadd -r elk && useradd -r -g elk elk

RUN apt-get -y update
# Install dependencies
RUN apt-get install -yq openjdk-7-jre-headless
#
# Install ElasticSearch.
#
RUN wget -qO- https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.3.2.tar.gz | tar xvz -C /tmp &&\
    mv /tmp/elasticsearch-* /opt/elasticsearch && chown elk:elk /opt/elasticsearch

ENV ES_RUN /etc/service/elasticsearch/run
ADD elasticsearch.sh $ES_RUN
RUN chmod +x $ES_RUN
#
# Install kibana
#
RUN wget -qO- https://download.elasticsearch.org/kibana/kibana/kibana-3.1.0.tar.gz | tar xvz -C /tmp &&\
    mv /tmp/kibana-* /opt/kibana && chown www-data:www-data /opt/kibana
#
# Install nginx
#
RUN apt-get install -yq nginx
ENV NGINX_RUN /etc/service/nginx/run
ADD nginx.sh $NGINX_RUN
RUN chmod +x $NGINX_RUN
ADD nginx.conf /etc/nginx/nginx.conf

#
# update kibana default route schema json file
#
# RUN cd /opt/kibana/app/dashboards && cp default.json default.json.bak
# ADD kibana.json /opt/kibana/app/dashboards/default.json

#
# logstash conf
#
ADD nginx.pattern /opt/logstash/patterns/nginx
RUN /opt/srvtool.sh -y logstash
RUN /opt/srvtool.sh -y collectd
ADD logstash.conf $LS_CONF

RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
CMD ["/sbin/my_init"]


text:
namespace osm {

// Dans la spec OSM, les lat/lon sont representees en degres avec 7 digits
//      http://wiki.openstreetmap.org/wiki/Node
// Or [-180°,180°]/1.0e-7 tient dans 32 bits. On represente donc partout les
// lat/lon en virgule fixe (entier) avec un LSB de 10^-7, ce qui occupe 32bits
// au lieu de 64bits pour un double (32b pour un float, mais imprecis a 1.0e-7)
// L'intervalle canonique de latitude est  [ -90, 90]
// L'intervalle canonique de longitude est [-180,180]
typedef int32_t latlon_t;

static double const latlon_lsb = 1.0e-7;

inline double degree (latlon_t g) { return (double) g * latlon_lsb; }
inline double latlon (double g)   { return (double) g * latlon_lsb; }

// Normalisation dans les intervalles transformables en virgule fixe
inline double canonicalDeg (double g)
{
  g = fmod (g, 360.0);
  if (g >= 180.0) g -=360; else if (g < -180.0) g +=360;
  return g;
}

struct LatLon
{
  latlon_t lat, lon;
  inline double degLat(void) { return degree (lat); }
  inline double degLon(void) { return degree (lon); }
};

// Un pave rectangulaire de lat/lon
class LatLonBox
{
public:
  LatLon min, max;

  // Tout le domaine
  inline void open (void)
  { min.lat = min.lon = -LATLONMAX;
    max.lat = max.lon =  LATLONMAX;
  }

  // Vide
  inline void close (void)
  { min.lat = min.lon =  LATLONMAX;
    max.lat = max.lon = -LATLONMAX;
  }

  // Etendre le pave pour qui'il contienne le point donne
  // + close() is the required initial state
  inline void extend (LatLon &ll)
  {
    if (ll.lat < min.lat) min.lat = ll.lat;
    if (ll.lat > max.lat) max.lat = ll.lat;
    if (ll.lon < min.lon) min.lon = ll.lon;
    if (ll.lon > max.lon) max.lon = ll.lon;
  }

  // C# put/get is better ...
  inline double degMinLat(void) { return degree (min.lat); }
  inline double degMaxLat(void) { return degree (max.lat); }
  inline double degMinLon(void) { return degree (min.lon); }
  inline double degMaxLon(void) { return degree (max.lon); }

private:
  static const latlon_t LATLONMAX = 180*10000000;
};

// Un niveau de zoom : cela va de 0 a 17
typedef unsigned zoom_t;

// Un identifiant d'element de fichier OSM / XML
// Cela n'est pas propre a OSM mais est defini par XML comme occupant au plus 0..2^63-1
// + Compile sur GCC 4.5 32bits, a la lecture de "rhone-alpes.osm" (2.4Go) gprof affirme
//   que strtoull occupe 15% du temps de lecture
//   Les std::map::find de id_t sont le premier poste de cout pour gprof
//   Donc il peut y avoir un interet de perfo a rester sur 32 bits ... qui semble suffisant
//   dans les fichiers OSM vus (en 2011, mais la croissance est exponentielle)

#ifndef OSM_ID32
  typedef uint64_t id_t;        // unsignedLong XML, "API v0.6/XSD" conformant
#else
  typedef uint32_t id_t;        // RAM is expensive ...
#endif

// Les trois types elements d'un OSM : Node, Way, Relation
enum eltType { eltNode, eltWay, eltRelation };

// Noms de proprietes usuelles
// + Le format OSM permet de stocker n'importe quel tags "key=value", neanmoins
//   l'usage prevoit certains "key" :
//      http://wiki.openstreetmap.org/wiki/Map_Features
//   Quelques uns potentiellement utiles au rendu sont regroupes ici
// Bof: Cela pourrait etre fastidieux. La methode osmarender est preferable :
//   Un fichier lu au demarrage contient une association entre "key=value" et
//   une caracteristique de rendu, son LoD minimal, etc.
//   Mais cela melangerait l'objet et son rendu ... donc on se contente ici
//   de memoriser des chaines de caracteres usuelles, pour perfos (memoire,
//   int==int au lieu de strcmp, etc ?)
//
enum commonTag
{
  tagNil = 0,
  tagHighway,
      tagMotorway, tagMotorwayLink, tagTrunk, tagTrunkLink, tagPrimary,
      tagPrimaryLink,
  tagTrafficCalming,
  tagService,
  tagBoundary,
      tagAdministrative, tagCivil, tagPolitical, tagMaritime,

  // Nombre de chaines predefinies
  tagCommonCount
};

//extern XML_Char *commonTagStr[(int) tagCommonCount];

union tagString         // UTF-8  (char compatible)
{
  enum commonTag index;        // Valid only if < tagStringCount
  const char    *pntr;

  inline const char *str(void)
//{ return ((unsigned) index < tagCommonCount) ? commonTagStr[index] : pntr; }
  { return pntr; }
};

struct tagPair
{
  union tagString key, value;
};

// Ensemble de proprietes d'un element
// + C'est assez cher en RAM, alors il ne faut le mettre que dans les elements qui
//   en ont besoin et non pas dans tous (IElement).
//   Compte des Elements sans nom ou avec nom, dans quelques OSM :
//     "rhone-alpes.osm" :    poorNode= 11M  richNode= 17k
//                            poorWay =1.4M  richWay = 68k
//                            poorRel =2.9k  richRel = 10k
//     "ile-de-france.osm" :  poorNode=8.2M  richNode= 19k
//                            poorWay =1.1M  richWay =101k
//                            poorRel = 12k  richRel =4.7k
//   Le resultat change radicalement si on compte avec/sans tag (nom ou autre)
//     "rhone-alpes.osm" :    poorNode= 11M  richNode=846k
//                            poorWay =3.4k  richWay =1.4k
//                            poorRel =   0  richRel = 13k
//     "ile-de-france.osm" :  poorNode=7.8M  richNode=472k
//                            poorWay =3.1k  richWay =1.2M
//                            poorRel =   1  richRel = 17k
//   Mais la proportion de Node sans tag justifie que l'on specialise la classe Node
//   en "avec" ou "sans" tag.
class Tags
{
public:
  // May have a ctor : is not un IElement, no ctor will be called by large containers
  Tags() { Init(); }

  // Usual tags
  char *name;         // Not so usual ?  (UTF-8)
  char layer;         // -5 .. 5,  0 == au sol, -1 == tunnel, etc

  enum Kind
  {
    unknown,
    building,
    highway,
    waterway,
    railway
  } kind;

  unsigned short count;     // Stats : nombre de tags, nom compris

  // Discovered tags
  // + L'examen de quelques OSM montre que de nombreux tags non documentes existent ...
  // TODO: liste de chaines "Atom" : faire une map string->index et in vector index->string
  //       des chaines trouvees.
  //       initialiser cette map/vector avec les chaines predefinies par la "spec" d'emploi
  //       d'OSM ("highway", etc), de sorte qu'elles soient reconnues par le code par un enum
  //       connu a la compilation.
  //       Pour les chaines "nom de propriete" : ok
  //       Pour les chaines "valeur de propriete" : la valeur est a stocker dans sa traduction
  //       binaire plutot que comme une chaine
  std::vector<struct tagPair> pairs;    // ou *pairs pour eviter un ctor systematique ?

  inline void Init (void)
  { name = NULL; layer = 0; kind = unknown; count = 0; }

  inline bool isEmpty (void)
  { return (name == NULL) && (pairs.size() == 0); }

private:
};

extern Tags nilTags;   // Always empty

// Classe racine des elements OSM Node, Way, Relation
// + Aucun IElement et derives n'a pas de constructeur pour eviter des
//   inits volumineuses inutiles quand un Element est dans un conteneur
//   comme std::vector
// + Au sujet de la presence ou non de tags, qui sont cher a enregistrer
//   donc pour lesquels il vaudrait mieux avoir une race sans tag et une race
//   avec, au moins les Node qui sont majoritairement sans tag.
//   Cela compliquerait la taxonomie des Elements, imposerait peut etre
//   un double heritage pour ne pas dupliquer la classe Node, ajouterait
//   une memoire des Node avec et sans, un cas de plus a eltType, etc.
//   Alternative: n'enregistrer que les Node possedant un tag, et stocker
//   dans un Way directement la latlon de ses Node.
//   Un Node tagge reference par un Way est a la fois dans la table des Node
//   et sa latlon est copiee dans le Way (ou les Way).
//   On suppose en effet que les tags d'un Node n'ont pas d'utilite pour le Way,
//   qui possede les siens propres.
//
// Exemples vus :
//   + un Way qui est un building, reference des Node dont l'un possede
//     un tag : celui qui represente la porte d'entree avec le numero d'adresse
//     du batiment a le tag "addr:housenumber", et le Way lui-meme n'a pas cette
//     info ...
//     Pour supporter ces cas, il faut que les Way referencent les Node. Et pour
//     ne pas gacher la RAM, il faut que deux classes Node existent, Poor et Rich.
//     Ou alors il faut copier les tags des Node d'un Way dans le Way lui-meme.
//   + Idem avec le Way building "Musee d'Orsay" dont un Node represente l'horloge
//     murale qu'il porte.
//   + Un Relation reduite a un Node. La Relation possede des tags (permettant le
//     rendu), de sorte que le Node n'a pas besoin de tag (et n'en a pas)
//
// Hierarchies possibles :
//   IElement                    IElement
//     PoorNode-->Node             ITaggedElement
//     ITaggedElement                Node  (*have* tags)
//       RichNode-->Node             Way  (holds latlon's)
//       Way (holds indexes)         Relation
//       Relation
//   Node
//
//   Bof: il ne sert a rien de memoriser un PoorNode, en tout cas pour un Way. Autant
//        memoriser les latlon dans le Way. Quid des Relation qui detiennent des PoorNode ?
//   => Il semble complique d'eloigner les IElement des capacites effectives du format OSM

class IElement
{
public:
  // unique ID value of this OSM Element
  // + Using an inline function has no cost and enables user code syntatic
  //   independance of ODM_ID_STORED
#ifdef OSM_ID_STORED
  inline id_t id (void) const { return mID; };
#else
  inline id_t id (void) const { return 0; };   // 0 is not a valid OSM ID
#endif

  inline virtual void Init()
  {
#ifdef OSM_ID_STORED
    mID = 0;
#endif
  }

  // Type d'element Node / Way / Relation
  inline virtual eltType type (void) const = 0;

  // "Est capable de stocker des tags"
  inline virtual bool tagCapable (void) const
  { return false; }

  inline virtual const Tags& tags (void) const
  { return nilTags; }

  // "Possede au moins un tag" (qui peut etre par exemple "name")
  // + Always false if !tagCapable()
  inline virtual bool hasTag (void) const
  { return false; }

//protected:
#ifdef OSM_ID_STORED
  id_t mID;           // Identifiant unique (dans un fichier ou pour tous ?)
#endif
};

// OSM Element that can store Tags
class ITaggedElement : public IElement
{
public:
  inline virtual const Tags& tags (void) const
  { return *mTags; }

  inline virtual void Init()
  {
#ifdef OSM_ID_STORED
    mID = 0;
#endif
    mTags = &nilTags;
  }

  // "Est capable de stocker des tags"
  inline virtual bool tagCapable (void) const
  { return true; }

  inline virtual bool hasTag (void) const
  { return ! mTags->isEmpty(); }

//protected:
  // A Tags object (set of tags) is much larger than a (void *), so we store
  // it only then at least one tag exists
  Tags *mTags;
};

// Image en memoire d'un fichier OSM, ou de plusieurs accumules
// + Les liens qu'entretiennent entre eux Node, Way et Relation sont designes
//   par les IDs XML dans le fichier OSM. Ici en memoire, on compile ces liens
//   par des index directs. Donc la representation de ces elements est liee a
//   leur presence au sein de OSMData, raison pour laquelles ces classes sont
//   inclues dans OSMData et pas externe.
//   Par exemple, un index de Node n'a de sens que parce que les nodes sont
//   contenus dans un std::vector de OSMData
//   Pourquoi pas un pointeur plutot qu'un index ? Parce que ces conteneurs
//   dynamiquemlent agrandis lors de la lecture ne garantissent pas que l'adresse
//   des objets contenus est inchangee (ils contiennent des valeurs, pas des
//   "objets").

class OSMData
{
public:
  OSMData();
  ~OSMData();

  // Lire un fichier OSM (XML)
  // + Les fichiers OSM comprimes en ".bz2" ou ".gz" sont admis
  // + Les donnees sont ajoutees a l'existant, il est permis d'appeler LoadText
  //   plusieurs fois.
  //   Si un element Node/Way/Relation est deja charge, le second est ignore
  // + Un fichier OSM "naturel" contient la totalite des infos de sa region, a
  //   l'echelle la plus fone (zoom 17). Ils peuvent donc etre tres grand.
  //   Par exemple, "rhone-alpes.osm" en 2011/01 pese 2.4Go (163Mo en bz2)
  //   Il y a donc des version de LoadText pour ne charger qu'une partie filtree
  //   sur un domaine geographique, ou pour un niveau de zoom defini
  //
  // TODO: facteur de zoom, pour ne pas charger des details inutiles si
  //       cet OSM est destine a produire une vue de zoom faible, etc.
  // TODO: PBF reader
  void LoadText (const char *filename);
  void LoadText (const char *filename, LatLonBox &clip);

  // Quelques statistiques de dernier appel a LoadText
  // - Nombre d'elements Node/Way/Relation designes mais absents
  //   (l'absence peut etre due au filtrage demande)
  //   Ceci peut arriver si un OSM contient des "references en avant",
  //   i.e. un Way dont les Node seraient decrits apres le Way.
  //   L'exament de quelques fichiers montre que ceci est negligeable
  //   et le lecteur fonctionne donc en une seule passe
  //   TODO: sinon ecrire un LoadText qui recompile ensuite au format
  //         canonique
  unsigned m_badrefwn,       // Node inconnu reference par un Way
           m_badrefr;        // Element inconnu reference par un Relation
  LatLonBox m_filebound;     // Limites annoncees par le fichier
  LatLonBox m_loadbound;     // Limites du domaine effectivement charge

  // Evaluer les limites effectives de ce qui est charge
  // Bof: systematique lors du Load(), toute appli en aura besoin inutile
  //      d'economiser cela
//void ComputeBound ();

  // Un Node
  // + C'est un simple point sur la carte, qui peut faire partir d'un autre element
  // + Il peut etre tag-capable, auquel cas dans cette version 'riche', un Way memorise
  //   un index de Node, ce qui lui permet d'acceder aux eventuels tags de son Node qui
  //   pourraient affecter son rendu. Par contre c'est assez cher en RAM alors que la
  //   majorite des Node n'ont pas de tag. Donc :
  // + Il peut etre tag-incapable, auquel cas un Way memorise

#ifdef OSM_NODE_TAGGED
  class Node : public ITaggedElement
#else
  class Node : public IElement
#endif
  {
  public:
    inline eltType type (void) const { return eltNode; }

    // A Node is only a Lat/Lon and zero or some tags.
    LatLon pos;

    // Definition a partir des chaines lat="" et lon="" du OSM/XML
    // + gprof prouve que ceci est un des principaux consomateurs de CPU au
    //   chargement aussi est-il inline avec un "atoi()" dedie
    //   Le temps de LoadText passe ainsi de 75s a 67s sur "rhone-alpes.osm"
    inline void set (const char *latimg, const char *lonimg)
    { pos.lat = fixedlatlon (latimg);
      pos.lon = fixedlatlon (lonimg);
    }

//  inline void set (double latdeg, double londeg)
//  { pos.lat = latlon (canonicalDeg(latdeg));
//    pos.lon = latlon (canonicalDeg(londeg));
//  }
  };

  // NB: Le cout memoire de ce double heritage est supportable
  //     Le sizeof() est juste la somme des deux classes meres
  //     Ce sont juste les VTable qui doivent se compliquer ?

//class PoorNode : public Node, public IElement
//{
//  inline eltType type (void) { return eltNode; }
//};

//class RichNode : public Node, public ITaggedElement
//{
//  inline eltType type (void) { return eltNode; }
//};

  // Un Way
  // + C'est un ensemble ordonne de Node, formant un ligne ou delimitant une aire

  class Way : public ITaggedElement
  {
  public:
    inline eltType type (void) const { return eltWay; }

    // "the same node is at first and last"
    // + So it is an area, event if no tag tells it ?
    inline bool isLoop(void) const
    { return nodesIx.front() == nodesIx.back(); }

    // Index des Node constituant le Way
    // + nodesIx[i] == -1 si le Node i n'a pas pu etre trouve a partir
    //   de son ID.
    //   Ceci est une provision, en l'etat actuel un tel Node n'est plus
    //   conserve dans le Way. En effet, le cas ne se presente pas dans les
    //   fichiers OSM testes
    // + On a couramment plus de 2^16 Nodes dans un fichier, donc pas possible
    //   de stocker ces index sur un short
    std::vector<int> nodesIx;      // Indexes in m_nodes (-1 if unknown)

    // TODO: est-il utile de garder un pointeur vers les Node et leurs Tags ?
    //       reproduire ici la lat/lon ne suffit-il pas ? Un Node est rarement
    //       partage par plusieurs Way, et les Nodes d'un Way possedent-ils des
    //       Tags propres a heriter vers le Way ?
    //       Un node = 2 x mot-32, un ptr = 1 mot-32
  };

  // Un Relation
  // + C'est un ensemble de Node, de Way, et de Relation  (resursif)

  class Relation : public ITaggedElement
  {
  public:
    inline eltType type (void) const { return eltRelation; }

    struct Member       // Un pointeur + RTTI suffirait prendrait moins de place ?
    {
      eltType elt;
      int     ix;
    };
    std::vector<Member> eltIx;       // Indexes (-1 if unknown)
  };

#if 0
  template<class E>
    class SetOf
    {
      std::vector<E>    m_elts;         // Liste des objets E
      std::map<id_t,unsigned> m_idmap;  // Trouver l'indice dans m_elts suivant E.id
      void registerID (id_t);
    };
  SetOf<Node>        m_toto;
#endif

  // Les ensembles d'objets lus
  // + Il y a un vector pour chacun des 3 types d'elements,
  //   plus une map pour convertir "id XML" -> "index dans le vector"
  //   Seuls les elements entres dans le vector ont une entree dans la map
  //   donc l'index enregistre en map est toujours defini ([0..zize-1])
  //   L'ordre des elements dans un vector n'est pas particulier (c'est celui
  //   du fichier OSM)
  // + Pour resoudre des references en avant, il faudrait noter dans la map
  //   un index=-1, et lorsque l'element est enfin defini et qu'on voit qu'il
  //   est deja en map avec -1, alors il faudrait parcourir les hotes possibles
  //   (Way et Relation) et corriger, ce qui imposerait de stocker aussi les
  //   IDs (64bits) des membres des Way/Relation.
  //   => On fait l'impasse. Il apparait sur les OSM testes qu'il n'existe pas
  //      de reference en avant.
  //      Par ailleurs le nombre de Node non reference, bien que non nul, est
  //      negligeable face a la totalite.
  // + TODO: template pour cette paire vector/map ?

  std::vector<Node>       m_nodes;         // Liste des Node
  std::map<id_t,unsigned> m_idnodes;       // Map id -> index dans m_nodes

  std::vector<Way>        m_ways;          // Liste des Way
  std::map<id_t,unsigned> m_idways;        // Map id -> index dans m_nodes

  std::vector<Relation>   m_relations;     // Liste des Relation
  std::map<id_t,unsigned> m_idrelations;   // Map id -> index dans m_nodes

public:
  int findNodeIx (id_t id);
  int findWayIx (id_t id);
  int findRelationIx (id_t id);
  int findIx (eltType elt, id_t id);

private:
//struct ParserContext          // Si ceci s'avere volumineux
//{
    XML_Parser m_parser;
    ITaggedElement *m_curelt;
    bool m_inway, m_inrel;
//};
//ParserContext *m_ctx;
//

  inline void newNode (const XML_Char **atts);
  inline void endNode (void);
  inline void newWay  (const XML_Char **atts);
  inline void newND   (id_t id);
  inline void endWay  (void);
  inline void newRelation (const XML_Char **atts);
  inline void newMember (id_t id, enum eltType elt, const XML_Char *role);
  inline void endRelation (void);
  inline void addTag (const XML_Char *key, const XML_Char *value);
public: // really private
  void startElementHandler (const XML_Char *name, const XML_Char **atts);
  void endElementHandler (const XML_Char *name);

private:
  static latlon_t fixedlatlon (const char *str);      // strtoul() "optimise"

};

}  // namespace osm

#endif


text:
package com.fsck.k9.message.html;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

public class BitcoinUriParserTest {
    BitcoinUriParser parser = new BitcoinUriParser();

    @Test
    public void basicBitcoinUri() throws Exception {
        assertValidUri("bitcoin:19W6QZkx8SYPG7BBCS7odmWGRxqRph5jFU");
    }

    @Test
    public void bitcoinUriWithAmount() throws Exception {
        assertValidUri("bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2");
    }

    @Test
    public void bitcoinUriWithQueryParameters() throws Exception {
        assertValidUri("bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2" +
                "&message=Payment&label=Satoshi&extra=other-param");
    }

    @Test
    public void uriInMiddleOfInput() throws Exception {
        String prefix = "prefix ";
        String uri = "bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2";
        String text = prefix + uri;

        UriMatch uriMatch = parser.parseUri(text, prefix.length());

        assertUriMatch(uri, uriMatch, prefix.length());
    }

    @Test
    public void invalidScheme() throws Exception {
        assertInvalidUri("bitcion:19W6QZkx8SYPG7BBCS7odmWGRxqRph5jFU");
    }

    @Test
    public void invalidAddress() throws Exception {
        assertInvalidUri("bitcoin:[invalid]");
    }

    private void assertValidUri(String uri) {
        UriMatch uriMatch = parser.parseUri(uri, 0);
        assertUriMatch(uri, uriMatch);
    }

    private void assertUriMatch(String uri, UriMatch uriMatch) {
        assertUriMatch(uri, uriMatch, 0);
    }

    private void assertUriMatch(String uri, UriMatch uriMatch, int offset) {
        assertNotNull(uriMatch);
        assertEquals(offset, uriMatch.getStartIndex());
        assertEquals(uri.length() + offset, uriMatch.getEndIndex());
        assertEquals(uri, uriMatch.getUri().toString());
    }

    private void assertInvalidUri(String text) {
        UriMatch uriMatch = parser.parseUri(text, 0);
        assertNull(uriMatch);
    }
}


text:
package paths

import (
	"errors"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strings"
)

// FilePathSeparator as defined by os.Separator.
const FilePathSeparator = string(filepath.Separator)

// filepathPathBridge is a bridge for common functionality in filepath vs path
type filepathPathBridge interface {
	Base(in string) string
	Clean(in string) string
	Dir(in string) string
	Ext(in string) string
	Join(elem ...string) string
	Separator() string
}

type filepathBridge struct {
}

func (filepathBridge) Base(in string) string {
	return filepath.Base(in)
}

func (filepathBridge) Clean(in string) string {
	return filepath.Clean(in)
}

func (filepathBridge) Dir(in string) string {
	return filepath.Dir(in)
}

func (filepathBridge) Ext(in string) string {
	return filepath.Ext(in)
}

func (filepathBridge) Join(elem ...string) string {
	return filepath.Join(elem...)
}

func (filepathBridge) Separator() string {
	return FilePathSeparator
}

var fpb filepathBridge

// ToSlashTrimLeading is just a filepath.ToSlash with an added / prefix trimmer.
func ToSlashTrimLeading(s string) string {
	return strings.TrimPrefix(filepath.ToSlash(s), "/")
}

// MakeTitle converts the path given to a suitable title, trimming whitespace
// and replacing hyphens with whitespace.
func MakeTitle(inpath string) string {
	return strings.Replace(strings.TrimSpace(inpath), "-", " ", -1)
}

// ReplaceExtension takes a path and an extension, strips the old extension
// and returns the path with the new extension.
func ReplaceExtension(path string, newExt string) string {
	f, _ := fileAndExt(path, fpb)
	return f + "." + newExt
}

func makePathRelative(inPath string, possibleDirectories ...string) (string, error) {
	for _, currentPath := range possibleDirectories {
		if strings.HasPrefix(inPath, currentPath) {
			return strings.TrimPrefix(inPath, currentPath), nil
		}
	}
	return inPath, errors.New("can't extract relative path, unknown prefix")
}

// Should be good enough for Hugo.
var isFileRe = regexp.MustCompile(`.*\..{1,6}$`)

// GetDottedRelativePath expects a relative path starting after the content directory.
// It returns a relative path with dots ("..") navigating up the path structure.
func GetDottedRelativePath(inPath string) string {
	inPath = filepath.Clean(filepath.FromSlash(inPath))

	if inPath == "." {
		return "./"
	}

	if !isFileRe.MatchString(inPath) && !strings.HasSuffix(inPath, FilePathSeparator) {
		inPath += FilePathSeparator
	}

	if !strings.HasPrefix(inPath, FilePathSeparator) {
		inPath = FilePathSeparator + inPath
	}

	dir, _ := filepath.Split(inPath)

	sectionCount := strings.Count(dir, FilePathSeparator)

	if sectionCount == 0 || dir == FilePathSeparator {
		return "./"
	}

	var dottedPath string

	for i := 1; i < sectionCount; i++ {
		dottedPath += "../"
	}

	return dottedPath
}

// ExtNoDelimiter takes a path and returns the extension, excluding the delimiter, i.e. "md".
func ExtNoDelimiter(in string) string {
	return strings.TrimPrefix(Ext(in), ".")
}

// Ext takes a path and returns the extension, including the delimiter, i.e. ".md".
func Ext(in string) string {
	_, ext := fileAndExt(in, fpb)
	return ext
}

// PathAndExt is the same as FileAndExt, but it uses the path package.
func PathAndExt(in string) (string, string) {
	return fileAndExt(in, pb)
}

// FileAndExt takes a path and returns the file and extension separated,
// the extension including the delimiter, i.e. ".md".
func FileAndExt(in string) (string, string) {
	return fileAndExt(in, fpb)
}

// FileAndExtNoDelimiter takes a path and returns the file and extension separated,
// the extension excluding the delimiter, e.g "md".
func FileAndExtNoDelimiter(in string) (string, string) {
	file, ext := fileAndExt(in, fpb)
	return file, strings.TrimPrefix(ext, ".")
}

// Filename takes a file path, strips out the extension,
// and returns the name of the file.
func Filename(in string) (name string) {
	name, _ = fileAndExt(in, fpb)
	return
}

// PathNoExt takes a path, strips out the extension,
// and returns the name of the file.
func PathNoExt(in string) string {
	return strings.TrimSuffix(in, path.Ext(in))
}

// FileAndExt returns the filename and any extension of a file path as
// two separate strings.
//
// If the path, in, contains a directory name ending in a slash,
// then both name and ext will be empty strings.
//
// If the path, in, is either the current directory, the parent
// directory or the root directory, or an empty string,
// then both name and ext will be empty strings.
//
// If the path, in, represents the path of a file without an extension,
// then name will be the name of the file and ext will be an empty string.
//
// If the path, in, represents a filename with an extension,
// then name will be the filename minus any extension - including the dot
// and ext will contain the extension - minus the dot.
func fileAndExt(in string, b filepathPathBridge) (name string, ext string) {
	ext = b.Ext(in)
	base := b.Base(in)

	return extractFilename(in, ext, base, b.Separator()), ext
}

func extractFilename(in, ext, base, pathSeparator string) (name string) {
	// No file name cases. These are defined as:
	// 1. any "in" path that ends in a pathSeparator
	// 2. any "base" consisting of just an pathSeparator
	// 3. any "base" consisting of just an empty string
	// 4. any "base" consisting of just the current directory i.e. "."
	// 5. any "base" consisting of just the parent directory i.e. ".."
	if (strings.LastIndex(in, pathSeparator) == len(in)-1) || base == "" || base == "." || base == ".." || base == pathSeparator {
		name = "" // there is NO filename
	} else if ext != "" { // there was an Extension
		// return the filename minus the extension (and the ".")
		name = base[:strings.LastIndex(base, ".")]
	} else {
		// no extension case so just return base, which willi
		// be the filename
		name = base
	}
	return
}

// GetRelativePath returns the relative path of a given path.
func GetRelativePath(path, base string) (final string, err error) {
	if filepath.IsAbs(path) && base == "" {
		return "", errors.New("source: missing base directory")
	}
	name := filepath.Clean(path)
	base = filepath.Clean(base)

	name, err = filepath.Rel(base, name)
	if err != nil {
		return "", err
	}

	if strings.HasSuffix(filepath.FromSlash(path), FilePathSeparator) && !strings.HasSuffix(name, FilePathSeparator) {
		name += FilePathSeparator
	}
	return name, nil
}

// PathPrep prepares the path using the uglify setting to create paths on
// either the form /section/name/index.html or /section/name.html.
func PathPrep(ugly bool, in string) string {
	if ugly {
		return Uglify(in)
	}
	return PrettifyPath(in)
}

// PrettifyPath is the same as PrettifyURLPath but for file paths.
//     /section/name.html       becomes /section/name/index.html
//     /section/name/           becomes /section/name/index.html
//     /section/name/index.html becomes /section/name/index.html
func PrettifyPath(in string) string {
	return prettifyPath(in, fpb)
}

func prettifyPath(in string, b filepathPathBridge) string {
	if filepath.Ext(in) == "" {
		// /section/name/  -> /section/name/index.html
		if len(in) < 2 {
			return b.Separator()
		}
		return b.Join(in, "index.html")
	}
	name, ext := fileAndExt(in, b)
	if name == "index" {
		// /section/name/index.html -> /section/name/index.html
		return b.Clean(in)
	}
	// /section/name.html -> /section/name/index.html
	return b.Join(b.Dir(in), name, "index"+ext)
}

type NamedSlice struct {
	Name  string
	Slice []string
}

func (n NamedSlice) String() string {
	if len(n.Slice) == 0 {
		return n.Name
	}
	return fmt.Sprintf("%s%s{%s}", n.Name, FilePathSeparator, strings.Join(n.Slice, ","))
}

// FindCWD returns the current working directory from where the Hugo
// executable is run.
func FindCWD() (string, error) {
	serverFile, err := filepath.Abs(os.Args[0])
	if err != nil {
		return "", fmt.Errorf("can't get absolute path for executable: %v", err)
	}

	path := filepath.Dir(serverFile)
	realFile, err := filepath.EvalSymlinks(serverFile)
	if err != nil {
		if _, err = os.Stat(serverFile + ".exe"); err == nil {
			realFile = filepath.Clean(serverFile + ".exe")
		}
	}

	if err == nil && realFile != serverFile {
		path = filepath.Dir(realFile)
	}

	return path, nil
}

// AddTrailingSlash adds a trailing Unix styled slash (/) if not already
// there.
func AddTrailingSlash(path string) string {
	if !strings.HasSuffix(path, "/") {
		path += "/"
	}
	return path
}


text:
<?php
namespace Production\Model;

 use Zend\Db\TableGateway\TableGateway;

 class ProductionActivityTable
 {
     protected $tableGateway;

     public function __construct(TableGateway $tableGateway)
     {
         $this->tableGateway = $tableGateway;
     }

     public function getActivityDetail($id)
     {

         $rowset = $this->tableGateway->select(array('r_time_log_activity_code' => $id));

         $row = $rowset->current();

         return $row;

     }

     public function saveActivity(ProductionActivity $activity)
     {

         $data = array(
             'r_time_log_activity_code' => $activity->activity_id,
             'r_time_log_activity_name'  => $activity->activity_name

         );

        if ($this->getActivityDetail($activity->activity_id))
        {
        $this->tableGateway->update($data, array('r_time_log_activity_code' => $activity->activity_id));
        }
        else
        {
            $this->tableGateway->insert($data);
        }

     }

 }