text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>NoFlo web preview</title>

    <!-- Polyfills -->
    <script src="../browser/noflo-ui.js"></script>
    <script src="./browser/noflo-noflo-runtime-iframe/runtime/network.js"></script>
    <script src="../bower_components/coffee-script/extras/coffee-script.js"></script>
    <script>
      window.NofloIframeRuntime({
        baseDir: 'noflo-ui'
      });
    </script>
    <style>
      body {
        padding: 0px;
        margin: 0px;
        background-color: black;
        color: #ffffff;
        font-family: "SourceCodePro",Helvetica,Arial,sans-serif;
        font-family: proxima-nova-regular,"Helvetica Neue",Helvetica,Arial,sans-serif;
      }
    </style>
  </head>
  <body>
  </body>
</html>


text:
package HologramGo

import (
	"github.com/hologram-io/hologram-go"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"testing"
)

func TestGetProductCategories(t *testing.T) {

	file, e := ioutil.ReadFile("json/product_categories.json")
	if e != nil {
		fmt.Printf("Error opening file: %v\n", e)
	}

	var payload = HologramGo.Placeholder{}
	err := json.Unmarshal(file, &payload)
	if err != nil {
		fmt.Println("Unable to parse file")
	}

	// Test the first product
	var productCategories = (payload["data"].([]interface{}))
	var productCategory = (HologramGo.ProductCategory)(productCategories[0].(map[string]interface{}))

	// Check for expected category.
	expectedString := "accessories"
	returnedString := productCategory.GetProductCategoryName()
	if expectedString != returnedString {
		t.Fatalf("Expected %s, got %s", expectedString, returnedString)
	}

	// Check for expected category.
	//expectedIntSlice := []int{15, 19, 11, 10, 9, 8, 7, 23}
	//returnedIntSlice := productCategory.GetProductIdsFromCategory()

	//// Length check
	//if len(expectedIntSlice) != len(returnedIntSlice) {
	//	t.Fatalf("Expected length %s, got %s", expectedString, returnedString)
	//}

	//for i := range expectedIntSlice {

	//	if expectedIntSlice[i] != returnedIntSlice[i] {
	//		t.Fatalf("Expected %s, got %s", expectedString, returnedString)
	//	}
	//}
}

redpajama_set_name: RedPajamaGithub


text:
//=============================================================================
// Copyright 2006-2010 Daniel W. Dyer
//
// 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.
//=============================================================================
package org.uncommons.watchmaker.framework;

import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import org.uncommons.watchmaker.framework.factories.StubIntegerFactory;
import org.uncommons.watchmaker.framework.operators.IntegerAdjuster;

/**
 * Unit test for {@link EvolutionStrategyEngine} class.
 * @author Daniel Dyer
 */
public class EvolutionStrategyEngineTest
{
    @Test
    public void testOnePlusOneEvolutionStrategy()
    {
        EvolutionStrategyEngine<Integer> engine = new EvolutionStrategyEngine<Integer>(new StubIntegerFactory(),
                                                                                new IntegerAdjuster(-1),
                                                                                new IndividualFitnessEvaluationStrategy<Integer>(new IntegerEvaluator()),
                                                                                true,
                                                                                1,
                                                                                FrameworkTestUtils.getRNG());
        @SuppressWarnings("unchecked")
        List<EvaluatedCandidate<Integer>> population = Arrays.asList(new EvaluatedCandidate<Integer>(1, 1));

        List<EvaluatedCandidate<Integer>> evolvedPopulation
            = engine.nextEvolutionStep(population, 0, FrameworkTestUtils.getRNG());
        assert evolvedPopulation.size() == 1 : "Population size should be 1, is " + evolvedPopulation.size();
        // The offspring is less fit than the parent (due to the -1 operator) so the parent should be retained.
        assert evolvedPopulation.get(0).getCandidate() == 1 : "Wrong individual after evolution.";
    }

    @Test
    public void testOneCommaOneEvolutionStrategy()
    {
        EvolutionStrategyEngine<Integer> engine = new EvolutionStrategyEngine<Integer>(new StubIntegerFactory(),
                                                                                new IntegerAdjuster(-1),
                                                                                new IndividualFitnessEvaluationStrategy<Integer>(new IntegerEvaluator()),
                                                                                false,
                                                                                1,
                                                                                FrameworkTestUtils.getRNG());
        @SuppressWarnings("unchecked")
        List<EvaluatedCandidate<Integer>> population = Arrays.asList(new EvaluatedCandidate<Integer>(1, 1));

        List<EvaluatedCandidate<Integer>> evolvedPopulation
            = engine.nextEvolutionStep(population, 0, FrameworkTestUtils.getRNG());
        assert evolvedPopulation.size() == 1 : "Population size should be 1, is " + evolvedPopulation.size();
        // The offspring is less fit than the parent (due to the -1 operator) but the parent is not allowed to survive.
        assert evolvedPopulation.get(0).getCandidate() == 0 : "Wrong individual after evolution.";
    }
}


text:
"use strict";
var Statement = require('./dynamodb-statement.js');

/**
 * An abstract base class for ScanStatement and QueryStatement.
 * @constructor
 */
function DynamoDbReadItemStatement() {
    Statement.apply(this, Array.from(arguments));
}

DynamoDbReadItemStatement.prototype = new Statement();

/**
 * Set LIMIT clause.
 * @param {number} limit A limit count to be read
 * @returns {undefined}
 */
DynamoDbReadItemStatement.prototype.setLimit = function(limit) {
    this.limit = limit;
};

/**
 * Set an exclusive start key that is used for `lastEvaluatedKey` parameter.
 * @param {string} lastEvaluatedKey A lastEvaluatedKey which was returned
 *  previous scan or query
 * @returns {undefined}
 */
DynamoDbReadItemStatement.prototype.setExclusiveStartKey = function(lastEvaluatedKey) {
    this.exclusiveStartKey = lastEvaluatedKey;
};

/**
 * Set ProjectionExpression.
 * @param {string} projexpr Comma separated attribute names to be selected
 * @returns {undefined}
 */
DynamoDbReadItemStatement.prototype.setProjectionExpression = function(projexpr) {
    this.projectionExpression =
        this._parser.parseProjectionExpression(
                projexpr, this.expressionAttributeNames);
};

module.exports = DynamoDbReadItemStatement;


text:
import { Action, MediaStatus, TimeMode } from "../types";
import {
  PLAY,
  STOP,
  PAUSE,
  IS_STOPPED,
  IS_PLAYING,
  SET_VOLUME,
  SET_BALANCE,
  SET_MEDIA,
  TOGGLE_REPEAT,
  TOGGLE_SHUFFLE,
  TOGGLE_TIME_MODE,
  UPDATE_TIME_ELAPSED,
  LOAD_SERIALIZED_STATE,
} from "../actionTypes";
import { TIME_MODE, MEDIA_STATUS } from "../constants";
import { MediaSerializedStateV1 } from "../serializedStates/v1Types";

export interface MediaState {
  timeMode: TimeMode; // TODO: Convert this to an enum
  timeElapsed: number;
  volume: number;
  balance: number;
  shuffle: boolean;
  repeat: boolean;
  status: MediaStatus;
}

const defaultState = {
  timeMode: TIME_MODE.ELAPSED,
  timeElapsed: 0,

  // The winamp ini file declares the default volume as "200".
  // The UI seems to show a default volume near 78, which would
  // math with the default value being 200 out of 255.
  volume: Math.round((200 / 255) * 100),
  balance: 0,
  shuffle: false,
  repeat: false,
  // TODO: Enforce possible values
  status: MEDIA_STATUS.STOPPED,
};

const media = (
  state: MediaState = defaultState,
  action: Action
): MediaState => {
  switch (action.type) {
    // TODO: Make these constants
    case PLAY:
    case IS_PLAYING:
      return { ...state, status: MEDIA_STATUS.PLAYING };
    case PAUSE:
      return { ...state, status: MEDIA_STATUS.PAUSED };
    case STOP:
    case IS_STOPPED:
      return { ...state, status: MEDIA_STATUS.STOPPED };
    case TOGGLE_TIME_MODE:
      const newMode =
        state.timeMode === TIME_MODE.REMAINING
          ? TIME_MODE.ELAPSED
          : TIME_MODE.REMAINING;
      return { ...state, timeMode: newMode };
    case UPDATE_TIME_ELAPSED:
      return { ...state, timeElapsed: action.elapsed };
    case SET_MEDIA:
      return {
        ...state,
      };
    case SET_VOLUME:
      return { ...state, volume: action.volume };
    case SET_BALANCE:
      return { ...state, balance: action.balance };
    case TOGGLE_REPEAT:
      return { ...state, repeat: !state.repeat };
    case TOGGLE_SHUFFLE:
      return { ...state, shuffle: !state.shuffle };
    case LOAD_SERIALIZED_STATE:
      return { ...state, ...action.serializedState.media };
    default:
      return state;
  }
};

export function getSerializedState(state: MediaState): MediaSerializedStateV1 {
  const { volume, balance, shuffle, repeat } = state;
  return { volume, balance, shuffle, repeat };
}

export default media;


text:
package com.sandbox.uitest;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by wangjia1-xy on 2015/9/17.
 */
public class SandboxDialog extends Dialog {
    public SandboxDialog(Context context, int theme) {
        super(context, theme);
    }

    public SandboxDialog(Context context) {
        super(context);
    }

    /**
     * Helper class for creating a custom dialog
     */
    public static class Builder {
        private Context context;
        private String title;
        private String message;
        private String backButtonText;
        private String confirmButtonText;
        private View contentView;

        private DialogInterface.OnClickListener
                backButtonClickListener,
                confirmButtonClickListener;

        public Builder(Context context) {
            this.context = context;
        }

        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        public Builder setMessage(int message) {
            this.message = (String) context.getText(message);
            return this;
        }

        public Builder setTitle(int title) {
            this.title = (String) context.getText(title);
            return this;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setContentView(View v) {
            this.contentView = v;
            return this;
        }

        public Builder setBackButton(int backButtonText, DialogInterface.OnClickListener listener) {
            this.backButtonText = (String) context.getText(backButtonText);
            this.backButtonClickListener = listener;
            return this;
        }

        public Builder setBackButton(String backButtonText, DialogInterface.OnClickListener listener) {
            this.backButtonText = backButtonText;
            this.backButtonClickListener = listener;
            return this;
        }

        public Builder setConfirmButton(int confirmButtonText, DialogInterface.OnClickListener listener) {
            this.confirmButtonText = (String) context.getText(confirmButtonText);
            this.confirmButtonClickListener = listener;
            return this;
        }

        public Builder setConfirmButton(String confirmButtonText, DialogInterface.OnClickListener listener) {
            this.confirmButtonText = confirmButtonText;
            this.confirmButtonClickListener = listener;
            return this;
        }

        public SandboxDialog create() {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            final SandboxDialog dialog = new SandboxDialog(context, R.style.custom_dialog);

            View layout = inflater.inflate(R.layout.sandbox_dialog, null);
            dialog.addContentView(layout,
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

            ((TextView) layout.findViewById(R.id.dialog_title)).setText(title);
            if (message != null) {
                TextView dlgMsg = (TextView) layout.findViewById(R.id.dialog_content_text);
                dlgMsg.setText(message);
            } else if (contentView != null) {
                // 如果未设置Dialog文本,则添加contentView
                ((LinearLayout) layout.findViewById(R.id.dialog_content)).removeAllViews();
                ((LinearLayout) layout.findViewById(R.id.dialog_content)).addView(
                        contentView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            }

            if (backButtonText == null || confirmButtonText == null) {
                layout.findViewById(R.id.dialog_bottom_divider).setVisibility(View.GONE);
                layout.findViewById(R.id.dialog_bottom_content).setVisibility(View.GONE);

            } else {
                LinearLayout bckButton = ((LinearLayout) layout.findViewById(R.id.dialog_back));
                ((TextView) layout.findViewById(R.id.dialog_back_text)).setText(backButtonText);

                if (backButtonClickListener != null) {
                    bckButton.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            backButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
                        }
                    });
                }

                LinearLayout cfmButton = ((LinearLayout) layout.findViewById(R.id.dialog_confirm));
                ((TextView) layout.findViewById(R.id.dialog_confirm_text)).setText(confirmButtonText);

                if (confirmButtonClickListener != null) {
                    cfmButton.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            confirmButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
                        }
                    });
                }
            }
            dialog.setContentView(layout);

            return dialog;
        }
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

import {connect, Socket} from 'net';

export class FirefoxProtocol {
	private _client: Socket;
	private _state: string;

	public constructor() {
		this._state = 'disconnected';
	}

	public connect(port: number): Promise<void> {
		this._state = 'connecting';
		return new Promise<void>((resolve, reject) => {
			var client: Socket = connect(port, () => {
				console.log('connected to firefox');
				this._state = 'connected';
				this.setupSocket(client);
				resolve();
			});
		});
	}

	protected onExecuteCommand(body: any): void {

	}

	protected onDisconnect(): void  {

	}

	protected sendResponse(body: any): void {
		var buffer = new Buffer(JSON.stringify(body));
		var headerBytes = new Buffer(buffer.length + ':');
		var data = Buffer.concat([headerBytes, buffer]);
		this._client.write(data);
	}

	protected setupSocket(client: Socket): void  {
		var ffBuffer = new Buffer(0);
		client.on('data', (data) => {
			var newBuffer = Buffer.concat([ffBuffer, data], ffBuffer.length + data.length);
			var pos = 0;
			var parseResult;
			while (pos < newBuffer.length &&
						 (parseResult = this.parseFirefoxPacket(newBuffer, pos))) {
				this.onExecuteCommand(parseResult.body);
				pos = parseResult.lastPos;
			}
			if (pos < newBuffer.length) {
				ffBuffer = newBuffer.slice(pos);
			} else if (ffBuffer.length > 0) {
				ffBuffer = new Buffer(0);
			}
		});

		client.on('end', () => {
			client.end();
			console.log('client disconnected');
			this._state = 'disconnected';
			this.onDisconnect();
		});
		this._client = client;
	}

	private parseFirefoxPacket(buffer: Buffer, pos: number): {lastPos: number; body: Object} {
		var i = pos;
		// find next ":"
		while (i < buffer.length && buffer[i] >= 0x30 && buffer[i] <= 0x39) {
			i++;
		}
		if (i >= buffer.length) {
			return null; // need headers
		}
		if (i === pos || buffer[i] !== 0x3a) {
			throw new Error('Invalid packet header');
		}
		var contentLength = +buffer.toString('utf8', pos, i);
		i++;
		if (i + contentLength > buffer.length) {
			return null; // need entire packet data
		}
		var body = buffer.toString('utf8', i, i + contentLength);
		return {
			lastPos: i + contentLength,
			body: body === '' ? undefined : JSON.parse(body)
		};
	}
}


text:
package com.skycloud.jkb.pojo.entity;

// Generated 2013-12-31 14:44:24 by Hibernate Tools 3.4.0.CR1

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * TriggerDepends generated by hbm2java
 */
@Entity
@Table(name = "trigger_depends", catalog = "skycloud", uniqueConstraints = @UniqueConstraint(columnNames = {
		"triggerid_down", "triggerid_up" }))
public class TriggerDepends implements java.io.Serializable {

	private long triggerdepid;
	private Triggers triggersByTriggeridDown;
	private Triggers triggersByTriggeridUp;

	public TriggerDepends() {
	}

	public TriggerDepends(long triggerdepid, Triggers triggersByTriggeridDown, Triggers triggersByTriggeridUp) {
		this.triggerdepid = triggerdepid;
		this.triggersByTriggeridDown = triggersByTriggeridDown;
		this.triggersByTriggeridUp = triggersByTriggeridUp;
	}

	@Id
	@Column(name = "triggerdepid", unique = true, nullable = false)
	public long getTriggerdepid() {
		return this.triggerdepid;
	}

	public void setTriggerdepid(long triggerdepid) {
		this.triggerdepid = triggerdepid;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "triggerid_down", nullable = false)
	public Triggers getTriggersByTriggeridDown() {
		return this.triggersByTriggeridDown;
	}

	public void setTriggersByTriggeridDown(Triggers triggersByTriggeridDown) {
		this.triggersByTriggeridDown = triggersByTriggeridDown;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "triggerid_up", nullable = false)
	public Triggers getTriggersByTriggeridUp() {
		return this.triggersByTriggeridUp;
	}

	public void setTriggersByTriggeridUp(Triggers triggersByTriggeridUp) {
		this.triggersByTriggeridUp = triggersByTriggeridUp;
	}

}


text:
// dependencies

var CSON = require('cson');

// expose

module.exports = {
  name: 'cson',
  priority: 10,
  match: function (pattern, opts) {
    var cson = pattern.cson;
    var match = typeof cson !== 'undefined';
    return match;
  },
  transform: function (pattern, opts, done) {
    try {
      done({
        json: CSON.parseSync(pattern.cson)
      });
    } catch (e) {
      done(e);
    }
  }
};


text:
from setuptools import setup, find_packages

print(find_packages(exclude=['tests*']))

setup(name='sourcelyzer',
      version='0.0.1',
      description='Sourcelyzer',
      url='https://github.com/alex-dow/sourcelyzer',
      author='Alex Dow',
      author_email='adow@psikon.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False
)


text:
<?php

namespace Google\Cloud\Samples\PubSub\test;

use Google\Cloud\TestUtils\AppEngineDeploymentTrait;
use Google\Cloud\TestUtils\FileUtil;
use PHPUnit\Framework\TestCase;

class DeployAppEngineFlexTest extends TestCase
{
    use AppEngineDeploymentTrait;

    public static function beforeDeploy()
    {
        $tmpDir = FileUtil::cloneDirectoryIntoTmp(__DIR__ . '/..');
        copy(__DIR__ . '/../app.yaml.flexible', $tmpDir . '/app.yaml');
        self::$gcloudWrapper->setDir($tmpDir);
        chdir($tmpDir);
    }

    public function testIndex()
    {
        // Access the modules app top page.
        $resp = $this->client->get('/');
        $this->assertEquals('200', $resp->getStatusCode(),
            'top page status code');
    }

    public function testSendMessage()
    {
        $resp = $this->client->request('POST', '/send_message', [
            'form_params' => [
                'message' => 'Good day!'
            ]
        ]);

        $this->assertEquals('204', $resp->getStatusCode(),
            '/send_message status code');
    }

    public function testReceiveMessage()
    {
        $resp = $this->client->request('POST', '/receive_message', [
                'body' => json_encode(['message' => ['data' => 'Bye.']]),
            ]
        );
        $this->assertEquals('200', $resp->getStatusCode(),
            '/receive_message status code');
    }
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using ZKWebStandard.Collections;
using ZKWebStandard.Web;

namespace ZKWeb.Web.ActionCollections {
	///
	/// Default action collection

	/// Support ordinary path and expression path (eg "get/{id}")

	/// 默认的Action集合

	/// 支持普通路径和表达式路径(例如"get/{id}")

	///
	public class DefaultActionCollection : IActionCollection {
		///
		/// { (Path, Method): Action }
		///
		protected ConcurrentDictionary<Pair<string, string>, Func<IActionResult>> Actions { get; set; }
		///
		/// { Path: Action Descriptor }
		///
		protected HierarchyDictionary<char, List<RegexActionDescriptor>> RegexActions { get; set; }
		///
		/// Lock for RegexActions

		/// RegexActions的线程锁

		///
		protected ReaderWriterLockSlim RegexActionsLock { get; set; }

		///
		/// Initialize

		/// 初始化

		///
		public DefaultActionCollection() {
			Actions = new ConcurrentDictionary<Pair<string, string>, Func<IActionResult>>();
			RegexActions = new HierarchyDictionary<char, List<RegexActionDescriptor>>();
			RegexActionsLock = new ReaderWriterLockSlim();
		}

		///
		/// Get base path and regular expression from full path

		/// If no expression in full path then 'regex' and 'parameters' would be null

		/// 根据完整路径获取基础路径和正则表达式

		/// 如果完整路径中无表达式则'regex'和'parameters'会等于null

		///
		protected string ParsePath(string path, out string pattern, out List<string> parameters) {
			var index = path.IndexOf('{');
			if (index >= 0) {
				// Split base path
				var basePath = path.Substring(0, index);
				// Build regular expression
				var patternBuilder = new List<string>(3);
				parameters = new List<string>(3);
				index = 0;
				while (index < path.Length) {
					var braceBegin = path.IndexOf('{', index);
					if (braceBegin >= 0) {
						var braceFinish = path.IndexOf('}', braceBegin);
						if (braceFinish < 0) {
							throw new FormatException($"invalid path: {path}, no '}}' match to '{{'");
						}
						var parameter = path.Substring(braceBegin + 1, braceFinish - braceBegin - 1).Trim();
						if (parameter.Length == 0) {
							throw new FormatException($"invalid path: {path}, no identifier between '{{' and '}}'");
						}
						patternBuilder.Add(Regex.Escape(path.Substring(index, braceBegin - index)));
						patternBuilder.Add("(.+)");
						parameters.Add(parameter);
						index = braceFinish + 1;
					} else {
						patternBuilder.Add(Regex.Escape(path.Substring(index, path.Length - index)));
						index = path.Length;
					}
				}
				pattern = string.Join("", patternBuilder);
				return basePath;
			} else {
				pattern = null;
				parameters = null;
				return path;
			}
		}

		///
		/// Associate action with path and method

		/// 设置路径和方法关联的Action函数

		///
		public void Set(string path, string method, Func<IActionResult> action, bool overrideExists) {
			// Parse path
			var basePath = ParsePath(path, out var pattern, out var parameters);
			// Duplicate check
			var key = Pair.Create(basePath, method);
			if (!overrideExists) {
				bool duplicated = false;
				if (pattern == null) {
					// No expression found, just check the key
					duplicated = Actions.ContainsKey(key);
				} else {
					// Check if there any descriptor have same method and regex
					RegexActionsLock.EnterReadLock();
					try {
						duplicated = RegexActions.TryGetValue(basePath, out var descriptors) &&
							descriptors.Any(d => d.Method == method && d.Pattern == pattern);
					} finally {
						RegexActionsLock.ExitReadLock();
					}
				}
				if (duplicated) {
					throw new ArgumentException(
						$"Action for method '{method}' and path '{path}' already registered, " +
						"please use option `overrideExists` if you want to replace it");
				}
			}
			// Register action
			if (pattern == null) {
				// Normal action
				Actions[key] = action;
			} else {
				// Regex action
				RegexActionsLock.EnterWriteLock();
				try {
					if (!RegexActions.TryGetValue(basePath, out var descriptors)) {
						descriptors = new List<RegexActionDescriptor>();
						RegexActions[basePath] = descriptors;
					}
					// Sort descriptors by pattern length descending
					var regex = new Regex(pattern);
					descriptors.Add(new RegexActionDescriptor(method, pattern, regex, parameters, action));
					descriptors.Sort((x, y) => y.Pattern.Length - x.Pattern.Length);
				} finally {
					RegexActionsLock.ExitWriteLock();
				}
			}
		}

		///
		/// Get action associated with path and method

		/// 获取路径和方法关联的Action函数

		///
		public Func<IActionResult> Get(string path, string method) {
			// Search normal action
			var key = Pair.Create(path, method);
			if (Actions.TryGetValue(key, out var action)) {
				return action;
			}
			// Search regex action
			// Matching from the lonest base path, for example:
			//	rules: "get/some/{id}", "get/{id}"
			//	"get/some/1" matches "get/some/{id}"
			//	"get/1" matches "get/{id}"
			RegexActionsLock.EnterReadLock();
			try {
				var nodes = RegexActions.Travel(path, false).Where(a => a.HasValue).Reverse();
				foreach (var node in nodes) {
					foreach (var descriptor in node.Value) {
						// Check method first because all methods are using the same list
						if (descriptor.Method != method) {
							continue;
						}
						// Match pattern, descriptors should be sorted by pattern length descennding
						var match = descriptor.Regex.Match(path);
						if (!match.Success) {
							continue;
						}
						// Set custom parameters to request
						var request = HttpManager.CurrentContext.Request;
						for (var i = 0; i < descriptor.Parameters.Count; ++i) {
							var name = descriptor.Parameters[i];
							var value = match.Groups[i + 1].Value;
							request.CustomParameters[name] = value;
						}
						return descriptor.Action;
					}
				}
			} finally {
				RegexActionsLock.ExitReadLock();
			}
			return null;
		}

		///
		/// Remove action associated with path and method

		/// 删除路径和方法关联的Action函数

		///
		public bool Remove(string path, string method) {
			var basePath = ParsePath(path, out var regex, out var parameters);
			if (regex == null) {
				// Normal action
				var key = Pair.Create(basePath, method);
				return Actions.TryRemove(key, out var _);
			} else {
				// Regex action
				RegexActionsLock.EnterReadLock();
				try {
					var pattern = regex.ToString();
					return RegexActions.TryGetValue(basePath, out var descriptors) &&
						descriptors.RemoveAll(d => d.Method == method && d.Regex.ToString() == pattern) > 0;
				} finally {
					RegexActionsLock.ExitReadLock();
				}
			}
		}

		///
		/// Regex action descriptor

		/// 使用正则表达式的Action信息

		///
		protected class RegexActionDescriptor {
			///
			/// Http Method

			/// Http方法

			///
			public string Method { get; }
			///
			/// Pattern string used by regex

			/// 正则表达式使用的字符串

			///
			public string Pattern { get; set; }
			///
			/// Regex use to match request path

			/// Group name is not used, for duplicate detection

			/// 用于匹配请求路径的正则表达式

			/// 不使用分组名称, 以检测重复

			///
			public Regex Regex { get; }
			///
			/// Parameter name array

			/// 参数的名称数组

			///
			public List<string> Parameters { get; }
			///
			/// Action method

			/// Action函数

			///
			public Func<IActionResult> Action { get; }

			///
			/// Initialize

			/// 初始化

			///
			public RegexActionDescriptor(
				string method, string pattern, Regex regex, List<string> parameters, Func<IActionResult> action) {
				Method = method;
				Pattern = pattern;
				Regex = regex;
				Parameters = parameters;
				Action = action;
			}
		}
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.alibaba</groupId>
	<artifactId>log4j2-ttl-thread-context-map</artifactId>
	<version>1.4.0-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>TTL Thread Context Map for Log4j2</name>
	<description>TTL Thread Context Map for Log4j2</description>
	<url>https://github.com/oldratlee/log4j2-ttl-thread-context-map</url>
	<inceptionYear>2015</inceptionYear>

	<licenses>
		<license>
			<name>Apache 2</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
			<comments>A business-friendly OSS license</comments>
		</license>
	</licenses>
	<scm>
		<connection>scm:git:git@github.com:oldratlee/log4j2-ttl-thread-context-map.git</connection>
		<developerConnection>scm:git:git@github.com:oldratlee/log4j2-ttl-thread-context-map.git</developerConnection>
		<url>git@github.com:oldratlee/log4j2-ttl-thread-context-map.git</url>
	</scm>
	<issueManagement>
		<url>https://github.com/oldratlee/log4j2-ttl-thread-context-map/issues</url>
		<system>GitHub Issues</system>
	</issueManagement>
	<organization>
		<name>Alibaba</name>
		<url>http://www.alibaba.com</url>
	</organization>
	<developers>
		<developer>
			<name>Jerry Lee</name>
			<id>oldratlee</id>
			<email>oldratlee(AT)gmail(DOT)com</email>
			<timezone>+8</timezone>
			<url>http://oldratlee.com/</url>
			<roles>
				<role>developer</role>
			</roles>
			<organization>Alibaba</organization>
			<organizationUrl>http://www.alibaba.com</organizationUrl>
		</developer>
	</developers>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<log4j2.version>2.12.0</log4j2.version>
		<slf4j.version>1.7.25</slf4j.version>
	</properties>

	<dependencies>
		<!-- logging libs -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>transmittable-thread-local</artifactId>
			<version>2.10.2</version>
		</dependency>
		<!-- Testing libs -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j2.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>${log4j2.version}</version>
			<scope>test</scope>
		</dependency>
		<!--
			https://stackoverflow.com/a/34543148/922688
			https://stefanbirkner.github.io/system-rules/apidocs/org/junit/contrib/java/lang/system/SystemOutRule.html

			https://github.com/stefanbirkner/system-rules
		-->
		<dependency>
			<groupId>com.github.stefanbirkner</groupId>
			<artifactId>system-rules</artifactId>
			<version>1.19.0</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<distributionManagement>
		<snapshotRepository>
			<id>ossrh</id>
			<url>https://oss.sonatype.org/content/repositories/snapshots</url>
		</snapshotRepository>
	</distributionManagement>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.22.0</version>
				<configuration>
					<!--
						terminate the spawned process after one test class and to create a new process for the next test in line (reuseForks=false)
						http://maven.apache.org/surefire-archives/maven-surefire-2.16/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html
					-->
					<reuseForks>false</reuseForks>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-deploy-plugin</artifactId>
				<version>2.8.2</version>
			</plugin>
			<plugin>
				<groupId>org.sonatype.plugins</groupId>
				<artifactId>nexus-staging-maven-plugin</artifactId>
				<version>1.6.7</version>
				<extensions>true</extensions>
				<configuration>
					<serverId>ossrh</serverId>
					<nexusUrl>https://oss.sonatype.org/</nexusUrl>
					<autoReleaseAfterClose>true</autoReleaseAfterClose>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<profiles>
		<profile>
			<id>srcDoc</id>
			<activation>
				<property>
					<name>performRelease</name>
					<value>true</value>
				</property>
			</activation>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-source-plugin</artifactId>
						<version>3.0.1</version>
						<executions>
							<execution>
								<id>attach-sources</id>
								<goals>
									<goal>jar-no-fork</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<artifactId>maven-javadoc-plugin</artifactId>
						<version>2.10.4</version>
						<configuration>
							<show>public</show>
							<charset>UTF-8</charset>
							<encoding>UTF-8</encoding>
							<docencoding>UTF-8</docencoding>
							<links>
								<link>http://docs.oracle.com/javase/7/docs/api</link>
							</links>
							<additionalJOptions>
								<additionalJOption>-J-Duser.language=en -J-Duser.country=US</additionalJOption>
							</additionalJOptions>
						</configuration>
						<executions>
							<execution>
								<id>attach-javadocs</id>
								<goals>
									<goal>jar</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>sign</id>
			<activation>
				<property>
					<name>performRelease</name>
					<value>true</value>
				</property>
			</activation>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-gpg-plugin</artifactId>
						<version>1.6</version>
						<executions>
							<execution>
								<id>sign-artifacts</id>
								<phase>verify</phase>
								<goals>
									<goal>sign</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>travis</id>
			<activation>
				<property>
					<name>env.TRAVIS</name>
					<value>true</value>
				</property>
			</activation>
			<build>
				<plugins>
					<plugin>
						<!-- for codecov.io -->
						<!-- config example: https://github.com/codecov/example-java -->
						<!-- plugin docs: http://eclemma.org/jacoco/trunk/doc/ -->
						<groupId>org.jacoco</groupId>
						<artifactId>jacoco-maven-plugin</artifactId>
						<version>0.8.1</version>
						<executions>
							<execution>
								<goals>
									<goal>prepare-agent</goal>
								</goals>
							</execution>
							<execution>
								<id>report</id>
								<phase>test</phase>
								<goals>
									<goal>report</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
</project>


text:
class Group < ApplicationRecord
  include PgSearch
  multisearchable against: [:name, :description]

  validates :name, presence: true
  validates :meeting, presence: true

  belongs_to :meeting
  has_many :group_assignments, dependent: :destroy
  has_many :individuals, through: :group_assignments
end


text:
# Introduction

This article is written in the form of a tutorial and the intent is to explain the benefits of Aurelia plugins [defined](http://aurelia.io/docs.html#plugins) as:

> A plugin is only a module with an exported ``configure function``. During startup Aurelia will load all plugin modules and call their ``configure`` functions, passing to them the FrameworkConfiguration instance so that they can configure the framework appropriately. Plugins can optionally return a ``Promise`` from their ``configure`` function in order to perform asynchronous configuration tasks. When writing a plugin, be sure to explicitly supply all metadata, including a View Strategy for Custom Elements.

>In order to do configuration on your plugin from within the app you can specify a function or object as the second argument to the configure function. Your plugin's configure function can then use that after your installation work is done. The consumer of your plugin might write code like this:
>
>```javascript
>aurelia.use.plugin('plugin-name', config => { /* configuration work */ });
```

**Important note**: Aurelia framework itself is organized in the form of a single module that "uses" (``aurelia.use``) a collection of "plugins", many of them using other plugins. Here is the code for using  ``aurelia-computed`` in your application: (``aurelia-computed`` is defined as a plugin that improves the efficiency of Aurelia data-binding computed properties)

```javascript
export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()         // enable debug logging to see aurelia-computed's observability messages.
    .plugin('aurelia-computed');  // install the plugin

  aurelia.start().then(a => a.setRoot());
}
```

----------
# What is a plugin really and how is it used?

While the above described concept of an Aurelia plugin is not difficult to grasp (after all you can say that it is just an "DLL" - a dynamically linked library), there are details in both **creating** and **consuming** a plugin that need special attention and require detailed explanations. So, using the "mechanical" depiction of the relationship between the Aurelia application and a plugin (which literally is a container, lets start with the plugin construction first - to answer the first half of the question that serves as a title of this section.

![](http://i.imgur.com/6kSaQ7m.png)

## Creating a plugin

Every plugin has to expose two endpoints (note that we called them "interface" and "export" just to get you to map several vocabularies together and be less confused by terminology). The Configuration endpoint allows plugin's adaptability to different (but still supported) use case scenarios.

In most general situation different developers **create** the plugin than developers that **use** the plugin as an external component to their application. This is not always the case, as application developer can create a plugin containing the code that is common for all applications this developer may have to develop. In either case the plugin creator has to have a very detailed knowledge of application developer's needs (so that the exported functionality fits the needs of as many developers as possible, while the opposite is not necessarily true; application developer only needs to understand the API that plugin exposes to the application that consumes that plugin. In other words, creating plugins is a lot more difficult than using them. This tutorial takes the position that the reader needs to understand both sides.

Plugin's Export Services endpoint is defined as a JavaScript code with the default name ``index.js`` which looks like (this is actual code for Aurelia-Bootstraper, referenced in the next section below - **Using (consuming a plugin)**

```javascript
/*eslint no-unused-vars:0*/
import core from 'core-js';
import {Aurelia, LogManager} from 'aurelia-framework';

let logger = LogManager.getLogger('bootstrapper');
let readyQueue = [];
let isReady = false;

function onReady(callback) {
  return new Promise((resolve, reject) => {
    if (!isReady) {
      readyQueue.push(() => {
        try {
          resolve(callback());
        } catch (e) {
          reject(e);
        }
      });
    } else {
      resolve(callback());
    }
  });
}

export function bootstrap(configure: (aurelia:Aurelia) => void): Promise<void> {
  return onReady(() => {
    let loader = new window.AureliaLoader();
    let aurelia = new Aurelia(loader);

    return configure(aurelia);
  });
}
...

```

## Using (consuming a plugin)

In order to use the plugin, application needs to ensure that the plugin is "fetched" from some repository (npm registry, github, jspm registry are examples of such repository) and "stored" in the application's file structure. Such fetch takes place as a consequence:

- Reference a plugin in application's ``package.json`` file like

```
    ...
  },
"jspm": {
    "dependencies": {
      "aurelia-animator-css": "github:aurelia/animator-css@^0.16.0",
      "aurelia-binding": "github:aurelia/binding@^0.9.0",
      "bootstrapper": "github:aurelia/bootstrapper@^0.17.0",
	...
},
...
```
where we define that:

-  the origin for ``aurelia-bootstraper`` plugin to be [https://github.com/aurelia/bootstrapper](https://github.com/aurelia/bootstrapper)
- this plugin's "internal name to be "bootstrapper"

This "internal name" is subsequently used in the context of application's initialization code (typically the ``main.js`` that is the recommended application's entry point (place where the execution starts once the application is loaded in the browser):

```javascript
export function configure(aurelia) {
  aurelia.use
    .defaultBindingLanguage()
    .defaultResources()
    .history()
    .router()
    .eventAggregator()
    .boostrapper(),
...

  aurelia.start().then(a => a.setRoot('app', document.body));
}
```

----------

# End to end tutorial

A nice example of a plugin, which is also easy to understand and very well designed / implemented is the **[Aurelia-Application-Configuration](https://github.com/Vheissu/Aurelia-Configuration)** created by Dwayne Harrington from Brisbane, Australia. We will use this plugin to illustrate plugin creation and use with all gory details.

## Aurelia Application Configuration Plugin Creation

Let's call this plugin AAC plugin in the remainder of this text and start with the description of its purpose as defined by Dwayne Charrington, its author:

>  **AAC is a smart configuration plugin and singleton service layer for your Aurelia applications**

Using a bit more formal language, AAC exposes (exports) a handful of methods that can be used at the time of your application's (application that uses AAC plugin) configuration phase. Let's list them here and you can see more details in the AAC plugin's **[README.md](https://github.com/Vheissu/Aurelia-Configuration#api)** file

- ``setCascadeMode(boolean = true)``
- ``setDirectory(name)``
- ``setConfig(fileName)``
- ``setEnvironment(environment)``
- ``setEnvironments(environments)``
- ``is(environment)``
- ``get(key, defaultValue = null)``
- ``set(key, val)``
- ``setAll(obj)``
- ``getAll()``

At this point we can explain the main sections of any plugin structure:

#### 1 Plugin Configuration Endpoint

#### 2 Plugin Services Endpoint
#### 3 Plugin Services Implementation

See **[Aurelia-Configuration/src/configure.js](https://github.com/Vheissu/Aurelia-Configuration/blob/master/src/configure.js)**

----------

## Aurelia Application Configuration Plugin Use

We will use the **[Aurelia Skeleton Navigation](https://github.com/aurelia/skeleton-navigation/releases/tag/0.18.1)** app (note that this link references the most current release 0.18.1). See also [Building Skeleton Navigation From Scratch](https://github.com/aurelia-guides/aurelia-guides.md-articles/blob/master/Building-Skeleton-Navigation-From-Scratch.md) for all details that will be used in this section.

----------

----------

----------

### Working notes (@jdanyov)

unfortunately an end-to-end tutorial does not exist to my knowledge. I have an idea for you if you want to push ahead and write this guide without a tutorial written by someone else: what you could do is take a look at the index.js files in each of the plugins I mentioned along with the instructions for usage in each of the libraries readme.md files. By pooling those examples and instructions you could probably create some pretty compelling original content for aurelia guides.

Aurelia is very very extensible so a plugin could do anything. Here's some examples:
- Plugins that provide general functionality like aurelia-dialog, aurelia-i18n, etc
- Some plugins provide resources like custom elements, custom attributes, value converters. In that case it's a matter of calling globalResources(...) in the plugin code.
- Other plugins register adapters to teach aurelia's binding system how to observe certain types of objects. Examples of this would be (aurelia-computed and aurelia-breeze).
- Then there are plugins that register custom implementations of standard aurelia components or monkey-patch standard aurelia components. Examples of this would be any of the animation plugins, also aurelia-async.
- A plugin could be any combination of the above. Does that help you?


text:
<?php

namespace Base\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * BaseConteudo
 *
 * @ORM\Table(name="base_conteudo", indexes={@ORM\Index(name="fk_base_conteudo_base_submenu1_idx", columns={"submenu"}), @ORM\Index(name="fk_base_conteudo_base_menu1_idx", columns={"menu"})})
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="Base\Entity\BaseConteudoRepository")
 */
class BaseConteudo
{
	public function __construct() {
		//$this->fotos = new ArrayCollection();
	}
	/**
	 * @ORM\OneToMany(targetEntity="BaseImagens", mappedBy="conteudo")
	 */
	private $fotos;
	/**
	 * @var integer
	 *
	 * @ORM\Column(name="idconteudo", type="integer", nullable=false)
	 * @ORM\Id
	 * @ORM\GeneratedValue(strategy="IDENTITY")
	 */
	private $idconteudo;

	/**
	 * @var string
	 *
	 * @ORM\Column(name="logo", type="string", length=255, nullable=true)
	 */
	private $logo;

	/**
	 * @var string
	 *
	 * @ORM\Column(name="descricao", type="text", nullable=true)
	 */
	private $descricao;

	/**
	 * @var string
	 *
	 * @ORM\Column(name="src", type="string", length=255, nullable=true)
	 */
	private $src;

	/**
	 * @var \BaseSubmenu
	 *
	 * @ORM\ManyToOne(targetEntity="BaseSubmenu")
	 * @ORM\JoinColumns({
	 *   @ORM\JoinColumn(name="submenu", referencedColumnName="idbase_submenu")
	 * })
	 */
	private $submenu;

	/**
	 * @var \BaseMenu
	 *
	 * @ORM\ManyToOne(targetEntity="BaseMenu")
	 * @ORM\JoinColumns({
	 *   @ORM\JoinColumn(name="menu", referencedColumnName="idmenu")
	 * })
	 */
	private $menu;
	/**
	 * @return the $idconteudo
	 */
	public function getIdconteudo() {
		return $this->idconteudo;
	}

	/**
	 * @return the $logo
	 */
	public function getLogo() {
		return $this->logo;
	}

	/**
	 * @return the $descricao
	 */
	public function getDescricao() {
		return $this->descricao;
	}

	/**
	 * @return the $src
	 */
	public function getSrc() {
		return $this->src;
	}

	/**
	 * @return the $submenu
	 */
	public function getSubmenu() {
		return $this->submenu;
	}

	/**
	 * @return the $menu
	 */
	public function getMenu() {
		return $this->menu;
	}

	/**
	 * @param number $idconteudo
	 */
	public function setIdconteudo($idconteudo) {
		$this->idconteudo = $idconteudo;
	}

	/**
	 * @param string $logo
	 */
	public function setLogo($logo) {
		$this->logo = $logo;
	}

	/**
	 * @param string $descricao
	 */
	public function setDescricao($descricao) {
		$this->descricao = $descricao;
	}

	/**
	 * @param string $src
	 */
	public function setSrc($src) {
		$this->src = $src;
	}

	/**
	 * @param BaseSubmenu $submenu
	 */
	public function setSubmenu($submenu) {
		$this->submenu = $submenu;
	}

	/**
	 * @param BaseMenu $menu
	 */
	public function setMenu($menu) {
		$this->menu = $menu;
	}
	/**
	 * @return the $fotos
	 */
	public function getFotos() {
		return $this->fotos;
	}

	/**
	 * @param \Base\Entity\ArrayCollection $fotos
	 */
	public function setFotos($fotos) {
		$this->fotos = $fotos;
	}

}


text:
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lousy.Monolith")]
[assembly: AssemblyDescription("Monolith is a Windows library that lets you create animations in codebehind in a fluent, somewhat straightforward manner. It's a wrapper around the Windows.UI.Xaml.Media.Animation library that removes as much of the setup as possible.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Lousy")]
[assembly: AssemblyProduct("Monolith")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
@interface OpenAllCommand : NSScriptCommand
{
}

- (id)performDefaultImplementation;

@end


text:
import { Component, ViewChild } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';

import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 LatLng,
 CameraPosition,
 MarkerOptions,
 Marker
} from '@ionic-native/google-maps';

declare var google: any;

@Component({
  selector: 'page-map',
  templateUrl: 'map.html'
})
export class MapPage {
  @ViewChild('map') map;

  constructor(public navCtrl: NavController, public platform: Platform, private googleMaps: GoogleMaps) {}

  initJSMaps(mapEle) {
    new google.maps.Map(mapEle, {
      center: { lat: 43.071584, lng: -89.380120 },
      zoom: 16
    });
  }

  initNativeMaps(mapEle) {
    this.map = new GoogleMap(mapEle);
    mapEle.classList.add('show-map');

    this.googleMaps.isAvailable().then(() => {
      const position = new LatLng(43.074395, -89.381056);
      this.map.setPosition(position);
    });
  }

  ionViewDidLoad() {
    let mapEle = this.map.nativeElement;

    if (!mapEle) {
      console.error('Unable to initialize map, no map element with #map view reference.');
      return;
    }

    // Disable this switch if you'd like to only use JS maps, as the APIs
    // are slightly different between the two. However, this makes it easy
    // to use native maps while running in Cordova, and JS maps on the web.
    if (this.platform.is('cordova') === true) {
      this.initNativeMaps(mapEle);
    } else {
      this.initJSMaps(mapEle);
    }
  }

}


text:
package org.springframework.ldap.core;

import org.junit.Before;
import org.junit.Test;
import org.springframework.ldap.LimitExceededException;
import org.springframework.ldap.PartialResultException;

import javax.naming.Binding;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.ldap.LdapContext;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Unit tests for the list operations in {@link LdapTemplate}.
 *
 * @author Ulrik Sandberg
 */
public class LdapTemplateListTest {

	private static final String NAME = "o=example.com";

	private static final String CLASS = "com.example.SomeClass";

	private ContextSource contextSourceMock;

	private DirContext dirContextMock;

	private NamingEnumeration namingEnumerationMock;

	private Name nameMock;

	private NameClassPairCallbackHandler handlerMock;

	private ContextMapper contextMapperMock;

	private LdapTemplate tested;

	@Before
	public void setUp() throws Exception {
		// Setup ContextSource mock
		contextSourceMock = mock(ContextSource.class);

		// Setup LdapContext mock
		dirContextMock = mock(LdapContext.class);

		// Setup NamingEnumeration mock
		namingEnumerationMock = mock(NamingEnumeration.class);

		// Setup Name mock
		nameMock = mock(Name.class);

		// Setup Handler mock
		handlerMock = mock(NameClassPairCallbackHandler.class);

		contextMapperMock = mock(ContextMapper.class);

		tested = new LdapTemplate(contextSourceMock);
	}

	private void expectGetReadOnlyContext() {
		when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
	}

	private void setupStringListAndNamingEnumeration(NameClassPair listResult)
			throws NamingException {
		when(dirContextMock.list(NAME)).thenReturn(namingEnumerationMock);

		setupNamingEnumeration(listResult);
	}

	private void setupListAndNamingEnumeration(NameClassPair listResult)
			throws NamingException {
		when(dirContextMock.list(nameMock)).thenReturn(namingEnumerationMock);

		setupNamingEnumeration(listResult);
	}

	private void setupStringListBindingsAndNamingEnumeration(
			NameClassPair listResult) throws NamingException {
		when(dirContextMock.listBindings(NAME)).thenReturn(namingEnumerationMock);

		setupNamingEnumeration(listResult);
	}

	private void setupListBindingsAndNamingEnumeration(NameClassPair listResult)
			throws NamingException {
		when(dirContextMock.listBindings(nameMock)).thenReturn(namingEnumerationMock);

		setupNamingEnumeration(listResult);
	}

	private void setupNamingEnumeration(NameClassPair listResult)
			throws NamingException {
		when(namingEnumerationMock.hasMore()).thenReturn(true, false);
		when(namingEnumerationMock.next()).thenReturn(listResult);
	}

	@Test
	public void testList_Name() throws NamingException {
		expectGetReadOnlyContext();

		NameClassPair listResult = new NameClassPair(NAME, CLASS);

		setupListAndNamingEnumeration(listResult);

		List list = tested.list(nameMock);

		verify(dirContextMock).close();
		verify(namingEnumerationMock).close();

		assertThat(list).isNotNull();
		assertThat(list).hasSize(1);
		assertThat(list.get(0)).isSameAs(NAME);
	}

	@Test
	public void testList_String() throws NamingException {
		expectGetReadOnlyContext();

		NameClassPair listResult = new NameClassPair(NAME, CLASS);

		setupStringListAndNamingEnumeration(listResult);

		List list = tested.list(NAME);

		verify(dirContextMock).close();
		verify(namingEnumerationMock).close();

		assertThat(list).isNotNull();
		assertThat(list).hasSize(1);
		assertThat(list.get(0)).isSameAs(NAME);
	}

	@Test
	public void testList_Name_CallbackHandler() throws NamingException {
		expectGetReadOnlyContext();

		NameClassPair listResult = new NameClassPair(NAME, CLASS);

		setupListAndNamingEnumeration(listResult);

		tested.list(nameMock, handlerMock);

		verify(handlerMock).handleNameClassPair(listResult);
		verify(namingEnumerationMock).close();
		verify(dirContextMock).close();
	}

	@Test
	public void testList_String_CallbackHandler() throws NamingException {
		expectGetReadOnlyContext();

		NameClassPair listResult = new NameClassPair(NAME, CLASS);

		setupStringListAndNamingEnumeration(listResult);

		tested.list("o=example.com", handlerMock);

		verify(handlerMock).handleNameClassPair(listResult);
		verify(namingEnumerationMock).close();
		verify(dirContextMock).close();
	}

	@Test
	public void testList_PartialResultException() throws NamingException {
		expectGetReadOnlyContext();

		javax.naming.PartialResultException pre = new javax.naming.PartialResultException();
		when(dirContextMock.list(NAME)).thenThrow(pre);

		try {
			tested.list(NAME);
			fail("PartialResultException expected");
		} catch (PartialResultException expected) {
			assertThat(true).isTrue();
		}

		verify(dirContextMock).close();
	}

	@Test
	public void testList_PartialResultException_Ignore() throws NamingException {
		expectGetReadOnlyContext();

		javax.naming.PartialResultException pre = new javax.naming.PartialResultException();
		when(dirContextMock.list(NAME)).thenThrow(pre);

		tested.setIgnorePartialResultException(true);

		List list = tested.list(NAME);

		verify(dirContextMock).close();

		assertThat(list).isNotNull();
		assertThat(list).isEmpty();
	}

	@Test
	public void testList_NamingException() throws NamingException {
		expectGetReadOnlyContext();

		javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException();
		when(dirContextMock.list(NAME)).thenThrow(ne);

		try {
			tested.list(NAME);
			fail("LimitExceededException expected");
		} catch (LimitExceededException expected) {
			assertThat(true).isTrue();
		}

		verify(dirContextMock).close();
	}

	// Tests for listBindings

	@Test
	public void testListBindings_String() throws NamingException {
		expectGetReadOnlyContext();

		Binding listResult = new Binding(NAME, CLASS, null);

		setupStringListBindingsAndNamingEnumeration(listResult);

		List list = tested.listBindings(NAME);

		verify(dirContextMock).close();
		verify(namingEnumerationMock).close();

		assertThat(list).isNotNull();
		assertThat(list).hasSize(1);
		assertThat(list.get(0)).isSameAs(NAME);
	}

	@Test
	public void testListBindings_Name() throws NamingException {
		expectGetReadOnlyContext();

		Binding listResult = new Binding(NAME, CLASS, null);

		setupListBindingsAndNamingEnumeration(listResult);

		List list = tested.listBindings(nameMock);

		verify(dirContextMock).close();
		verify(namingEnumerationMock).close();

		assertThat(list).isNotNull();
		assertThat(list).hasSize(1);
		assertThat(list.get(0)).isSameAs(NAME);
	}

	@Test
	public void testListBindings_ContextMapper() throws NamingException {
		expectGetReadOnlyContext();

		Object expectedObject = new Object();
		Binding listResult = new Binding("", expectedObject);

		setupStringListBindingsAndNamingEnumeration(listResult);

		Object expectedResult = expectedObject;
		when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);

		List list = tested.listBindings(NAME, contextMapperMock);

		verify(dirContextMock).close();
		verify(namingEnumerationMock).close();

		assertThat(list).isNotNull();
		assertThat(list).hasSize(1);
		assertThat(list.get(0)).isSameAs(expectedResult);
	}

	@Test
	public void testListBindings_Name_ContextMapper() throws NamingException {
		expectGetReadOnlyContext();

		Object expectedObject = new Object();
		Binding listResult = new Binding("", expectedObject);

		setupListBindingsAndNamingEnumeration(listResult);

		Object expectedResult = expectedObject;
		when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);

		List list = tested.listBindings(nameMock, contextMapperMock);

		verify(dirContextMock).close();
		verify(namingEnumerationMock).close();

		assertThat(list).isNotNull();
		assertThat(list).hasSize(1);
		assertThat(list.get(0)).isSameAs(expectedResult);
	}
}


text:
class Model(object):

    def __init__(self, *args, **kwargs):
        for k, value in kwargs.items():
            if k in dir(self):
                setattr(self, k, value)

    @classmethod
    def to_instance(cls, json):
        return cls(**json)

    def to_json(self):
        return_json = {}

        for field_name in sorted(self.columns()):
            value = getattr(self, field_name)
            if value:
                return_json[field_name] = value

        return return_json

    @classmethod
    def columns(cls):
        raise NotImplementedError()

    @classmethod
    def find(cls, *args, **kwargs):
        raise NotImplementedError()

    @classmethod
    def get(cls, id=None):
        raise NotImplementedError()

    def update(self, dict_fields_to_update):
        return self.__save()

    def put(self):
        result = self.__save()

        if self._hasnt_hooks():
            return result

        if result:

            for hook in self.hooks:
                instance = hook()

                # this is to make AND with the result of all hooks
                # the flow just continue if the result of all hoks is true

                instance.after_save(self)

        return result

    def __save(self):
        if self._hasnt_hooks():
            return True

        all_passed = True
        hooks_didnt_passed = []

        for hook in self.hooks:
            instance = hook()

            # this is to make AND with the result of all hooks
            # the flow just continue if the result of all hoks is true

            if not instance.before_save(self):
                all_passed = False
                hooks_didnt_passed.append(instance.__class__.__name__)

        if not all_passed:
            raise Exception("The hook(s) %s.before_save didnt return True" % ", ".join(hooks_didnt_passed))

        return True

    def delete(self):
        if self._hasnt_hooks():
            return True

        all_passed = True
        hooks_didnt_passed = []

        for hook in self.hooks:
            instance = hook()

            # this is to make AND with the result of all hoks
            # the flow just continue if the result of all hoks is true

            if not instance.before_delete(self):
                all_passed = False
                hooks_didnt_passed.append(instance.__class__.__name__)

        if not all_passed:
            raise Exception("The hook(s) %s.before_delete didnt return True" % ", ".join(hooks_didnt_passed))

        return True

    def _hasnt_hooks(self):
        return not hasattr(self, 'hooks')


text:
<?php

namespace TaskManagement\Entity;

use Doctrine\ORM\Mapping AS ORM;

/**
 * @ORM\Embeddable
 */

class Estimation {

	CONST NOT_ESTIMATED = -1;

	/**
	 * @ORM\Column(type="datetime", nullable=true)
	 * @var DateTime
	 */
	protected $createdAt;

	/**
	 * @ORM\Column(type="float", precision=10, scale=2, nullable=true)
	 * @var float
	 */
	private $value;

	public function __construct($value, \DateTime $createdAt) {
		$this->value = $value;
		$this->createdAt = $createdAt;
	}

	public function getValue() {
		return $this->value;
	}

	public function getCreatedAt() {
		return $this->createdAt;
	}

}


text:
package de.kaiserpfalzedv.iam.tenant.client.impl;

import java.io.IOException;
import java.io.Serializable;
import java.util.Properties;
import java.util.UUID;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;

import de.kaiserpfalzedv.commons.api.action.commands.CrudCommandBuilder;
import de.kaiserpfalzedv.commons.api.action.commands.CrudCommandBuilderCreator;
import de.kaiserpfalzedv.commons.api.cdi.Implementation;
import de.kaiserpfalzedv.commons.api.config.ConfigReader;
import de.kaiserpfalzedv.commons.api.data.paging.Pageable;
import de.kaiserpfalzedv.commons.api.data.paging.PageableBuilder;
import de.kaiserpfalzedv.commons.api.data.paging.PagedListable;
import de.kaiserpfalzedv.commons.api.data.query.Predicate;
import de.kaiserpfalzedv.commons.api.messaging.MessageInfo;
import de.kaiserpfalzedv.commons.api.messaging.MessageSender;
import de.kaiserpfalzedv.commons.api.messaging.MessagingCore;
import de.kaiserpfalzedv.commons.api.messaging.NoBrokerException;
import de.kaiserpfalzedv.commons.api.messaging.NoResponseException;
import de.kaiserpfalzedv.commons.api.messaging.ResponseOfWrongTypeException;
import de.kaiserpfalzedv.commons.client.messaging.MessageSenderImpl;
import de.kaiserpfalzedv.commons.impl.config.ConfigReaderBuilder;
import de.kaiserpfalzedv.iam.tenant.api.Tenant;
import de.kaiserpfalzedv.iam.tenant.api.TenantDoesNotExistException;
import de.kaiserpfalzedv.iam.tenant.api.TenantExistsException;
import de.kaiserpfalzedv.iam.tenant.api.TenantPredicate;
import de.kaiserpfalzedv.iam.tenant.api.commands.TenantCreateCommand;
import de.kaiserpfalzedv.iam.tenant.api.commands.TenantDeleteCommand;
import de.kaiserpfalzedv.iam.tenant.api.commands.TenantRetrieveCommand;
import de.kaiserpfalzedv.iam.tenant.api.commands.TenantUpdateCommand;
import de.kaiserpfalzedv.iam.tenant.api.replies.TenantContainingBaseReply;
import de.kaiserpfalzedv.iam.tenant.api.replies.TenantCreateReply;
import de.kaiserpfalzedv.iam.tenant.api.replies.TenantDeleteReply;
import de.kaiserpfalzedv.iam.tenant.api.replies.TenantRetrieveReply;
import de.kaiserpfalzedv.iam.tenant.api.replies.TenantUpdateReply;
import de.kaiserpfalzedv.iam.tenant.client.TenantClient;
import de.kaiserpfalzedv.iam.tenant.client.TenantClientCommunicationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static de.kaiserpfalzedv.commons.api.action.CrudCommandType.CREATE;
import static de.kaiserpfalzedv.commons.api.action.CrudCommandType.RETRIEVE;

/**
 * @author rlichti {@literal <rlichti@kaiserpfalz-edv.de>}
 * @since 2016-09-20
 */
@Implementation
@ApplicationScoped
public class TenantClientImpl implements TenantClient, Serializable {
    private static final Logger LOG = LoggerFactory.getLogger(TenantClientImpl.class);

    private MessagingCore messaging;
    private ConfigReader config;
    private UUID clientId = UUID.randomUUID();

    private CrudCommandBuilderCreator<Tenant> commandCreator;
    private String destination;

    @Inject
    public TenantClientImpl(
            @NotNull final ConfigReader config,
            @NotNull final MessagingCore messaging
    ) {
        this.config = config;
        this.messaging = messaging;
    }

    @Override
    public Tenant create(Tenant data) throws TenantExistsException {
        CrudCommandBuilder<TenantCreateCommand, Tenant> commandBuilder
                = new CrudCommandBuilder<TenantCreateCommand, Tenant>(TenantCreateCommand.class, commandCreator)
                .withSource(clientId)
                .withData(data)
                .create();

        TenantCreateCommand command = commandBuilder.build();

        MessageSender<TenantCreateCommand, TenantCreateReply> sender = new MessageSenderImpl<>(messaging);
        sender.withPayload(command);

        return getTenantFromResponse(sender, data.getId());
    }

    @Override
    public Tenant retrieve(UUID id) throws TenantDoesNotExistException {
        return retrieve(
                TenantPredicate.id().isEqualTo(id),
                new PageableBuilder()
                        .withPage(new PageableBuilder().withPage(1).withSize(5).build())
                        .build()
        ).getEntries().get(0);
    }

    @Override
    public PagedListable<Tenant> retrieve(
            @NotNull final Predicate<Tenant> predicate,
            @NotNull final Pageable page
    ) {
        CrudCommandBuilder<TenantRetrieveCommand, Tenant> commandBuilder
                = new CrudCommandBuilder<TenantRetrieveCommand, Tenant>(TenantRetrieveCommand.class, commandCreator)
                .withSource(clientId)
                .withPredicate(predicate)
                .withPage(page)
                .retrieve();

        TenantRetrieveCommand command = commandBuilder.build();

        MessageInfo response = null;
        UUID correlationId = UUID.randomUUID();
        try (MessageSender<TenantRetrieveCommand, TenantRetrieveReply> sender = new MessageSenderImpl<>(messaging)) {
            sender.withPayload(command);

            response = sender
                    .withDestination(destination)
                    .withCorrelationId(correlationId.toString())
                    .withResponse()
                    .sendMessage();

            return ((TenantRetrieveReply) response.waitForResponse()).getTenants();
        } catch (NoBrokerException | ClassCastException | InterruptedException | NoResponseException
                | ResponseOfWrongTypeException e) {
            throw new TenantClientCommunicationException(
                    RETRIEVE,
                    correlationId,
                    e.getMessage(),
                    e
            );
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error(e.getClass().getSimpleName() + " caught: " + e.getMessage(), e);
                }
            }
        }
    }

    @Override
    public Tenant update(Tenant data) throws TenantDoesNotExistException {
        CrudCommandBuilder<TenantUpdateCommand, Tenant> commandBuilder
                = new CrudCommandBuilder<TenantUpdateCommand, Tenant>(TenantUpdateCommand.class, commandCreator)
                .withSource(clientId)
                .withData(data)
                .update();

        TenantUpdateCommand command = commandBuilder.build();

        MessageSender<TenantUpdateCommand, TenantUpdateReply> sender = new MessageSenderImpl<>(messaging);
        sender.withPayload(command);

        return getTenantFromResponse(sender, data.getId());
    }

    @Override
    public void delete(UUID id) {
        CrudCommandBuilder<TenantDeleteCommand, Tenant> commandBuilder
                = new CrudCommandBuilder<TenantDeleteCommand, Tenant>(TenantDeleteCommand.class, commandCreator)
                .withSource(clientId)
                .withId(id)
                .delete();

        TenantDeleteCommand command = commandBuilder.build();

        MessageInfo<TenantDeleteReply> response = null;
        UUID correlationId = UUID.randomUUID();
        try (MessageSender<TenantDeleteCommand, TenantDeleteReply> sender = new MessageSenderImpl<>(messaging)) {
            sender.withPayload(command);

            response = sender
                    .withDestination(destination)
                    .withCorrelationId(correlationId.toString())
                    .withResponse()
                    .sendMessage();

            response.waitForResponse();
        } catch (NoBrokerException | ResponseOfWrongTypeException | NoResponseException | InterruptedException e) {
            throw new TenantClientCommunicationException(
                    CREATE,
                    correlationId,
                    "",
                    id,
                    e
            );
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error(e.getClass().getSimpleName() + " caught: " + e.getMessage(), e);
                }
            }
        }
    }

    private Tenant getTenantFromResponse(MessageSender sender, final UUID tenantId) {

        MessageInfo response = null;
        try {
            response = sender
                    .withDestination(destination)
                    .withResponse()
                    .sendMessage();

            return ((TenantContainingBaseReply) response.waitForResponse()).getTenant();
        } catch (NoBrokerException | ResponseOfWrongTypeException | NoResponseException | InterruptedException e) {
            throw new TenantClientCommunicationException(
                    CREATE,
                    UUID.fromString(sender.getCorrelationId()),
                    "",
                    tenantId,
                    e
            );
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error(e.getClass().getSimpleName() + " caught: " + e.getMessage(), e);
                }
            }
        }
    }

    @Override
    public void close() {
        messaging = null;
        config = null;
        clientId = null;
        destination = null;
    }

    @Override
    public void init() {
        this.destination = config.getEntry("tenant.queue", "tenant");
    }

    @Override
    public void init(Properties properties) {
        config = new ConfigReaderBuilder().withProperties(properties).build();

        init();
    }

}


text:
package com.palantir.atlasdb.jepsen.events;

import com.palantir.atlasdb.jepsen.CheckerResult;
import java.util.List;

public interface Checker {
    CheckerResult check(List<Event> events);
}


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

<title>com.jogamp.opengl.util (JOGL, NativeWindow and NEWT APIs)</title>
<meta name="date" content="2014-01-31">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.jogamp.opengl.util

Interface Summary

Interface
Description

AnimatorBase.AnimatorImpl

GLArrayDataEditable

The total number of bytes hold by the referenced buffer is:
 getComponentSize()* getComponentNumber() * getElementNumber()

GLPixelBuffer.GLPixelBufferProvider

Allows user to interface with another toolkit to define GLPixelBuffer.GLPixelAttributes and memory buffer to produce TextureData.

GLPixelBuffer.SingletonGLPixelBufferProvider

Single GLPixelBuffer provider.

TileRendererBase.TileRendererListener

Listener for tile renderer events, intended to extend GLEventListener implementations,
 enabling tile rendering via TileRendererBase.attachAutoDrawable(GLAutoDrawable).

Class Summary

Class
Description

Animator

 An Animator can be attached to one or more GLAutoDrawables to drive their display() methods in a loop.

AnimatorBase

Base implementation of GLAnimatorControl

FPSAnimator

An Animator subclass which attempts to achieve a target
 frames-per-second rate to avoid using all CPU time.

Gamma

Provides control over the primary display's gamma, brightness and
    contrast controls via the hardware gamma ramp tables.

GLArrayDataClient

GLArrayDataServer

GLArrayDataWrapper

GLBuffers

Utility routines for dealing with direct buffers.

GLDrawableUtil

Providing utility functions dealing w/ GLDrawables, GLAutoDrawable and their GLEventListener.

GLPixelBuffer

OpenGL pixel data buffer, allowing user to provide buffers via their GLPixelBuffer.GLPixelBufferProvider implementation.

GLPixelBuffer.DefaultGLPixelBufferProvider

GLPixelBuffer.GLPixelAttributes

Pixel attributes.

GLPixelStorageModes

Utility to safely set and restore the pack and unpack pixel storage mode,
 regardless of the GLProfile.

GLReadBufferUtil

Utility to read out the current FB to TextureData, optionally writing the data back to a texture object.

ImmModeSink

 Immediate mode sink, implementing OpenGL fixed function subset of immediate mode operations, i.e.

PMVMatrix

PMVMatrix implements a subset of the fixed function pipeline
 regarding the projection (P), modelview (Mv) matrix operation
 which is specified in GLMatrixFunc.

PNGPixelRect

RandomTileRenderer

Variation of TileRenderer w/o using fixed tiles but arbitrary rectangular regions.

TGAWriter

Utility class which helps take fast screenshots of OpenGL rendering
 results into Targa-format files.

TileRenderer

A fairly direct port of Brian Paul's tile rendering library, found
 at
 http://www.mesa3d.org/brianp/TR.html  .

TileRendererBase

A fairly direct port of Brian Paul's tile rendering library, found
 at
 http://www.mesa3d.org/brianp/TR.html  .

TimeFrameI

Integer time frame in milliseconds, maybe specialized for texture/video, audio, ..

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright 2010 JogAmp Community.


text:
<?xml version="1.0"?>
<test>
<setup>
  <system file="exercise-14-system.xml.gz"/>
  <channel name="test" file="exercise-14-packages.xml.gz"/>
</setup>
<trial>
  <install channel="test" package="D"/>
</trial>
</test>


text:
package com.spring.sample.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value="/help")
public class HelpController extends BaseController {

	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "help";
	}
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: tensorflow/core/framework/reader_base.proto

#ifndef PROTOBUF_tensorflow_2fcore_2fframework_2freader_5fbase_2eproto__INCLUDED
#define PROTOBUF_tensorflow_2fcore_2fframework_2freader_5fbase_2eproto__INCLUDED

#include <string>

#include <google/protobuf/stubs/common.h>

#if GOOGLE_PROTOBUF_VERSION < 3003000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 3003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif

#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>  // IWYU pragma: export
#include <google/protobuf/extension_set.h>  // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace tensorflow {
class ReaderBaseState;
class ReaderBaseStateDefaultTypeInternal;
extern ReaderBaseStateDefaultTypeInternal _ReaderBaseState_default_instance_;
}  // namespace tensorflow

namespace tensorflow {

namespace protobuf_tensorflow_2fcore_2fframework_2freader_5fbase_2eproto {
// Internal implementation detail -- do not call these.
struct TableStruct {
  static const ::google::protobuf::internal::ParseTableField entries[];
  static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
  static const ::google::protobuf::internal::ParseTable schema[];
  static const ::google::protobuf::uint32 offsets[];
  static void InitDefaultsImpl();
  static void Shutdown();
};
void AddDescriptors();
void InitDefaults();
}  // namespace protobuf_tensorflow_2fcore_2fframework_2freader_5fbase_2eproto

// ===================================================================

class ReaderBaseState : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tensorflow.ReaderBaseState) */ {
 public:
  ReaderBaseState();
  virtual ~ReaderBaseState();

  ReaderBaseState(const ReaderBaseState& from);

  inline ReaderBaseState& operator=(const ReaderBaseState& from) {
    CopyFrom(from);
    return *this;
  }

  inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
    return GetArenaNoVirtual();
  }
  inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
    return MaybeArenaPtr();
  }
  static const ::google::protobuf::Descriptor* descriptor();
  static const ReaderBaseState& default_instance();

  static inline const ReaderBaseState* internal_default_instance() {
    return reinterpret_cast<const ReaderBaseState*>(
               &_ReaderBaseState_default_instance_);
  }
  static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
    0;

  void UnsafeArenaSwap(ReaderBaseState* other);
  void Swap(ReaderBaseState* other);

  // implements Message ----------------------------------------------

  inline ReaderBaseState* New() const PROTOBUF_FINAL { return New(NULL); }

  ReaderBaseState* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
  void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
  void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
  void CopyFrom(const ReaderBaseState& from);
  void MergeFrom(const ReaderBaseState& from);
  void Clear() PROTOBUF_FINAL;
  bool IsInitialized() const PROTOBUF_FINAL;

  size_t ByteSizeLong() const PROTOBUF_FINAL;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
  ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
      bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
  int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const PROTOBUF_FINAL;
  void InternalSwap(ReaderBaseState* other);
  protected:
  explicit ReaderBaseState(::google::protobuf::Arena* arena);
  private:
  static void ArenaDtor(void* object);
  inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
  private:
  inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
    return _internal_metadata_.arena();
  }
  inline void* MaybeArenaPtr() const {
    return _internal_metadata_.raw_arena_ptr();
  }
  public:

  ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // bytes current_work = 4;
  void clear_current_work();
  static const int kCurrentWorkFieldNumber = 4;
  const ::std::string& current_work() const;
  void set_current_work(const ::std::string& value);
  void set_current_work(const char* value);
  void set_current_work(const void* value, size_t size);
  ::std::string* mutable_current_work();
  ::std::string* release_current_work();
  void set_allocated_current_work(::std::string* current_work);
  ::std::string* unsafe_arena_release_current_work();
  void unsafe_arena_set_allocated_current_work(
      ::std::string* current_work);

  // int64 work_started = 1;
  void clear_work_started();
  static const int kWorkStartedFieldNumber = 1;
  ::google::protobuf::int64 work_started() const;
  void set_work_started(::google::protobuf::int64 value);

  // int64 work_finished = 2;
  void clear_work_finished();
  static const int kWorkFinishedFieldNumber = 2;
  ::google::protobuf::int64 work_finished() const;
  void set_work_finished(::google::protobuf::int64 value);

  // int64 num_records_produced = 3;
  void clear_num_records_produced();
  static const int kNumRecordsProducedFieldNumber = 3;
  ::google::protobuf::int64 num_records_produced() const;
  void set_num_records_produced(::google::protobuf::int64 value);

  // @@protoc_insertion_point(class_scope:tensorflow.ReaderBaseState)
 private:

  ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
  friend class ::google::protobuf::Arena;
  typedef void InternalArenaConstructable_;
  typedef void DestructorSkippable_;
  ::google::protobuf::internal::ArenaStringPtr current_work_;
  ::google::protobuf::int64 work_started_;
  ::google::protobuf::int64 work_finished_;
  ::google::protobuf::int64 num_records_produced_;
  mutable int _cached_size_;
  friend struct protobuf_tensorflow_2fcore_2fframework_2freader_5fbase_2eproto::TableStruct;
};
// ===================================================================

// ===================================================================

#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// ReaderBaseState

// int64 work_started = 1;
inline void ReaderBaseState::clear_work_started() {
  work_started_ = GOOGLE_LONGLONG(0);
}
inline ::google::protobuf::int64 ReaderBaseState::work_started() const {
  // @@protoc_insertion_point(field_get:tensorflow.ReaderBaseState.work_started)
  return work_started_;
}
inline void ReaderBaseState::set_work_started(::google::protobuf::int64 value) {

  work_started_ = value;
  // @@protoc_insertion_point(field_set:tensorflow.ReaderBaseState.work_started)
}

// int64 work_finished = 2;
inline void ReaderBaseState::clear_work_finished() {
  work_finished_ = GOOGLE_LONGLONG(0);
}
inline ::google::protobuf::int64 ReaderBaseState::work_finished() const {
  // @@protoc_insertion_point(field_get:tensorflow.ReaderBaseState.work_finished)
  return work_finished_;
}
inline void ReaderBaseState::set_work_finished(::google::protobuf::int64 value) {

  work_finished_ = value;
  // @@protoc_insertion_point(field_set:tensorflow.ReaderBaseState.work_finished)
}

// int64 num_records_produced = 3;
inline void ReaderBaseState::clear_num_records_produced() {
  num_records_produced_ = GOOGLE_LONGLONG(0);
}
inline ::google::protobuf::int64 ReaderBaseState::num_records_produced() const {
  // @@protoc_insertion_point(field_get:tensorflow.ReaderBaseState.num_records_produced)
  return num_records_produced_;
}
inline void ReaderBaseState::set_num_records_produced(::google::protobuf::int64 value) {

  num_records_produced_ = value;
  // @@protoc_insertion_point(field_set:tensorflow.ReaderBaseState.num_records_produced)
}

// bytes current_work = 4;
inline void ReaderBaseState::clear_current_work() {
  current_work_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& ReaderBaseState::current_work() const {
  // @@protoc_insertion_point(field_get:tensorflow.ReaderBaseState.current_work)
  return current_work_.Get();
}
inline void ReaderBaseState::set_current_work(const ::std::string& value) {

  current_work_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
  // @@protoc_insertion_point(field_set:tensorflow.ReaderBaseState.current_work)
}
inline void ReaderBaseState::set_current_work(const char* value) {
  GOOGLE_DCHECK(value != NULL);

  current_work_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
              GetArenaNoVirtual());
  // @@protoc_insertion_point(field_set_char:tensorflow.ReaderBaseState.current_work)
}
inline void ReaderBaseState::set_current_work(const void* value,
    size_t size) {

  current_work_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
      reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
  // @@protoc_insertion_point(field_set_pointer:tensorflow.ReaderBaseState.current_work)
}
inline ::std::string* ReaderBaseState::mutable_current_work() {

  // @@protoc_insertion_point(field_mutable:tensorflow.ReaderBaseState.current_work)
  return current_work_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* ReaderBaseState::release_current_work() {
  // @@protoc_insertion_point(field_release:tensorflow.ReaderBaseState.current_work)

  return current_work_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* ReaderBaseState::unsafe_arena_release_current_work() {
  // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.ReaderBaseState.current_work)
  GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);

  return current_work_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
      GetArenaNoVirtual());
}
inline void ReaderBaseState::set_allocated_current_work(::std::string* current_work) {
  if (current_work != NULL) {

  } else {

  }
  current_work_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), current_work,
      GetArenaNoVirtual());
  // @@protoc_insertion_point(field_set_allocated:tensorflow.ReaderBaseState.current_work)
}
inline void ReaderBaseState::unsafe_arena_set_allocated_current_work(
    ::std::string* current_work) {
  GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
  if (current_work != NULL) {

  } else {

  }
  current_work_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
      current_work, GetArenaNoVirtual());
  // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.ReaderBaseState.current_work)
}

#endif  // !PROTOBUF_INLINE_NOT_IN_HEADERS

// @@protoc_insertion_point(namespace_scope)

}  // namespace tensorflow

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_tensorflow_2fcore_2fframework_2freader_5fbase_2eproto__INCLUDED


text:
@implementation CameraImageHelper
@synthesize session,  image;
static CameraImageHelper *sharedInstance = nil;

// Autorelease pool added thanks to suggestion by Josh Snyder
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
//	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    @autoreleasepool
    {
        CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
        CVPixelBufferLockBaseAddress(imageBuffer,0);
        uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
        size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
        size_t width = CVPixelBufferGetWidth(imageBuffer);
        size_t height = CVPixelBufferGetHeight(imageBuffer);

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
        CGImageRef newImage = CGBitmapContextCreateImage(context);
        CVPixelBufferUnlockBaseAddress(imageBuffer,0);

        self.image = [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationRight];

        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        CGImageRelease(newImage);
    }
//	[pool drain];
}

- (void) initialize
{
	NSError *error;
	AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo] error:&error];
	if (!captureInput)
	{
		NSLog(@"Error: %@", error);
		return;
	}

	// Update thanks to Jake Marsh who points out not to use the main queue
	dispatch_queue_t queue = dispatch_queue_create("com.myapp.tasks.grabcameraframes", NULL);
	AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
	captureOutput.alwaysDiscardsLateVideoFrames = YES;
	[captureOutput setSampleBufferDelegate:self queue:queue];
	// dispatch_release(queue); // Will not work when uncommented -- apparently reference count is altered by setSampleBufferDelegate:queue:

	NSDictionary *settings = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA] forKey:(NSString *)kCVPixelBufferPixelFormatTypeKey];
	[captureOutput setVideoSettings:settings];

	self.session = [[AVCaptureSession alloc] init];
	[self.session addInput:captureInput];
	[self.session addOutput:captureOutput];
}

- (id) init
{
	if (self = [super init]) [self initialize];
	return self;
}

- (UIView *) previewWithBounds: (CGRect) bounds
{
	UIView *view = [[UIView alloc] initWithFrame:bounds];

	AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession: self.session];
	preview.frame = bounds;
	preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
	[view.layer addSublayer: preview];

	return view;
}

- (void) dealloc
{
	self.session = nil;
	self.image = nil;
	//[super dealloc];
}

#pragma mark Class Interface

+ (id) sharedInstance // private
{
	if(!sharedInstance) sharedInstance = [[self alloc] init];
    return sharedInstance;
}

+ (void) startRunning
{
	[[[self sharedInstance] session] startRunning];
}

+ (void) stopRunning
{
	[[[self sharedInstance] session] stopRunning];
}

+ (UIImage *) image
{
	return [[self sharedInstance] image];
}

+ (UIView *) previewWithBounds: (CGRect) bounds
{
	return [[self sharedInstance] previewWithBounds: (CGRect) bounds];
}

@end


text:
from setuptools import setup
import ast
import os
import re

def _read(fn):
    path = os.path.join(os.path.dirname(__file__), fn)

    return open(path).read()

_version_re = re.compile(r'__version__\s+=\s+(.*)')

with open('flickr2markdown/__init__.py', 'rb') as f:
    version = str(ast.literal_eval(_version_re.search(
        f.read().decode('utf-8')).group(1)))

setup(
    name='flickr2markdown',
    version=version,
    url='https://github.com/xsteadfastx/flickr2markdown',
    license='MIT',
    author='Marvin Steadfast',
    author_email='marvin@xsteadfastx.org',
    description='A tool to get a number of flickr uploads or '
                'single pictures and create markdown strings out of them',
    long_description=_read('README.rst'),
    packages=['flickr2markdown'],
    platforms='any',
    install_requires=[
        'Click',
        'requests'
    ],
    keywords=['markdown', 'flickr'],
    classifiers=[
        'Environment :: Console',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3'
    ],
    entry_points={
        'console_scripts': [
            'flickr2markdown = flickr2markdown.ui:main'
        ]
    }
)


text:
var assert = require("assert");
var http = require("ringo/utils/http");

exports.testUrlEncode = function() {
    var encoded, expected;
    encoded = http.urlEncode({foo: 1, bar: "baz"});
    expected = "foo=1&bar=baz";
    assert.strictEqual(encoded, expected);
    encoded = http.urlEncode({foo: [1, 2, 3, 4, 5], bar: "baz"});
    expected = "foo=1&foo=2&foo=3&foo=4&foo=5&bar=baz";
    assert.strictEqual(encoded, expected);
};


text:
// -------------------------------------------------------------------------------------------------------------------
// <copyright company="Gemotial" file="BasePage.cs" project="RunnersTimeManagement.WP8" date="2014-06-08 14:32">
//
// </copyright>
// -------------------------------------------------------------------------------------------------------------------

namespace RunnersTimeManagement.WP8
{
    using System.ComponentModel;

    using Microsoft.Phone.Controls;

    public class BasePage : PhoneApplicationPage, INotifyPropertyChanged
    {
        private bool isBusy;
        public bool IsBusy
        {
            get
            {
                return isBusy;
            }
            set
            {
                if (isBusy != value)
                {
                    isBusy = value;
                    this.OnPropertyChanged("IsBusy");
                }
            }
        }
        public string Message { get; set; }

        public BasePage()
        {
            Message = "Working";
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}