text:
package com.microsoft.azure.servicebus.amqp;

import org.apache.qpid.proton.engine.BaseHandler;
import org.apache.qpid.proton.engine.EndpointState;
import org.apache.qpid.proton.engine.Event;
import org.apache.qpid.proton.engine.Session;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

public class SessionHandler extends BaseHandler {
    protected static final Logger TRACE_LOGGER = LoggerFactory.getLogger(SessionHandler.class);

    private final String name;

    public SessionHandler(final String name) {
        this.name = name;
    }

    @Override
    public void onSessionRemoteOpen(Event e) {
        TRACE_LOGGER.debug("onSessionRemoteOpen - entityName: {}, sessionIncCapacity: {}, sessionOutgoingWindow: {}", this.name, e.getSession().getIncomingCapacity(), e.getSession().getOutgoingWindow());

        Session session = e.getSession();
        if (session != null && session.getLocalState() == EndpointState.UNINITIALIZED) {
            session.open();
        }
    }

    @Override
    public void onSessionLocalClose(Event e) {
        TRACE_LOGGER.debug("onSessionLocalClose - entityName: {}, condition: {}", this.name, e.getSession().getCondition() == null ? "none" : e.getSession().getCondition().toString());
        freeClosedSession(e.getSession());
    }

    @Override
    public void onSessionRemoteClose(Event e) {
        TRACE_LOGGER.debug("onSessionRemoteClose - entityName: {}, condition: {}", this.name, e.getSession().getCondition() == null ? "none" : e.getSession().getCondition().toString());

        Session session = e.getSession();
        if (session != null && session.getLocalState() != EndpointState.CLOSED) {
            session.close();
        }
        freeClosedSession(session);
    }

    @Override
    public void onSessionFinal(Event e) {
        TRACE_LOGGER.debug("onSessionFinal - entityName: {}", this.name);
    }

    private static void freeClosedSession(Session session) {
    	if (session != null && session.getLocalState() == EndpointState.CLOSED && session.getRemoteState() == EndpointState.CLOSED) {
    		session.free();
    	}
    }

}


text:
layout: post
title:  "totally DRY...but at what cost?"
date:   2017-02-14 21:24:32
categories: wisdom
excerpt: "sometimes it's ok to repeat yourself"
tags:
  - refactoring
---

One of the first things taught in online software developer tutorials is the DRY principle, as in Don't Repeat Yourself.  The fundamental idea is solid: don't repeat processes, don't repeat logic.  Most of all don't copy and paste code.  Less lines are easier to maintain.

This is a great idea and I subscribe.  However, taking it to the extreme can actually have a detrimental impact on readability and therefore on maintainability.  As my career progresses I am starting to see the wisdom in choosing readability over cleverness and pure DRYness.  I would much rather have to debug some software that is easier to read and reason about vs. overly abstracted code.  [I have mentioned this theme before]({{ full_base_url }}/wisdom/2017/01/22/the-concrete-and-the-abstract.html) but I really have been experiencing the impact lately and I want to stress it again.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta charset='utf-8' />
<link href='../dist/fullcalendar.css' rel='stylesheet' />
<link href='../dist/fullcalendar.print.css' rel='stylesheet' media='print' />


text:
module Atmosphere
  module Api
    module V1
      class ApplianceConfigurationInstancesController < Atmosphere::Api::ApplicationController
        load_and_authorize_resource :appliance_configuration_instance,
          class: 'Atmosphere::ApplianceConfigurationInstance'

        respond_to :json

        def index
          respond_with @appliance_configuration_instances.where(filter).order(:id).uniq
        end

        def show
          respond_with @appliance_configuration_instance
        end

        private

        def filter
          filter = super
          appliance_id = params[:appliance_id]
          filter[:atmosphere_appliances] = {id: appliance_id} unless appliance_id.blank?

          filter
        end

        def model_class
          Atmosphere::ApplianceConfigurationInstance
        end
      end
    end
  end
end


text:
.. _config_file:

The Config File
===============

There are several aspects of how PySurfer looks and behaves that you may
wish to customize but do not want to have to alter every time you
instantiate a Brain object or use the command-line interface. To
facilitate this, PySurfer allows you to set certain options with a
standard Python config file.

When a new Brain object is created (either in a script or via the
command-line), it can read configuration options from one of two places:
first, in the local folder in a file called ``surfer.cfg``, and next in
your home directory, from a file called ``.surfer.cfg``. The file is
divided into the following sections:

Visual
------
*background*
    What color the display background should be. (Possible values:
    any HTML color name or 256 color hex code.

*cortex*
    What colormap should be used for the binarized curvature on the
    cortex. (Possible values: any cortical curvature color scheme name.)

*size*
    How large the sides of the display window should be (measured in
    pixels.) When using this option, the window will be square, and
    "size" it will be used for the height and width. (Possible values:
    any positive number.)

*width* and *height*
    The size of the window. This is an alternative to size, allowing
    the width and height to be set independently. (Possible values:
    any positive number.)

*default_view*
    Which view should be shown at the beginning of a visualization
    session. (Possible values: ``lateral``, ``medial``, ``rostral``,
    ``caudal``, ``dorsal``, ``ventral``, ``frontal``, ``parietal``.)

Overlay
-------
*min_thresh*
    What the default minimum threshold should be if not provided when
    calling the :meth:`Brain.add_overlay` method. (Possible values: any
    float, ``robust_min``, ``actual_min``.)

*max_thresh*
    What the default saturation point of the colormap should be if not
    provided when calling the :meth:`Brain.add_overlay` method.
    (Possible values: any float, ``robust_max``, ``actual_max``.)

Options
-------
*logging_level*
    Amount of verbosity to use in outputting status messages.
    (Possible values: ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR``.)


text:
package com.cezarykluczynski.stapi.etl.util.constant;

public class SeriesAbbreviation {

	public static final String TOS = "TOS";
	public static final String TAS = "TAS";
	public static final String TNG = "TNG";
	public static final String DS9 = "DS9";
	public static final String VOY = "VOY";
	public static final String ENT = "ENT";
	public static final String DIS = "DIS";
	public static final String LD = "LD";
	public static final String PIC = "PIC";
	public static final String PRO = "PRO";
	public static final String SNW = "SNW";

}


text:
package org.brixen.bean;

import javax.annotation.ParametersAreNonnullByDefault;

/**
 * Defines the contract for a data transfer object used to construct a <b>Selenium</b> page object that models a
 * drop-down menu.
 */
@SuppressWarnings("UnusedDeclaration")
@ParametersAreNonnullByDefault
public interface DropDownMenuBean extends MenuBean, DynamicControllableBean {
}


text:
package io.undertow.server.handlers;

import io.undertow.conduits.RangeStreamSinkConduit;
import io.undertow.server.ConduitWrapper;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.ResponseCommitListener;
import io.undertow.server.handlers.builder.HandlerBuilder;
import io.undertow.util.ByteRange;
import io.undertow.util.ConduitFactory;
import io.undertow.util.Headers;
import io.undertow.util.Methods;
import io.undertow.util.StatusCodes;
import org.xnio.conduits.StreamSinkConduit;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Handler for Range requests. This is a generic handler that can handle range requests to any resource
 * of a fixed content length i.e. any resource where the content-length header has been set.
 *
 * Note that this is not necessarily the most efficient way to handle range requests, as the full content
 * will be generated and then discarded.
 *
 * At present this handler can only handle simple (i.e. single range) requests. If multiple ranges are requested the
 * Range header will be ignored.
 *
 * @author Stuart Douglas
 */
public class ByteRangeHandler implements HttpHandler {

    private final HttpHandler next;
    private final boolean sendAcceptRanges;

    private static final ResponseCommitListener ACCEPT_RANGE_LISTENER = new ResponseCommitListener() {
        @Override
        public void beforeCommit(HttpServerExchange exchange) {
            if (exchange.getResponseHeaders().contains(Headers.CONTENT_LENGTH)) {
                exchange.getResponseHeaders().put(Headers.ACCEPT_RANGES, "bytes");
            } else {
                exchange.getResponseHeaders().put(Headers.ACCEPT_RANGES, "none");
            }
        }

    };

    public ByteRangeHandler(HttpHandler next, boolean sendAcceptRanges) {
        this.next = next;
        this.sendAcceptRanges = sendAcceptRanges;
    }

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        //range requests are only support for GET requests as per the RFC
        if(!Methods.GET.equals(exchange.getRequestMethod())) {
            next.handleRequest(exchange);
            return;
        }
        final ByteRange range = ByteRange.parse(exchange.getRequestHeaders().getFirst(Headers.RANGE));
        if (range == null || range.getRanges() > 1) {
            if (sendAcceptRanges) {
                exchange.addResponseCommitListener(ACCEPT_RANGE_LISTENER);
            }
            next.handleRequest(exchange);
        } else {

            exchange.addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() {
                @Override
                public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
                    if(exchange.getStatusCode() != StatusCodes.OK ) {
                        return factory.create();
                    }
                    String length = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LENGTH);
                    if (length == null) {
                        return factory.create();
                    }
                    long responseLength = Long.parseLong(length);
                    long start = range.getStart(0);
                    long end = range.getEnd(0);
                    if(start == -1 ) {
                        //suffix range
                        long toWrite = end;
                        if(toWrite >= 0) {
                            exchange.setResponseContentLength(toWrite);
                        } else {
                            //ignore the range request
                            return factory.create();
                        }
                        start = responseLength - end;
                        end = responseLength - 1;
                    } else if(end == -1) {
                        //prefix range
                        long toWrite = responseLength - start;
                        if(toWrite >= 0) {
                            exchange.setResponseContentLength(toWrite);
                        } else {
                            //ignore the range request
                            return factory.create();
                        }
                        end = responseLength - 1;
                    } else {
                        long toWrite = end - start + 1;
                        exchange.setResponseContentLength(toWrite);
                    }
                    exchange.setStatusCode(StatusCodes.PARTIAL_CONTENT);
                    exchange.getResponseHeaders().put(Headers.CONTENT_RANGE, start + "-" + end + "/" + responseLength);
                    return new RangeStreamSinkConduit(factory.create(), start, end, responseLength);
                }
            });
            next.handleRequest(exchange);
        }
    }

    public static class Wrapper implements HandlerWrapper {

        private final boolean sendAcceptRanges;

        public Wrapper(boolean sendAcceptRanges) {
            this.sendAcceptRanges = sendAcceptRanges;
        }

        @Override
        public HttpHandler wrap(HttpHandler handler) {
            return new ByteRangeHandler(handler, sendAcceptRanges);
        }
    }

    public static class Builder implements HandlerBuilder {

        @Override
        public String name() {
            return "byte-range";
        }

        @Override
        public Map<String, Class<?>> parameters() {
            Map<String, Class<?>> params = new HashMap<>();
            params.put("send-accept-ranges", boolean.class);
            return params;
        }

        @Override
        public Set<String> requiredParameters() {
            return Collections.emptySet();
        }

        @Override
        public String defaultParameter() {
            return "send-accept-ranges";
        }

        @Override
        public HandlerWrapper build(Map<String, Object> config) {
            Boolean send = (Boolean) config.get("send-accept-ranges");
            return new Wrapper(send != null && send);
        }
    }

}


text:
typedef NS_ENUM(NSInteger, BNPLanguageType) {
    BNPLanguageTypeALL = 0,
    BNPLanguageTypeEN_US,
    BNPLanguageTypeJA_JP,
    BNPLanguageTypeZH_CN
};

@interface BNPDateExtracter : NSObject

//alloc tree for all lan
-(instancetype)init;
//alloc tree for certain lan
-(instancetype)initWithLanguage:(BNPLanguageType)lan;

+(BNPLanguageType)getSystemLanguageType;
+(BNPLanguageType)getLanguageTypeWithName:(NSString *)local;
+(BNPLanguageType)guessLanguageTypeFromString:(NSString*)content;

//use default language
-(NSArray *)getDateEntitiesFromString:(NSString *)content;
-(NSArray *)getDateEntitiesFromString:(NSString *)content inLanguage:(BNPLanguageType)lang;

@end


text:
package org.kie.workbench.common.stunner.core.client.components.palette.model;

import java.util.List;

public interface HasPaletteItems<I extends PaletteItem> {

    List<I> getItems();
}


text:
id: events-zh-CN
title: 事件系统
permalink: events-zh-CN.html
prev: tags-and-attributes-zh-CN.html
next: dom-differences-zh-CN.html
---

## 合成事件

事件处理程序通过 `合成事件`(`SyntheticEvent`)的实例传递,`SyntheticEvent` 是浏览器原生事件跨浏览器的封装。`SyntheticEvent` 和浏览器原生事件一样有 `stopPropagation()`、`preventDefault()` 接口,而且这些接口夸浏览器兼容。

如果出于某些原因想使用浏览器原生事件,可以使用 `nativeEvent` 属性获取。每个和成事件(`SyntheticEvent`)对象都有以下属性:

```javascript
boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
DOMEventTarget target
number timeStamp
string type
```

> 注意:
>
> React v0.12 中,事件处理程序返回 `false` 不再停止事件传播,取而代之,应该根据需要手动触发 `e.stopPropagation()` 或 `e.preventDefault()`。

## 支持的事件

React 将事件统一化,使事件在不同浏览器上有一致的属性。

下面的事件处理程序在事件冒泡阶段被触发。如果要注册事件捕获处理程序,应该使用 `Capture` 事件,例如使用 `onClickCapture` 处理点击事件的捕获阶段,而不是 `onClick`。

### 剪贴板事件

事件名称:

```
onCopy onCut onPaste
```

属性:

```javascript
DOMDataTransfer clipboardData
```

### 键盘事件

事件名称:

```
onKeyDown onKeyPress onKeyUp
```

属性:

```javascript
boolean altKey
number charCode
boolean ctrlKey
boolean getModifierState(key)
string key
number keyCode
string locale
number location
boolean metaKey
boolean repeat
boolean shiftKey
number which
```

### 焦点事件

事件名称

```
onFocus onBlur
```

属性:

```javascript
DOMEventTarget relatedTarget
```

### 表单事件

事件名称:

```
onChange onInput onSubmit
```

关于 `onChange` 事件的更多信息,参见 [表单组件](/react/docs/forms-zh-CN.html)。

### 鼠标事件

事件名称:

```
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
```

属性:

```javascript
boolean altKey
number button
number buttons
number clientX
number clientY
boolean ctrlKey
boolean getModifierState(key)
boolean metaKey
number pageX
number pageY
DOMEventTarget relatedTarget
number screenX
number screenY
boolean shiftKey
```

### Selection Events

事件名称:

```
onSelect
```

### 触控事件

事件名称:

```
onTouchCancel onTouchEnd onTouchMove onTouchStart
```

属性:

```javascript
boolean altKey
DOMTouchList changedTouches
boolean ctrlKey
boolean getModifierState(key)
boolean metaKey
boolean shiftKey
DOMTouchList targetTouches
DOMTouchList touches
```

### 用户界面事件

事件名称:

```
onScroll
```

属性:

```javascript
number detail
DOMAbstractView view
```

### 滚轮事件

事件名称:

```
onWheel
```

属性:

```javascript
number deltaMode
number deltaX
number deltaY
number deltaZ
```

### Media Events

事件名称:

```
onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting
```

### Image Events

事件名称:

```
onLoad onError
```


text:
package nu.postnummeruppror.insamlingsappen.domain;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Assures that only a single instance of objects that equals is kept in memory.
 *
 * I.e. every instance of the String "android" consume 112 bytes more heap
 * than pointing at an existing object with that value.
 *
 * @author kalle
 * @since 2014-09-07 02:05
 */
public class Intern<T> implements Serializable {

  private static final long serialVersionUID = 1l;

  public Intern() {
  }

  private Map<T, T> map = new HashMap<>();

  public T intern(T value) {
    T interned = map.get(value);
    if (interned == null) {
      getMap().put(value, value);
      interned = value;
    }
    return interned;
  }

  public Map<T, T> getMap() {
    return map;
  }

  public void setMap(Map<T, T> map) {
    this.map = map;
  }
}


text:
<?php

declare(strict_types=1);
namespace JazzTest\Db;

/**
 * DB Test
 */

class SingleConnectionTest extends \JazzTest\AUnit
{
    /**
     * Test single Connection
     */
    public function testRun()
    {
        $db = new \Jazz\Db();
        $db->register(new \Jazz\Db\Connect\Mysql('host', 'db', 'user', 'pw', 1));

        $this->assertEquals(\Jazz\IDb::KEY, $db->getDefault());
        $this->assertInstanceOf(\Jazz\Db\Connect\Mysql::class, $db->getConnection());
        $this->assertInstanceOf(\Jazz\Db\Connect\Mysql::class, $db->getConnection(\Jazz\IDb::KEY));

        $connect = $db->getConnection();
        $this->assertEquals('host', $connect->getHost());
        $this->assertEquals('db', $connect->getDbName());
        $this->assertEquals('user', $connect->getUser());
        $this->assertEquals('pw', $connect->getPassword());
        $this->assertEquals(1, $connect->getPort());
        $this->assertEquals(array(), $connect->getOptions());
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const chalk = require("chalk");
const cli_utils_1 = require("@ionic/cli-utils");
const cordova_1 = require("../lib/utils/cordova");
const configXml_1 = require("../lib/utils/configXml");
const base_1 = require("./base");
let PluginCommand = class PluginCommand extends base_1.CordovaCommand {
    preRun(inputs, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            yield this.checkForAssetsFolder();
            inputs[0] = (typeof inputs[0] === 'undefined') ? 'ls' : inputs[0];
            inputs[0] = (inputs[0] === 'rm') ? 'remove' : inputs[0];
            inputs[0] = (inputs[0] === 'list') ? 'ls' : inputs[0];
            cli_utils_1.validate(inputs[0], 'action', [cli_utils_1.contains(['add', 'remove', 'ls', 'save'], {})]);
            // If the action is list then lets just end here.
            if (['ls', 'save'].includes(inputs[0])) {
                const response = yield this.runCordova(['plugin', inputs[0]]);
                this.env.log.msg(response);
                return 0;
            }
            if (!inputs[1]) {
                const plugin = yield this.env.prompt({
                    message: `What plugin would you like to ${inputs[0]}:`,
                    type: 'input',
                    name: 'plugin',
                });
                inputs[1] = plugin;
            }
            cli_utils_1.validate(inputs[1], 'plugin', [cli_utils_1.validators.required]);
        });
    }
    run(inputs, options) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const conf = yield configXml_1.ConfigXml.load(this.env.project.directory);
            yield conf.resetContentSrc();
            yield conf.save();
            const optionList = cordova_1.filterArgumentsForCordova(this.metadata, inputs.splice(0, 2), options);
            if (!optionList.includes('--save')) {
                optionList.push('--save');
            }
            // TODO: showExecution and filter out double newlines from cordova
            const response = yield this.runCordova(optionList);
            this.env.log.msg(response);
        });
    }
};
PluginCommand = tslib_1.__decorate([
    cli_utils_1.CommandMetadata({
        name: 'plugin',
        type: 'project',
        description: 'Manage Cordova plugins',
        longDescription: `
Like running ${chalk.green('cordova plugin')} directly, but provides friendly checks.
  `,
        exampleCommands: ['', 'add cordova-plugin-inappbrowser@latest', 'add phonegap-plugin-push --variable SENDER_ID=XXXXX', 'rm cordova-plugin-camera'],
        inputs: [
            {
                name: 'action',
                description: `${chalk.green('add')} or ${chalk.green('remove')} a plugin; ${chalk.green('ls')} or ${chalk.green('save')} all project plugins`,
            },
            {
                name: 'plugin',
                description: `The name of the plugin (corresponds to ${chalk.green('add')} and ${chalk.green('remove')})`,
            },
        ],
        options: [
            {
                name: 'force',
                description: `Forve overwrite the plugin if it exists (corresponds to ${chalk.green('add')})`,
                type: Boolean,
                intent: cordova_1.CORDOVA_INTENT,
            },
            {
                name: 'variable',
                description: 'Specify plugin variables',
                intent: cordova_1.CORDOVA_INTENT,
            }
        ]
    })
], PluginCommand);
exports.PluginCommand = PluginCommand;


text:
package rubber.duck.forklift.pilot.server.meta;

/**
 *
 * @author Peter C
 */
public class WorkerMeta {
    private final String container;
    private final String url;
    private final ArgumentMeta[] arguments;

    public WorkerMeta(String container, String url, ArgumentMeta... arguments) {
        this.container = container;
        this.url = url;
        this.arguments = arguments;
    }

    public String getContainer() {
        return container;
    }

    public String getUrl() {
        return url;
    }

    public ArgumentMeta[] getArguments() {
        return arguments;
    }
}


text:
var onRun = function(context) {

    var ga = require("../modules/Google_Analytics");
    ga("Layer");

    var document = context.document;
    var selection = context.selection;

    var predicate = NSPredicate.predicateWithFormat("className == %@", "MSLayerGroup");
    var selectedGroups = selection.filteredArrayUsingPredicate(predicate);
    if (selectedGroups.count() == 0) {
        document.showMessage("Please select at least 1 layer group.");
        return;
    }

    selectedGroups.forEach(function(group) {
        if (group.hasClickThrough()) {
            group.setHasClickThrough(false);
        } else {
            group.setHasClickThrough(true);
        }
    });

};


text:
Before("@importexport") do
  @service = Aws::ImportExport::Resource.new
  @client = @service.client
end

After("@importexport") do
  # shared cleanup logic
end


text:
require "#{File.join(File.dirname(__FILE__),'..','spec_helper.rb')}"

describe 'puppi::rollback' do

  let(:title) { 'puppi::rollback' }
  let(:node) { 'rspec.example42.com' }
  let(:params) {
    { 'enable'   =>  'true',
      'name'     =>  'get',
      'command'  =>  'echo',
      'priority' =>  '50',
      'project'  =>  'myapp',
    }
  }

  describe 'Test puppi rollback step file creation' do
    it 'should create a puppi::rollback step file' do
      should contain_file('/etc/puppi/projects/myapp/rollback/50-get').with_ensure('present')
    end
    it 'should populate correctly the puppi::rollback step file' do
      should contain_file('/etc/puppi/projects/myapp/rollback/50-get').with_content("su - root -c \"export project=myapp && /etc/puppi/scripts/echo \"\n")
    end
  end

end


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "string.h"
#include "main/php_main.h"
#include "Zend/zend_API.h"
#include "Zend/zend_variables.h"
#include "zend_exceptions.h"
#include "zend_interfaces.h"
#include "zend_object_handlers.h"
#include "ext/standard/php_string.h"

#include "php_r3.h"
// #include "ct_helper.h"
// #include "r3_functions.h"
// #include "r3_mux.h"
// #include "php_expandable_mux.h"
// #include "r3_controller.h"

ZEND_DECLARE_MODULE_GLOBALS(r3);

// persistent list entry type for HashTable
int le_mux_hash_table;

// persistent list entry type for boolean
int le_mux_bool;

// persistent list entry type for int
int le_mux_int;

// persistent list entry type for string
int le_mux_string;

zend_class_entry *ce_r3_exception;

// #define DEBUG 1
static const zend_function_entry r3_functions[] = {
    PHP_FE(r3_match, NULL)
    PHP_FE_END
};

void r3_init_exception(TSRMLS_D) {
  zend_class_entry e;
  INIT_CLASS_ENTRY(e, "R3Exception", NULL);
  ce_r3_exception = zend_register_internal_class_ex(&e, (zend_class_entry*)zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
}

void r3_mux_le_hash_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
    HashTable *h = (HashTable*) rsrc->ptr;
    if (h) {
        // zend_hash_destroy(h);
        // pefree(h, 1);
    }
}

zend_module_entry r3_module_entry = {
    STANDARD_MODULE_HEADER,
    PHP_R3_EXTNAME,
    r3_functions,
    PHP_MINIT(r3),
    PHP_MSHUTDOWN(r3),
    PHP_RINIT(r3),
    NULL,
    NULL,
    PHP_R3_VERSION,
    STANDARD_MODULE_PROPERTIES
};

PHP_INI_BEGIN()
    PHP_INI_ENTRY("r3.fstat", "0", PHP_INI_ALL, NULL)
    // STD_PHP_INI_ENTRY("r3.direction", "1", PHP_INI_ALL, OnUpdateBool, direction, zend_hello_globals, hello_globals)
PHP_INI_END()

#ifdef COMPILE_DL_R3
ZEND_GET_MODULE(r3)
#endif

static void php_r3_init_globals(zend_r3_globals *r3_globals)
{
    // r3_globals->persistent_list = (HashTable*)
    // array_init(r3_globals->persistent_list);
}

PHP_MINIT_FUNCTION(r3) {
  ZEND_INIT_MODULE_GLOBALS(r3, php_r3_init_globals, NULL);
  REGISTER_INI_ENTRIES();
  // r3_init_mux(TSRMLS_C);
  // r3_init_expandable_mux(TSRMLS_C);
  // r3_init_controller(TSRMLS_C);
  le_mux_hash_table = zend_register_list_destructors_ex(NULL, r3_mux_le_hash_dtor, "hash table", module_number);
  return SUCCESS;
}

PHP_MSHUTDOWN_FUNCTION(r3) {
  UNREGISTER_INI_ENTRIES();
  return SUCCESS;
}

PHP_RINIT_FUNCTION(r3) {
  return SUCCESS;
}

/*
 * r3_compile(array $routes, string $path);
 */
PHP_FUNCTION(r3_match)
{
    zval *z_routes;
    char *path;
    int  path_len;

    /* parse parameters */
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "as",
                    &z_routes,
                    &path, &path_len ) == FAILURE) {
        RETURN_FALSE;
    }

    /*
    zval *z_route;
    z_route = php_r3_match(z_routes, path, path_len TSRMLS_CC);
    if ( z_route != NULL ) {
        *return_value = *z_route;
        zval_copy_ctor(return_value);
        return;
    }
    */
    RETURN_NULL();
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

                <form #post_form="ngForm" (submit)="savePost()" >

                        <textarea class="form-control" name="txt" placeholder="schreibe einen Beitrag"
                                  [(ngModel)]="post.text" #text="ngModel"></textarea>

                        <input class="list-group-item form-control" name="tags" value="" type="text" placeholder="#Tags"
                               pattern="[#][^\s].*[\s#{1}.*]*" [(ngModel)]="post.tags" #tags="ngModel" required>

 Tags bitte
                        in der Form: #[name][leerzeichen]...

                        <button type="submit" class="btn btn-success">Post</button>

                </form>


text:
require './core/frame.rb'
require './core/protos/object.rb'

def ExpressionProto(messages)
  return ExpressionProto.new(messages)
end

class ExpressionProto < Frame

  attr :messages

  def initialize(messages)
    super(ObjectProto.instance)

    @messages = messages
  end

  def eval_(receiver, locals)
    trace "ExpressionProto::eval()"

    result = @messages.reduce(locals) do |receiver, value|
      value && value.eval_(receiver, locals)
    end

    return result
  end

  def frame_inspect(value)
    messages = value.frame.messages.map do |message|
      message.inspect()
    end

    return messages
  end

  def frame_to_s(value)
    messages = value.frame.messages.map do |message|
      message.to_s
    end

    return "(" + messages.join(" ") + ")"
  end

end


text:
::
:: Microsoft Azure SDK for Net - Generate library code
:: Copyright (C) Microsoft Corporation. All Rights Reserved.
::

@echo off
::set autoRestVersion=0.13.0-Nightly20151029
set autoRestVersion=0.14.0-Nightly20160125
if  "%1" == "" (
    set specFile="https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/arm-intune/2015-01-14-preview/swagger/intune.json"
) else (
    set specFile="%1"
)
set repoRoot=%~dp0..\..\..\..
set generateFolder=%~dp0Generated

if exist %generateFolder% rd /S /Q  %generateFolder%
call "%repoRoot%\tools\autorest.gen.cmd" %specFile% Microsoft.Azure.Management.Intune %autoRestVersion% %generateFolder%


text:
require 'gemdo'

module GemDo
module CLI

  # Command to bump version number.
  #
  class Bump < Base

    attr :project

    #
    def initialize
      @project = POM::Project.find
      @slots   = []
      @state   = nil
      @force   = false
    end

    #
    def run
      parse
      execute
    end

    # Returns instance of option parser.
    def parser
      @parser ||= OptionParser.new do |opt|
        opt.banner = "pom bump [OPTIONS | ENTRY]"

        opt.on("--major", "-M", "bump major version number") do
          @slots << :major
        end

        opt.on("--minor", "-m", "bump minor version number") do
          @slots << :minor
        end

        opt.on("--patch", "-p", "bump patch version number") do
          @slots << :patch
        end

        opt.on("--build", "-b", "bump build version number") do
          @slots << :build
        end

        opt.on("--state", "-s", "bump version state") do |term|
          @slots << :state
        end

        opt.on("--no-write", "-n", "do not write version change") do
          $DRYRUN = true
        end

        opt.on("--force", "-f", "force otherwise protected action") do
          @force = true
        end

        opt.on("--debug", "run in debug mode") do
          $DEBUG   = true
          $VERBOSE = true
        end

        opt.on_tail("--help", "-h", "display this help message") do
          puts opt
          exit
        end
      end
    end

    #
    def parse
      parser.parse!

      @entry = ARGV.last

      if @entry == 'help'
        puts parser
        exit
      end
    end

    #
    def execute
      if POM::VersionNumber::STATES.include?(@entry)
        @state = @entry.to_sym
      end

      if POM::VersionNumber::SLOTS.include?(@entry)
        @slots << @entry.to_sym
        @entry = nil
      end

      raise "Why bump if you know what you want, silly?" if @entry && !@slots.empty?

      new_version = @entry ? POM::VersionNumber.new(@entry) : project.version

      @slots.each do |slot|
        new_version = new_version.bump(slot)
      end

      if @state
        new_version = new_version.restate(@state)
      end

      if new_version > project.version or @force
        project.version = new_version
        #project.save_version! unless $TRIAL
      else
        if new_version < project.version
          $stderr.puts "pom: Going backwards in time?"
          $stderr.outs "   New version is older than current version."
          #$stderr.outs "   Use --force to fly the TARDIS."
        end
      end

      puts(project.version)
    end

  end

end
end


text:
package com.linecorp.bot.model.response;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.AllArgsConstructor;
import lombok.Value;

@Value
@AllArgsConstructor(onConstructor = @__(@JsonCreator))
public class NumberOfMessagesResponse {
    /**
     * A status of current calculation.
     */
    public enum Status {
        /**
         * You can get the number of messages.
         */
        @JsonProperty("ready")
        READY,
        /**
         * The message counting process for the date specified in {@code date} has not been completed yet.
         * Retry your request later. Normally, the counting process is completed within the next day.
         */
        @JsonProperty("unready")
        UNREADY,
        /**
         * The date specified in date is earlier than March 31, 2018, when the operation of the counting system
         * started.
         */
        @JsonProperty("out_of_service")
        OUT_OF_SERVICE
    }

    Status status;
    long success;
}


text:
<?php

/******************************************
* Begin Form configuration
******************************************/

$tform_def_file = "form/client_circle.tform.php";

/******************************************
* End Form configuration
******************************************/

require_once '../../lib/config.inc.php';
require_once '../../lib/app.inc.php';

//* Check permissions for module
$app->auth->check_module_permissions('client');

// Loading classes
$app->uses('tpl,tform,tform_actions');
$app->load('tform_actions');

class page_action extends tform_actions {

}

$page = new page_action;
$page->onLoad();

?>


text:
<?php
namespace DynamicForm\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class DynamicFormController extends AbstractActionController
{
    public function indexAction()
    {
        $sm = $this->getServiceLocator();
        $DFS = $sm->get('DynamicFormService');
        $form = $DFS->get('membre');
        $form->setInputFilter($form->getInputFilter());
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            $form->isValid();
        }
        return array('form' => $form);
    }
}


text:
package com.example.android.dragsource;

import android.content.ClipData;
import android.net.Uri;
import android.view.DragEvent;
import android.view.View;
import android.widget.ImageView;

/**
 * OnDragListener for ImageViews.
 * Sets colors of the target when DragEvents fire. When a drop is received, the {@link Uri} backing
 * the first {@link android.content.ClipData.Item} in the {@link DragEvent} is set as the image
 * resource of the ImageView.
 */
public class ImageDragListener implements View.OnDragListener {

    private static final int COLOR_INACTIVE = 0xFF888888;

    private static final int COLOR_ACTIVE = 0xFFCCCCCC;

    private static final int COLOR_HOVER = 0xFFEEEEEE;

    @Override
    public boolean onDrag(View view, DragEvent event) {
        // Change the color of the target for all events.
        // For the drop action, set the view to the dropped image.
        switch (event.getAction()) {
            case DragEvent.ACTION_DRAG_STARTED:
                setTargetColor(view, COLOR_ACTIVE);
                return true;

            case DragEvent.ACTION_DRAG_ENTERED:
                setTargetColor(view, COLOR_HOVER);
                return true;

            case DragEvent.ACTION_DRAG_LOCATION:
                processLocation(event.getX(), event.getY());
                return true;

            case DragEvent.ACTION_DRAG_EXITED:
                setTargetColor(view, COLOR_ACTIVE);
                return true;

            case DragEvent.ACTION_DROP:
                return processDrop(view, event);

            case DragEvent.ACTION_DRAG_ENDED:
                setTargetColor(view, COLOR_INACTIVE);
                return true;

            default:
                break;
        }

        return false;
    }

    private void setTargetColor(View view, int color) {
        view.setBackgroundColor(color);
    }

    private boolean processDrop(View view, DragEvent event) {
        ClipData clipData = event.getClipData();
        if (clipData == null || clipData.getItemCount() == 0) {
            return false;
        }
        ClipData.Item item = clipData.getItemAt(0);
        if (item == null) {
            return false;
        }
        Uri uri = item.getUri();
        if (uri == null) {
            return false;
        }
        return setImageUri(view, event, uri);
    }

    protected void processLocation(float x, float y) {
    }

    protected boolean setImageUri(View view, DragEvent event, Uri uri) {
        if (!(view instanceof ImageView)) {
            return false;
        }
        ((ImageView) view).setImageURI(uri);
        return true;
    }
}


text:
// <copyright file="Method.cs">
//      Copyright (c) Arseni Mourzenko 2015. The code is distributed under the MIT License.
// </copyright>
// <author id="5c2316d3-622a-4a8d-816d-5054a48f415f">Arseni Mourzenko</author>

namespace MockEverything.Inspection.MonoCecil
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using Mono.Cecil;
    using Mono.Cecil.Cil;
    using Mono.Collections.Generic;

    /// <summary>
    /// Represents a method from an assembly loaded using Mono.Cecil.
    /// </summary>
    [CLSCompliant(false)]
    public class Method : IMethod
    {
        /// <summary>
        /// The underlying definition of the method.
        /// </summary>
        private readonly MethodDefinition definition;

        /// <summary>
        /// Initializes a new instance of the <see cref="Method"/> class.
        /// </summary>
        /// <param name="definition">The Mono.Cecil definition of a method.</param>
        [SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", Justification = "The arguments are validated through Code Contracts.")]
        public Method(MethodDefinition definition)
        {
            Contract.Requires(definition != null);

            this.definition = definition;
        }

        /// <summary>
        /// Gets the short name of the method. This name doesn't contain any reference to the type, namespace or assembly.
        /// </summary>
        public string Name
        {
            get
            {
                Contract.Ensures(Contract.Result<string>() != null);

                return this.definition.Name;
            }
        }

        /// <summary>
        /// Gets the name which can be overwritten through the usage of <c>ProxyMethodAttribute</c> attribute.
        /// </summary>
        public string VirtualName
        {
            get
            {
                var proxyMethodAttribute = this.definition.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == "MockEverything.Attributes.ProxyMethodAttribute");
                if (proxyMethodAttribute != null)
                {
                    Contract.Assume(proxyMethodAttribute.ConstructorArguments.Count >= 2);

                    var arg = proxyMethodAttribute.ConstructorArguments[1];
                    Contract.Assume(arg.Type.FullName == "System.String");
                    return (string)arg.Value ?? this.Name;
                }

                return this.Name;
            }
        }

        /// <summary>
        /// Gets the parameters of the method.
        /// </summary>
        public IEnumerable<Parameter> Parameters
        {
            get
            {
                Contract.Ensures(Contract.Result<IEnumerable<Parameter>>() != null);

                return this.definition.Parameters.Select(this.GenerateParameter);
            }
        }

        /// <summary>
        /// Gets the return type of the method.
        /// </summary>
        public IType ReturnType
        {
            get
            {
                Contract.Ensures(Contract.Result<IType>() != null);

                return new Type(this.definition.ReturnType.Resolve());
            }
        }

        /// <summary>
        /// Gets the generic types of the method. If the method is not generic, the enumeration yields no results.
        /// </summary>
        /// <remarks>
        /// The generic aspect of the container class has no effect on the result.
        /// </remarks>
        public IEnumerable<string> GenericTypes
        {
            get
            {
                Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);

                foreach (var parameter in this.definition.GenericParameters)
                {
                    yield return string.Join(",", parameter.Describe().OrderBy(c => c));
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether the method is declared as public.
        /// </summary>
        public bool IsPublic
        {
            get
            {
                return this.definition.IsPublic;
            }
        }

        /// <summary>
        /// Compares this object to the specified object to determine if both represent the same method.
        /// </summary>
        /// <param name="obj">The object to compare.</param>
        /// <returns><see langword="true"/> if the object represent the same method; otherwise, <see langword="false"/>.</returns>
        public override bool Equals(object obj)
        {
            if (obj == null || !(obj is IMethod))
            {
                return false;
            }

            var other = (IMethod)obj;
            return
                this.VirtualName == other.VirtualName &&
                this.ReturnType.Equals(other.ReturnType) &&
                this.Parameters.SequenceEqual(other.Parameters) &&
                this.GenericTypes.SequenceEqual(other.GenericTypes);
        }

        /// <summary>
        /// Generates the hash code of this object.
        /// </summary>
        /// <returns>The hash code of the object.</returns>
        [ExcludeFromCodeCoverage]
        public override int GetHashCode()
        {
            var hash = 17;
            hash = (hash * 31) + this.Name.GetHashCode();
            hash = (hash * 31) + this.ReturnType.GetHashCode();
            return hash;
        }

        /// <summary>
        /// Replaces the body of this method by a body of the specified one.
        /// </summary>
        /// <param name="other">The method to use as a replacement.</param>
        /// <param name="entry">The method which should be called before executing the affected method, or <see langword="null"/> if there is no method to call.</param>
        /// <param name="exit">The method which should be called before the affected method returns, or <see langword="null"/> if there is no method to call.</param>
        /// <exception cref="System.NotImplementedException">The other method is not an instance of the <see cref="Method"/> class.</exception>
        public void ReplaceBody(IMethod other, IMethod entry = null, IMethod exit = null)
        {
            Contract.Requires(other != null);

            var otherMethod = other as Method;
            if (otherMethod == null)
            {
                throw new System.NotImplementedException();
            }

            this.ReplaceBody(
                otherMethod.definition,
                entry != null ? ((Method)entry).definition : null,
                exit != null ? ((Method)exit).definition : null);
        }

        /// <summary>
        /// Replaces the body of this method by a body of the specified method definition.
        /// </summary>
        /// <param name="definition">The method to use as a replacement.</param>
        /// <param name="entry">The method which should be called before executing the affected method, or <see langword="null"/> if there is no method to call.</param>
        /// <param name="exit">The method which should be called before the affected method returns, or <see langword="null"/> if there is no method to call.</param>
        private void ReplaceBody(MethodDefinition definition, MethodDefinition entry = null, MethodDefinition exit = null)
        {
            Contract.Requires(definition != null);

            var source = definition.Body;
            var destination = this.definition.Body;

            var instructionsTransform = definition.IsStatic && !this.definition.IsStatic ? this.CreateShiftArgumentsTransform(this.definition.Parameters) : default(Func<Instruction, Instruction>);

            this.ReplaceCollectionContents(source.Variables, destination.Variables);
            this.ReplaceCollectionContents(source.ExceptionHandlers, destination.ExceptionHandlers);
            this.ReplaceCollectionContents(source.Instructions, destination.Instructions, instructionsTransform);

            if (entry != null)
            {
                foreach (var instruction in this.GenerateEntryCall(entry).ToList().Reverse<Instruction>())
                {
                    destination.Instructions.Insert(0, instruction);
                }
            }

            if (exit != null)
            {
                var index = 0;
                while (index < destination.Instructions.Count)
                {
                    var instruction = destination.Instructions[index];
                    if (instruction.OpCode.Code == Code.Ret)
                    {
                        var exitVariable = this.definition.ReturnType.MetadataType != MetadataType.Void ?
                            new VariableDefinition(destination.Method.ReturnType) :
                            null;

                        if (exitVariable != null)
                        {
                            destination.Variables.Add(exitVariable);
                        }

                        foreach (var exitCallInstruction in this.GenerateExitCall(exit, exitVariable))
                        {
                            destination.Instructions.Insert(index, exitCallInstruction);
                            index += 1;
                        }
                    }

                    index += 1;
                }
            }
        }

        /// <summary>
        /// Generates the instructions which call the entry hook.
        /// </summary>
        /// <param name="entry">The entry hook method.</param>
        /// <returns>Zero or more instructions to insert at the beginning of the current method.</returns>
        private IEnumerable<Instruction> GenerateEntryCall(MethodDefinition entry)
        {
            Contract.Requires(entry != null);

            this.VerifyEntryMethod(entry);

            var objectType = entry.Parameters.Last().ParameterType.GetElementType();

            yield return Instruction.Create(OpCodes.Ldstr, this.definition.DeclaringType.FullName);
            yield return Instruction.Create(OpCodes.Ldstr, this.Name);
            yield return Instruction.Create(OpCodes.Ldstr, this.definition.FullName);
            yield return Instruction.Create(OpCodes.Ldc_I4, this.definition.Parameters.Count);
            yield return Instruction.Create(OpCodes.Newarr, objectType);

            int index = 0;
            foreach (var parameter in this.definition.Parameters)
            {
                yield return Instruction.Create(OpCodes.Dup);
                yield return Instruction.Create(OpCodes.Ldc_I4, index);
                yield return Instruction.Create(OpCodes.Ldarg_S, parameter);
                if (parameter.ParameterType.IsValueType)
                {
                    yield return Instruction.Create(OpCodes.Box, parameter.ParameterType);
                }

                yield return Instruction.Create(OpCodes.Stelem_Ref);
                index += 1;
            }

            yield return Instruction.Create(OpCodes.Call, entry);
        }

        /// <summary>
        /// Generates the instructions which call the exit hook.
        /// </summary>
        /// <param name="exit">The exit hook method.</param>
        /// <param name="exitVariable">The variable used to locally store the return value.</param>
        /// <returns>Zero or more instructions to insert before every <c>ret</c> IL instruction.</returns>
        private IEnumerable<Instruction> GenerateExitCall(MethodDefinition exit, VariableDefinition exitVariable)
        {
            Contract.Requires(exit != null);

            this.VerifyExitMethod(exit);

            if (this.definition.ReturnType.MetadataType != MetadataType.Void)
            {
                yield return Instruction.Create(OpCodes.Stloc_S, exitVariable);
                yield return Instruction.Create(OpCodes.Ldstr, this.definition.DeclaringType.FullName);
                yield return Instruction.Create(OpCodes.Ldstr, this.Name);
                yield return Instruction.Create(OpCodes.Ldstr, this.definition.FullName);
                yield return Instruction.Create(OpCodes.Ldloc_S, exitVariable);
                yield return Instruction.Create(OpCodes.Call, exit);
                yield return Instruction.Create(OpCodes.Ldloc_S, exitVariable);
            }
            else
            {
                yield return Instruction.Create(OpCodes.Ldstr, this.definition.DeclaringType.FullName);
                yield return Instruction.Create(OpCodes.Ldstr, this.Name);
                yield return Instruction.Create(OpCodes.Ldstr, this.definition.FullName);
                yield return Instruction.Create(OpCodes.Ldnull);
                yield return Instruction.Create(OpCodes.Call, exit);
            }
        }

        /// <summary>
        /// Verifies that the entry method corresponds to the one expected when calling it at IL level.
        /// </summary>
        /// <param name="entry">The entry hook method to check.</param>
        /// <exception cref="InvalidEntryException">The method is invalid.</exception>
        private void VerifyEntryMethod(MethodDefinition entry)
        {
            Contract.Requires(entry != null);

            // Notice that in the checks below, the type is compared by its full name. This means that, actually, nothing prevents the caller from creating a `System.Object` or `System.String` and use it instead of the native one; if he does, the code will fail. On the other hand, if the caller actually screws with the code at this level, there is probably no need to handle this case.
            if (!entry.IsPublic || !entry.IsStatic || entry.HasGenericParameters)
            {
                throw new InvalidEntryException(string.Format("The entry method {0} in {1} should be a public, static, non-generic method.", entry.FullName, entry.DeclaringType.FullName));
            }

            if (entry.ReturnType.FullName != "System.Void")
            {
                throw new InvalidEntryException(string.Format("The entry method {0} in {1} should not return a value.", entry.FullName, entry.DeclaringType.FullName));
            }

            const int NumberOfParameters = 4;
            if (entry.Parameters.Count != NumberOfParameters)
            {
                throw new InvalidEntryException(string.Format("The entry method {0} in {1} should have exactly {2} parameters, not {3}.", entry.FullName, entry.DeclaringType.FullName, NumberOfParameters, entry.Parameters.Count));
            }

            foreach (var parameter in entry.Parameters)
            {
                if (parameter.Attributes != ParameterAttributes.None)
                {
                    throw new InvalidEntryException(string.Format("The parameter `{0}` of the entry method {1} in {2} should not contain default values or other attributes such as `ref` or `out`.", parameter.Name, entry.FullName, entry.DeclaringType.FullName));
                }
            }

            foreach (var parameter in entry.Parameters.Take(3))
            {
                if (parameter.ParameterType.FullName != "System.String")
                {
                    throw new InvalidEntryException(string.Format("The parameter `{0}` of the entry method {1} in {2} should be a string, not {3}.", parameter.Name, entry.FullName, entry.DeclaringType.FullName, entry.Parameters[0].ParameterType.FullName));
                }
            }

            if (!entry.Parameters[3].ParameterType.IsArray || entry.Parameters[3].ParameterType.GetElementType().FullName != "System.Object")
            {
                throw new InvalidEntryException(string.Format("The last parameter of the entry method {0} in {1} should be an array of strings.", entry.FullName, entry.DeclaringType.FullName));
            }
        }

        /// <summary>
        /// Verifies that the entry method corresponds to the one expected when calling it at IL level.
        /// </summary>
        /// <param name="entry">The entry hook method to check.</param>
        /// <exception cref="InvalidEntryException">The method is invalid.</exception>
        private void VerifyExitMethod(MethodDefinition entry)
        {
            Contract.Requires(entry != null);

            // Notice that in the checks below, the type is compared by its full name. This means that, actually, nothing prevents the caller from creating a `System.Object` or `System.String` and use it instead of the native one; if he does, the code will fail. On the other hand, if the caller actually screws with the code at this level, there is probably no need to handle this case.
            if (!entry.IsPublic || !entry.IsStatic || entry.HasGenericParameters)
            {
                throw new InvalidEntryException(string.Format("The exit method {0} in {1} should be a public, static, non-generic method.", entry.FullName, entry.DeclaringType.FullName));
            }

            if (entry.ReturnType.FullName != "System.Void")
            {
                throw new InvalidEntryException(string.Format("The exit method {0} in {1} should not return a value.", entry.FullName, entry.DeclaringType.FullName));
            }

            const int NumberOfParameters = 4;
            if (entry.Parameters.Count != NumberOfParameters)
            {
                throw new InvalidEntryException(string.Format("The exit method {0} in {1} should have exactly {2} parameters, not {3}.", entry.FullName, entry.DeclaringType.FullName, NumberOfParameters, entry.Parameters.Count));
            }

            foreach (var parameter in entry.Parameters)
            {
                if (parameter.Attributes != ParameterAttributes.None)
                {
                    throw new InvalidEntryException(string.Format("The parameter `{0}` of the exit method {1} in {2} should not contain default values or other attributes such as `ref` or `out`.", parameter.Name, entry.FullName, entry.DeclaringType.FullName));
                }
            }

            foreach (var parameter in entry.Parameters.Take(3))
            {
                if (parameter.ParameterType.FullName != "System.String")
                {
                    throw new InvalidEntryException(string.Format("The parameter `{0}` of the exit method {1} in {2} should be a string, not {3}.", parameter.Name, entry.FullName, entry.DeclaringType.FullName, entry.Parameters[0].ParameterType.FullName));
                }
            }

            if (entry.Parameters[3].ParameterType.FullName != "System.Object")
            {
                throw new InvalidEntryException(string.Format("The last parameter of the exit method {0} in {1} should be an object.", entry.FullName, entry.DeclaringType.FullName));
            }
        }

        /// <summary>
        /// Creates a transform which shifts the use of the arguments to the right, in a context of moving code from static to instance method, since in instance methods, the first argument corresponds to the instance itself.
        /// </summary>
        /// <param name="parameters">The parameters of the destination method.</param>
        /// <returns>The transform.</returns>
        private Func<Instruction, Instruction> CreateShiftArgumentsTransform(IEnumerable<ParameterDefinition> parameters)
        {
            Contract.Requires(parameters != null);
            Contract.Ensures(Contract.Result<Func<Instruction, Instruction>>() != null);

            return instruction =>
            {
                if (instruction.OpCode == OpCodes.Ldarg_0)
                {
                    return Instruction.Create(OpCodes.Ldarg_1);
                }

                if (instruction.OpCode == OpCodes.Ldarg_1)
                {
                    return Instruction.Create(OpCodes.Ldarg_2);
                }

                if (instruction.OpCode == OpCodes.Ldarg_2)
                {
                    return Instruction.Create(OpCodes.Ldarg_3);
                }

                if (instruction.OpCode == OpCodes.Ldarg_3)
                {
                    var definition = parameters.ElementAt(3);
                    return Instruction.Create(OpCodes.Ldarg_S, definition);
                }

                if (instruction.OpCode == OpCodes.Ldarg_S)
                {
                    var index = ((ParameterDefinition)instruction.Operand).Index;
                    var definition = parameters.ElementAt(index);
                    return Instruction.Create(OpCodes.Ldarg_S, definition);
                }

                return instruction;
            };
        }

        /// <summary>
        /// Replaces the contents of a collection by the contents of a sequence.
        /// </summary>
        /// <typeparam name="TElement">The type of the elements in the collection.</typeparam>
        /// <param name="source">The source sequence.</param>
        /// <param name="destination">The collection to modify.</param>
        /// <param name="transform">The transformation to perform for every element, or <see langword="null"/> if the elements should be copied as is.</param>
        private void ReplaceCollectionContents<TElement>(IEnumerable<TElement> source, Collection<TElement> destination, Func<TElement, TElement> transform = null)
        {
            Contract.Requires(source != null);
            Contract.Requires(destination != null);

            if (transform == null)
            {
                transform = obj => obj;
            }

            while (destination.Any())
            {
                destination.RemoveAt(0);
            }

            foreach (var element in source)
            {
                destination.Add(transform(element));
            }
        }

        /// <summary>
        /// Creates a parameter from a Mono.Cecil definition of a parameter.
        /// </summary>
        /// <param name="definition">Mono.Cecil definition of a parameter.</param>
        /// <returns>The corresponding parameter object.</returns>
        private Parameter GenerateParameter(ParameterDefinition definition)
        {
            Contract.Requires(definition != null);
            Contract.Ensures(Contract.Result<Parameter>() != null);

            var variant = ParameterVariant.In;
            if (definition.IsOut)
            {
                variant = ParameterVariant.Out;
            }
            else if (definition.ParameterType.IsByReference)
            {
                variant = ParameterVariant.Ref;
            }
            else if (definition.CustomAttributes.Any(a => a.AttributeType.FullName == typeof(System.ParamArrayAttribute).FullName))
            {
                variant = ParameterVariant.Params;
            }

            return new Parameter(variant, new Type(definition.ParameterType.Resolve()));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--

 Copyright 2003 - 2015 The eFaps Team

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

-->
<ui-command xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>fec6814c-6f52-482e-b1de-996863c9745b</uuid>
    <file-application>eFapsApp-Payroll</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Payroll_ProcessPaymentTree_Menu_Action_ExecuteAsJob</name>
        <access>
            <role>Payroll_Admin</role>
        </access>
        <target>
            <execute method="executeProcessAsJob" program="org.efaps.esjp.payroll.Process">
                <property name="UseNumberGenerator4Name">true</property>
            </execute>
            <trigger event="UI_ACCESSCHECK" method="configCheck" index="1"
                name="ayroll_ProcessPaymentTree_Menu_Action_ExecuteAsJob.UI_ACCESSCHECK.1"
                program="org.efaps.esjp.admin.access.AccessCheck4UI">
                <!-- eFapsApp-Payroll -->
                <property name="SystemConfig">6f21b777-3c7d-4792-b3c0-8bfb6af0bf5e</property>
                <property name="Attribute">org.efaps.payroll.Process.ExecuteAsJob</property>
            </trigger>
            <trigger event="UI_ACCESSCHECK" method="check4Status" index="2"
                name="Payroll_ProcessPaymentTree_Menu_Action_ExecuteAsJob.UI_ACCESSCHECK.2"
                program="org.efaps.esjp.admin.access.AccessCheck4UI">
                <property name="Status">Open</property>
            </trigger>
            <trigger event="UI_ACCESSCHECK" method="accessCheck4Single" index="3"
                name="Payroll_ProcessPaymentTree_Menu_Action_ExecuteAsJob.UI_ACCESSCHECK.3"
                program="org.efaps.esjp.common.background.Job">
                <!-- Payroll_BackgroundJobPayment -->
                <property name="Type">d0d2ba0c-678f-4739-935a-9640c46748f6</property>
            </trigger>
        </target>
        <property name="AskUser">true</property>
        <property name="Submit">true</property>
        <property name="SubmitSelectedRows">-1</property>
    </definition>
</ui-command>


text:
@(note: Note)

@main("NoteIt - View Note", "/" + note.id) {
  <form class="pure-form">
    <textarea class="pure-input-1 upload-text" readonly>@note.contents</textarea>
    Edit
  </form>
}


text:
let ClassRoomController = new require("@modules/user/classroom/controller")
let controller = new ClassRoomController

module.exports = [
	{ method: 'GET', path: '/classroom', handler: controller.index },
	{ method: 'GET', path: '/classroom/{courseId}', handler: controller.showCourseRoom },
	{ method: 'GET', path: '/classroom/{courseId}/{classId}', handler: controller.showClassRoom },
	{ method: 'GET', path: '/classroom/test/{courseId}/{classId}', handler: controller.showTestRoom },
	{ method: 'GET', path: '/classroom/teams/{userId}', handler: controller.getUserCourses },
	{ method: 'GET', path: '/classroom/courses/{teamId}', handler: controller.getTeamCourses }
]


text:
using System;
using Ical.Net.Serialization.DataTypes;

namespace Ical.Net.DataTypes
{
    /// <summary> Represents an iCalendar period of time. </summary>
    public class Period : EncodableDataType, IComparable<Period>
    {
        public Period() { }

        public Period(IDateTime occurs)
            : this(occurs, default(TimeSpan)) {}

        public Period(IDateTime start, IDateTime end)
        {
            if (end != null && end.LessThanOrEqual(start))
            {
                throw new ArgumentException($"Start time ( {start} ) must come before the end time ( {end} )");
            }

            StartTime = start;
            if (end == null)
            {
                return;
            }
            EndTime = end;
            Duration = end.Subtract(start);
        }

        public Period(IDateTime start, TimeSpan duration)
        {
            if (duration < TimeSpan.Zero)
            {
                throw new ArgumentException($"Duration ( ${duration} ) cannot be less than zero");
            }

            StartTime = start;
            if (duration == default(TimeSpan))
            {
                return;
            }

            Duration = duration;
            EndTime = start.Add(duration);
        }

        public override void CopyFrom(ICopyable obj)
        {
            base.CopyFrom(obj);

            var p = obj as Period;
            if (p == null)
            {
                return;
            }
            StartTime = p.StartTime;
            EndTime = p.EndTime;
            Duration = p.Duration;
        }

        protected bool Equals(Period other) => Equals(StartTime, other.StartTime) && Equals(EndTime, other.EndTime) && Duration.Equals(other.Duration);

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            return obj.GetType() == GetType() && Equals((Period) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = StartTime?.GetHashCode() ?? 0;
                hashCode = (hashCode * 397) ^ (EndTime?.GetHashCode() ?? 0);
                hashCode = (hashCode * 397) ^ Duration.GetHashCode();
                return hashCode;
            }
        }

        public override string ToString()
        {
            var periodSerializer = new PeriodSerializer();
            return periodSerializer.SerializeToString(this);
        }

        private void ExtrapolateTimes()
        {
            if (EndTime == null && StartTime != null && Duration != default(TimeSpan))
            {
                EndTime = StartTime.Add(Duration);
            }
            else if (Duration == default(TimeSpan) && StartTime != null && EndTime != null)
            {
                Duration = EndTime.Subtract(StartTime);
            }
            else if (StartTime == null && Duration != default(TimeSpan) && EndTime != null)
            {
                StartTime = EndTime.Subtract(Duration);
            }
        }

        private IDateTime _startTime;
        public virtual IDateTime StartTime
        {
            get => _startTime.HasTime
                ? _startTime
                : new CalDateTime(new DateTime(_startTime.Value.Year, _startTime.Value.Month, _startTime.Value.Day, 0, 0, 0), _startTime.TzId);
            set
            {
                if (Equals(_startTime, value))
                {
                    return;
                }
                _startTime = value;
                ExtrapolateTimes();
            }
        }

        private IDateTime _endTime;
        public virtual IDateTime EndTime
        {
            get => _endTime;
            set
            {
                if (Equals(_endTime, value))
                {
                    return;
                }
                _endTime = value;
                ExtrapolateTimes();
            }
        }

        private TimeSpan _duration;
        public virtual TimeSpan Duration
        {
            get
            {
                if (StartTime != null
                    && EndTime == null
                    && StartTime.Value.TimeOfDay == TimeSpan.Zero)
                {
                    return TimeSpan.FromDays(1);
                }
                return _duration;
            }
            set
            {
                if (Equals(_duration, value))
                {
                    return;
                }
                _duration = value;
                ExtrapolateTimes();
            }
        }

        public virtual bool Contains(IDateTime dt)
        {
            // Start time is inclusive
            if (dt == null || StartTime == null || !StartTime.LessThanOrEqual(dt))
            {
                return false;
            }

            // End time is exclusive
            return EndTime == null || EndTime.GreaterThan(dt);
        }

        public virtual bool CollidesWith(Period period) => period != null
            && ((period.StartTime != null && Contains(period.StartTime)) || (period.EndTime != null && Contains(period.EndTime)));

        public int CompareTo(Period other)
        {
            if (StartTime.Equals(other.StartTime))
            {
                return 0;
            }
            if (StartTime.LessThan(other.StartTime))
            {
                return -1;
            }
            if (StartTime.GreaterThan(other.StartTime))
            {
                return 1;
            }
            throw new Exception("An error occurred while comparing two Periods.");
        }
    }
}


text:
<?php

/**
 * CommunityArticle
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    diem-project
 * @subpackage model
 * @author     Thibault D
 * @version    SVN: $Id: Builder.php 7021 2010-01-12 20:39:49Z lsmith $
 */
class CommunityArticle extends BaseCommunityArticle
{
}


text:
import React, { Component } from 'react';

export default class Footer extends Component {
  render() {
    return (
      <footer>
      	© 2017 |
      	<span> Designed By Longyarnz Inc. 08082935102</span>
      </footer>
    );
  }
}


text:
help!

{#if $T.election.BOGUS_P}
The public key for this election is not yet ready. This election is in preview mode only.
{#else}
Election Fingerprint: {$T.election.hash}
{#/if}


text:
import Algo       from '../algos/Algo.js';
import {Color}    from 'jPalette';
import {ColorMap} from 'jPalette';

export default class BailoutColoring {

  /**
   * Simple bailout coloring.
   *
   * @constructor
   * @memberof jFractal
   * @param  {Algorithm} algorithm
   * @param  {Color} mainColor
   * @param  {ColorMap} palette
   */
  constructor(algorithm, mainColor, palette) {
    this.algorithm = algorithm;
    this.mainColor = mainColor;
    this.palette   = palette;
  }

  /**
   * Return a color for a given complex.
   *
   * @param  {Complex} z
   * @return {Color}
   */
  getColor(z) {
    var bailout = this.algorithm.iterate(z);

    if (bailout.iter == this.algorithm.maxIter) {
      return this.mainColor;
    }
    return this.palette.getColor(bailout.iter / this.algorithm.maxIter);
  }

  toJSON() {
    return {
      _type     : 'BailoutColoring',
      algorithm : this.algorithm.toJSON(),
      mainColor : this.mainColor.toJSON(),
      palette   : this.palette.toJSON()
    };
  }

  static revive(o) {
    return new BailoutColoring(
      Algo    .revive(o.algorithm),
      Color   .revive(o.mainColor),
      ColorMap.revive(o.palette)
    );
  }
}


text:
- works with skippables frame id 0x184D2A50 (12 bytes per compressed frame)
- brotli is supported the same way, it will encapsulate the real brotli stream
  within an 16 byte frame header

## Generic skippable frame definition

- the frame header for [Lizard], [LZ4], [LZ5] and [Zstandard] is like this:

size    | value             | description
--------|-------------------|------------
4 bytes | 0x184D2A50U       | magic for skippable frame
4 bytes | 4                 | size of skippable frame
4 bytes | compressed size   | size of the following frame (compressed data)

## [Brotli] frame definition

- the frame header for brotli is defined a bit different:

size    | value             | description
--------|-------------------|------------
4 bytes | 0x184D2A50U       | magic for skippable frame (like zstd)
4 bytes | 8                 | size of skippable frame
4 bytes | compressed size   | size of the following frame (compressed data)
2 bytes | 0x5242U           | magic for brotli "BR"
2 bytes | uncompressed size | allocation hint for decompressor (64KB * this size)

## Usage of the Testutils
- see [programs](https://github.com/mcmilk/zstdmt/tree/master/programs)

## Usage of the Library

- see [lib](https://github.com/mcmilk/zstdmt/tree/master/lib)

[Brotli]:https://github.com/google/brotli/
[LZ4]:https://github.com/lz4/lz4/
[LZ5]:https://github.com/inikep/lz5/
[Zstandard]:https://github.com/facebook/zstd/
[Lizard]:https://github.com/inikep/lizard/

/TR 2017-05-24


text:
package HxCKDMS.HxCLinkPads.Client.Models;

import HxCKDMS.HxCLinkPads.Reference;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.AdvancedModelLoader;
import net.minecraftforge.client.model.IModelCustom;

@SideOnly(Side.CLIENT)
public class ModelLinkPad {
    private IModelCustom modelLinkPad;

    public ModelLinkPad() {
        modelLinkPad = AdvancedModelLoader.loadModel(new ResourceLocation(Reference.MOD_ID + ":textures/models/LinkPad.obj"));
    }

    public void render() {
        modelLinkPad.renderAll();
    }

    public void renderPart(String part) {
        modelLinkPad.renderPart(part);
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Position (EscherConverter 1.2.0 API)</title>
<meta name="date" content="2019-06-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

edu.ucsd.sbrg.escher.model

Interface Position

All Superinterfaces:

Cloneable, EscherBase

All Known Subinterfaces:

Box

All Known Implementing Classes:

AbstractBox, AbstractPosition, Canvas, EscherCompartment, Node, Point, TextLabel

public interface Position
extends EscherBase

A base class for a position with x and y coordinates

Author:

Andreas Dräger

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

Double
getX()

Double
getY()

boolean
isSetX()

boolean
isSetY()

void
setX(Double x)

void
setY(Double y)

Methods inherited from interface edu.ucsd.sbrg.escher.model.EscherBase

getUserObject, putUserObject, userObjectEntrySet, userObjectKeys

Method Detail

getX

Double getX()

Returns:

the x

getY

Double getY()

Returns:

the y

isSetX

boolean isSetX()

Returns:

true if the requested property is not null.

isSetY

boolean isSetY()

Returns:

true if the requested property is not null.

setX

void setX(Double x)

Parameters:

x - the x to set

setY

void setY(Double y)

Parameters:

y - the y to set

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015–2019 University of Tübingen. All rights reserved.


text:
package com.thoughtworks.go.server.service;

import java.io.File;
import java.util.Date;

import com.thoughtworks.go.config.GoConfigDao;
import com.thoughtworks.go.config.materials.Materials;
import com.thoughtworks.go.config.materials.mercurial.HgMaterial;
import com.thoughtworks.go.domain.MaterialRevisions;
import com.thoughtworks.go.domain.Pipeline;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.ModifiedAction;
import com.thoughtworks.go.domain.materials.dependency.DependencyMaterialRevision;
import com.thoughtworks.go.helper.PipelineMother;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.dao.DatabaseAccessHelper;
import com.thoughtworks.go.server.dao.PipelineSqlMapDao;
import com.thoughtworks.go.server.persistence.MaterialRepository;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.ReflectionUtil;
import org.apache.commons.lang.time.DateUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static com.thoughtworks.go.util.DataStructureUtils.a;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:WEB-INF/applicationContext-global.xml",
        "classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
        "classpath:WEB-INF/applicationContext-acegi-security.xml",
        "classpath:testPropertyConfigurer.xml"
})
public class PipelineServiceIntegrationTest {
    @Autowired private DatabaseAccessHelper dbHelper;
    @Autowired private GoCache goCache;
    @Autowired private GoConfigDao goConfigDao;
    @Autowired private PipelineService pipelineService;
    @Autowired private MaterialRepository materialRepository;
    @Autowired private PipelineSqlMapDao pipelineSqlMapDao;
    @Autowired private TransactionTemplate transactionTemplate;

    private GoConfigFileHelper configHelper = new GoConfigFileHelper();
    private ScheduleTestUtil u;

    @Before
    public void setUp() throws Exception {
        goCache.clear();
        configHelper.usingCruiseConfigDao(goConfigDao);
        configHelper.onSetUp();

        dbHelper.onSetUp();
        u = new ScheduleTestUtil(transactionTemplate, materialRepository, dbHelper, configHelper);
    }

    @After
    public void teardown() throws Exception {
        dbHelper.onTearDown();
        configHelper.onTearDown();
    }

    @Test
    public void shouldFetchPipelinePointedToByGivenDMR() {
        Pipeline pipeline = PipelineMother.passedPipelineInstance("pipeline", "stage", "job");
        dbHelper.savePipelineWithMaterials(pipeline);

        UpstreamPipelineResolver resolver = pipelineService;
        BuildCause loadedBC = resolver.buildCauseFor(
                DependencyMaterialRevision.create(pipeline.getStages().get(0).getIdentifier().getStageLocator(), pipeline.getLabel()).getPipelineName(),
                DependencyMaterialRevision.create(pipeline.getStages().get(0).getIdentifier().getStageLocator(), pipeline.getLabel()).getPipelineCounter());

        assertEquals(pipeline.getBuildCause(), loadedBC);
    }

    @Test
    public void shouldReturnCorrectNumberOfMaterialRevisionsAndMaterials() throws Exception {
        File file1 = new File("file1");
        File file2 = new File("file2");
        File file3 = new File("file3");
        File file4 = new File("file4");
        Material hg = new HgMaterial("url", "Dest");
        String[] hgRevs = new String[]{"h1"};

        u.checkinFiles(hg, "h1", a(file1, file2, file3, file4), ModifiedAction.added);

        ScheduleTestUtil.AddedPipeline pair01 = u.saveConfigWith("pair01", "stageName", u.m(hg));

        u.runAndPass(pair01, hgRevs);

        ReflectionUtil.invoke(pipelineSqlMapDao, "initDao");
        Pipeline pipeline = pipelineService.mostRecentFullPipelineByName("pair01");
        MaterialRevisions materialRevisions = pipeline.getBuildCause().getMaterialRevisions();
        assertThat(materialRevisions.getMaterials().size(), is(1));
    }

    @Test
    public void shouldReturnModificationsInCorrectOrder() throws Exception {
        File file1 = new File("file1");
        File file2 = new File("file2");
        File file3 = new File("file3");
        File file4 = new File("file4");
        Material hg1 = new HgMaterial("url1", "Dest1");
        String[] hgRevs = new String[]{"hg1_2"};

        Date latestModification = new Date();
        Date older = DateUtils.addDays(latestModification, -1);
        u.checkinFiles(hg1, "hg1_1", a(file1, file2, file3, file4), ModifiedAction.added, older);
        u.checkinFiles(hg1, "hg1_2", a(file1, file2, file3, file4), ModifiedAction.modified, latestModification);

        ScheduleTestUtil.AddedPipeline pair01 = u.saveConfigWith("pair01", "stageName", u.m(hg1));

        u.runAndPass(pair01, hgRevs);

        ReflectionUtil.invoke(pipelineSqlMapDao, "initDao");
        Pipeline pipeline = pipelineService.mostRecentFullPipelineByName("pair01");
        MaterialRevisions materialRevisions = pipeline.getBuildCause().getMaterialRevisions();
        assertThat(materialRevisions.getMaterials().size(), is(1));
        assertThat(materialRevisions.getDateOfLatestModification().getTime(), is(latestModification.getTime()));
    }

    @Test
    public void shouldReturnPMRsInCorrectOrder() throws Exception {
        File file1 = new File("file1");
        File file2 = new File("file2");
        File file3 = new File("file3");
        File file4 = new File("file4");
        Material hg1 = new HgMaterial("url1", "Dest1");
        Material hg2 = new HgMaterial("url2", "Dest2");
        String[] hgRevs = new String[]{"h1","h2"};

        Date latestModification = new Date();
        u.checkinFiles(hg2, "h2", a(file1, file2, file3, file4), ModifiedAction.added,  org.apache.commons.lang.time.DateUtils.addDays(latestModification, -1));
        u.checkinFiles(hg1, "h1", a(file1, file2, file3, file4), ModifiedAction.added, latestModification);

        ScheduleTestUtil.AddedPipeline pair01 = u.saveConfigWith("pair01", "stageName", u.m(hg1),u.m(hg2));
        u.runAndPass(pair01, hgRevs);

        ReflectionUtil.invoke(pipelineSqlMapDao, "initDao");
        Pipeline pipeline = pipelineService.mostRecentFullPipelineByName("pair01");
        MaterialRevisions materialRevisions = pipeline.getBuildCause().getMaterialRevisions();
        Materials materials = materialRevisions.getMaterials();
        assertThat(materials.size(), is(2));
        assertThat(materials.get(0),is(hg1));
        assertThat(materials.get(1),is(hg2));
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
var _ = require('lodash'),
  path = require('path'),
  util = require('util'),
  mongoose = require('mongoose'),
  Media = mongoose.model('Media'),
  multer = require('multer'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  config = require(path.resolve('./config/config')),
  Jimp = require('jimp');

/**
 * Create an media
 */
exports.create = function (req, res) {

  var media = new Media(req.body);

  var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, config.uploads.listing.image.full);
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname);
    }
  });

  var upload = multer({ storage: storage }).single('file');
  var imageUploadFileFilter = require(path.resolve('./config/lib/multer')).imageFileFilter;

  // Filtering to upload only images
  upload.fileFilter = imageUploadFileFilter;

  if (media) {
    uploadImage()
      .then(resizeImages)
      .then(updateMedia)
      .then(function () {
        res.json(media);
      })
      .catch(function (err) {
        res.status(400).send(err);
      });
  } else {
    res.status(400).send({
      message: 'Media is not exist'
    });
  }

  function resizeImages() {
    // Full Image
    var full = config.uploads.listing.image.full + req.file.filename;

    // Large Image
    Jimp.read(full, function (err, largeImage) {
      if (err) throw err;
      largeImage
        .cover(1200, 800, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE)
        .quality(100)
        .write(config.uploads.listing.image.large + req.file.filename);
    });

    // Medium Image
    Jimp.read(full, function (err, medium_Image) {
      if (err) throw err;
      medium_Image
        .cover(990, 660, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE)
        .quality(100)
        .write(config.uploads.listing.image.medium + req.file.filename);
    });

    // Small Image
    Jimp.read(full, function (err, small_Image) {
      if (err) throw err;
      small_Image
        .cover(768, 512, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE)
        .quality(100)
        .write(config.uploads.listing.image.small + req.file.filename);
    });

    // Extra Small Image
    Jimp.read(full, function (err, extra_small_Image) {
      if (err) throw err;
      extra_small_Image
        .cover(576, 384, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE)
        .quality(100)
        .write(config.uploads.listing.image.extra_small + req.file.filename);
    });

    // Double Extra Small Image
    Jimp.read(full, function (err, double_extra_small_Image) {
      if (err) throw err;
      double_extra_small_Image
        .cover(414, 276, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE)
        .quality(100)
        .write(config.uploads.listing.image.double_extra_small + req.file.filename);
    });

    // Thumbnail Image
    Jimp.read(full, function (err, thumbnail_Image) {
      if (err) throw err;
      thumbnail_Image
        .cover(200, 200, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE)
        .quality(100)
        .write(config.uploads.listing.image.thumbnail + req.file.filename);
    });

  }

  function uploadImage () {
    return new Promise(function (resolve, reject) {
      upload(req, res, function (uploadError) {
        if (uploadError) {
          reject(errorHandler.getErrorMessage(uploadError));
        } else {
          resolve();
        }
      });
    });
  }

  function updateMedia () {
    return new Promise(function (resolve, reject) {
      media.thumbnail = config.uploads.listing.image.thumbnail + req.file.filename;
      media.medium = config.uploads.listing.image.medium + req.file.filename;
      media.extra_small = config.uploads.listing.image.extra_small + req.file.filename;
      media.double_extra_small = config.uploads.listing.image.double_extra_small + req.file.filename;
      media.small = config.uploads.listing.image.small + req.file.filename;
      media.large = config.uploads.listing.image.large + req.file.filename;
      media.full = config.uploads.listing.image.full + req.file.filename;
      media.save(function (err, themedia) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }

};

/**
 * Show the current media
 */
exports.read = function (req, res) {
  // convert mongoose document to JSON
  var media = req.media ? req.media.toJSON() : {};

  // Add a custom field to the Media, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Media model.
  media.isCurrentUserOwner = !!(req.user && media.user && media.user._id.toString() === req.user._id.toString());

  res.json(media);
};

/**
 * Update an media
 */
exports.update = function (req, res) {
  var media = req.media;

  media.title = req.body.title;
  media.content = req.body.content;

  media.save(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(media);
    }
  });
};

/**
 * Delete an media
 */
exports.delete = function (req, res) {
  var media = req.media;

  media.remove(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(media);
    }
  });
};

/**
 * List of Medias
 */
exports.list = function (req, res) {
  Media.find().sort('-created').populate('user', 'displayName').exec(function (err, medias) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(medias);
    }
  });
};

/**
 * Media middleware
 */
exports.mediaByID = function (req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Media is invalid'
    });
  }

  Media.findById(id).populate('user', 'displayName').exec(function (err, media) {
    if (err) {
      return next(err);
    } else if (!media) {
      return res.status(404).send({
        message: 'No media with that identifier has been found'
      });
    }
    req.media = media;
    next();
  });
};


text:
<?php
/**
 * Basic example of how to use Prometheus. Don't forget to copy
 * the config file!
 *
 */
error_reporting(-1);
date_default_timezone_set('America/New_York');
ini_set('error_log', realpath('logs/error.log'));
ini_set('display_errors', true);

// Prometheus uses Composer (http://getcomposer.org) to manage its
// dependencies. If you use it, it will automatically generate this
// autoloader file.
require 'vendor/autoload.php';

$cfgPath = realpath('src/Prometheus/Config/Config.php');

if (!is_readable($cfgPath)) {
    die(sprintf('Config not found in "%s"', $cfgPath));
}

require $cfgPath;

$p = new Prometheus\Prometheus();

// Pass log path to enable logging
$p->enableLogging(realpath('./logs/Prometheus.log'));

// Pass backup path to enable database backups
$p->enableDatabaseBackup(getcwd());

// Pass an array of emails to receive mail when upgrades are completed
// Note: this uses a gmail account to send mail. Set MAIL_USER and MAIL_PASSWORD
// in the config.
$p->setReportRecipients(array('bill@prgmrbill.com'));

// Pass an array of directories which contain PHP files (updates)
$p->run(array(sprintf('%s/src/Prometheus/Test/Fixture/Updates', __DIR__)));


text:
from __future__ import absolute_import
from __future__ import print_function
import os
import os.path
import argparse
from itertools import cycle
import json
from decimal import Decimal
import time
import datetime as dt
import flask
import flask_script as script
from flask_migrate import Migrate, MigrateCommand, stamp
from alembic.migration import MigrationContext
from alembic.script import ScriptDirectory
import six
from .. import create_app, db, migrate, models, auth, killmail
from .datetime import utc

if six.PY3:
    unicode = str

manager = script.Manager(create_app)

class AbsolutePathAction(argparse.Action):
    """Custom argparse.Action that transforms path strings into absolute paths.
    """
    def __call__(self, parser, namespace, values, option_string=None):
        current_absolute = os.path.abspath(os.getcwd())
        if isinstance(values, str):
            new_values = os.path.join(current_absolute, values)
        else:
            new_values = []
            for value in values:
                real_path = os.path.join(current_absolute, values)
                new_values.append(real_path)
        setattr(namespace, self.dest, new_values)

# Monkeypatch Flask-Script to consider my custom path action 'safe'
safe_actions = list(script.safe_actions)
safe_actions.append(AbsolutePathAction)
script.safe_actions = safe_actions

# Crufty workaround to get Flask-Migrate working with app factories
class MigrateManager(script.Manager):
    def __init__(self, old_command, directory='migrations'):
        super(MigrateManager, self).__init__()
        self.directory = directory
        for attr in ('app', '_commands', '_options', 'usage', 'help',
                'description', 'disable_argcomplete', 'with_default_commands',
                'parent'):
            setattr(self, attr, getattr(old_command, attr))

    def __call__(self, app=None, directory='migrations', **kwargs):
        if app is None:
            app = self.app
            if app is None:
                raise Exception(u"No app specified")

        db = kwargs.pop('db', None)

        if not isinstance(app, flask.Flask):
            app = app(**kwargs)

        # Last ditch effort to get a database handle
        if db is None:
            if 'sqlalchemy' in app.extensions:
                db = app.extensions['sqlalchemy'].db
            else:
                raise Exception(u"No database defined for app.")

        Migrate(app, db, self.directory)
        return app

migrate_path = os.path.dirname(migrate.__file__)
migrate_path = os.path.abspath(migrate_path)
migrate_manager = MigrateManager(MigrateCommand, migrate_path)
manager.add_command('db', migrate_manager)

manager.add_option('-c', '--config', dest='config', required=False,
        action=AbsolutePathAction)
manager.add_option('-i', '--instance', dest='instance_path', required=False,
        action=AbsolutePathAction)

@migrate_manager.command
def create(force=False):
    """Create tables if the database has not been configured yet."""
    # Fail if there's an alembic version set
    engine = db.get_engine(flask.current_app)
    conn = engine.connect()
    context = MigrationContext.configure(conn)
    current_rev = context.get_current_revision()
    alembic_config = flask.current_app.extensions['migrate'].migrate.get_config(
            directory=migrate_path)
    script = ScriptDirectory.from_config(alembic_config)
    latest_rev = script.get_current_head()
    if current_rev == latest_rev and not force:
        print(u"You need to run 'evesrp -c config.py db migrate' to "
              u"migrate to the latest database schema.")
    else:
        db.create_all()
        if current_rev is None:
            stamp()

@manager.shell
def shell_context():
    ctx = dict(
        app=flask.current_app,
        db=db)
    for cls in ('Request', 'Action', 'ActionType', 'Modifier',
                'AbsoluteModifier', 'RelativeModifier'):
        ctx[cls] = getattr(models, cls)
    for cls in ('Entity', 'User', 'Group', 'Note', 'APIKey', 'Permission',
            'Division', 'Pilot'):
        ctx[cls] = getattr(auth.models, cls)
    ctx['PermissionType'] = auth.PermissionType
    return ctx

class PopulatedKillmail(killmail.Killmail, killmail.RequestsSessionMixin,
        killmail.ShipNameMixin, killmail.LocationMixin):
    pass

class Populate(script.Command):
    """Populate the database with data given from a list of losses form zKB."""

    option_list = (
        script.Option('--file', '-f', dest='kill_file', required=True),
        script.Option('--users', '-u', dest='num_users', default=5, type=int),
        script.Option('--divisions', '-d', dest='num_divisions', default=3,
                type=int),
    )

    def run(self, kill_file, num_users, num_divisions, **kwargs):
        # Set up users, divisions and permissions
        users = []
        for user_num, authmethod in zip(range(num_users),
                cycle(flask.current_app.config['SRP_AUTH_METHODS'])):
            user_name = u'User {}'.format(user_num)
            user = auth.models.User.query.filter_by(name=user_name).first()
            if user is None:
                user = auth.models.User(user_name, authmethod.name)
                db.session.add(user)
            users.append(user)
        divisions = []
        for division_num in range(num_divisions):
            division_name = u'Division {}'.format(division_num)
            division = auth.models.Division.query.filter_by(
                    name=division_name).first()
            if division is None:
                division = auth.models.Division(division_name)
                db.session.add(division)
            divisions.append(division)
        db.session.add_all(divisions)
        for user in users:
            for division in divisions:
                perm = auth.models.Permission.query.filter_by(division=division,
                        permission=auth.PermissionType.submit,
                        entity=user).first()
                if perm is None:
                    auth.models.Permission(division,
                            auth.PermissionType.submit, user)
        db.session.commit()
        # load and start processing killmails
        with open(kill_file, 'r') as f:
            kills = json.load(f)
        for user, division, kill_info in zip(cycle(users), cycle(divisions), kills):
            victim = kill_info[u'victim']
            # Skip corp-level kills (towers, pocos, etc)
            if victim['characterID'] == '0':
                continue
            # make sure a Pilot exists for this killmail
            pilot = auth.models.Pilot.query.get(victim['characterID'])
            if pilot is None:
                pilot = auth.models.Pilot(user, victim['characterName'],
                        int(victim['characterID']))
            db.session.commit()
            pilot_user = pilot.user
            # create a Killmail
            args = dict(
                    kill_id=int(kill_info[u'killID']),
                    pilot_id=int(victim[u'characterID']),
                    pilot=victim[u'characterName'],
                    corp_id=int(victim[u'corporationID']),
                    corp=victim[u'corporationName'],
                    ship_id=int(victim[u'shipTypeID']),
                    system_id=int(kill_info[u'solarSystemID']),
                    verified=True)
            if victim[u'allianceID'] != '0':
                args['alliance_id'] = int(victim[u'allianceID'])
                args['alliance'] = victim[u'allianceName']
            time_struct = time.strptime(kill_info[u'killTime'], '%Y-%m-%d %H:%M:%S')
            args['timestamp'] = dt.datetime(*(time_struct[0:6]), tzinfo=utc)
            args['url'] = u'https://zkillboard.com/kill/{}'.format(
                    args['kill_id'])
            try:
                args['value'] = Decimal(kill_info[u'zkb'][u'totalValue'])
            except KeyError:
                args['value'] = Decimal(0)
            killmail = PopulatedKillmail(**args)
            try:
                killmail.ship
            except KeyError:
                continue
            # Create a request for this killmail
            models.Request(pilot_user, unicode(killmail), division, killmail)
            db.session.commit()

manager.add_command('populate', Populate())

def main():
    manager.run()

if __name__ == '__main__':
    main()