text:
export * from "./common";
export * from "./ActionOptions";
export * from "./StateOptions";
export * from "./StateOptionsEx";

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import { CodeActionProvider, TextDocument, Range, CancellationToken, CodeActionContext, Command, commands, Uri, workspace, WorkspaceEdit, TextEdit, Position, FormattingOptions, window } from 'vscode';

import * as Proto from '../protocol';
import { ITypescriptServiceClient } from '../typescriptService';

interface NumberSet {
	[key: number]: boolean;
}

interface Source {
	uri: Uri;
	version: number;
	range: Range;
	formattingOptions: FormattingOptions | undefined;
}

export default class TypeScriptCodeActionProvider implements CodeActionProvider {
	private commandId: string;

	private supportedCodeActions: Promise<NumberSet>;

	constructor(
		private client: ITypescriptServiceClient,
		modeId: string
	) {
		this.commandId = `typescript.codeActions.${modeId}`;
		this.supportedCodeActions = client.execute('getSupportedCodeFixes', null, undefined)
			.then(response => response.body || [])
			.then(codes => {
				return codes.map(code => +code).filter(code => !isNaN(code));
			})
			.then(codes =>
				codes.reduce((obj, code) => {
					obj[code] = true;
					return obj;
				}, Object.create(null)));

		commands.registerCommand(this.commandId, this.onCodeAction, this);
	}

	public provideCodeActions(document: TextDocument, range: Range, context: CodeActionContext, token: CancellationToken): Thenable<Command[]> {
		const file = this.client.normalizePath(document.uri);
		if (!file) {
			return Promise.resolve<Command[]>([]);
		}
		let editor = window.activeTextEditor && window.activeTextEditor.document === document ? window.activeTextEditor : undefined;
		const source: Source = {
			uri: document.uri,
			version: document.version,
			range: range,
			formattingOptions: editor
				? { tabSize: editor.options.tabSize, insertSpaces: editor.options.insertSpaces } as FormattingOptions : undefined
		};
		return this.getSupportedCodeActions(context)
			.then(supportedActions => {
				return this.client.execute('getCodeFixes', {
					file: file,
					startLine: range.start.line + 1,
					endLine: range.end.line + 1,
					startOffset: range.start.character + 1,
					endOffset: range.end.character + 1,
					errorCodes: supportedActions
				}, token);
			})
			.then(response => response.body || [])
			.then(codeActions => codeActions.map(action => this.actionToEdit(source, action)));
	}

	private getSupportedCodeActions(context: CodeActionContext): Thenable<number[]> {
		return this.supportedCodeActions
			.then(supportedActions => {
				return context.diagnostics
					.map(diagnostic => +diagnostic.code)
					.filter(code => supportedActions[code]);
			});
	}

	private actionToEdit(source: Source, action: Proto.CodeAction): Command {
		const workspaceEdit = new WorkspaceEdit();
		action.changes.forEach(change => {
			change.textChanges.forEach(textChange => {
				workspaceEdit.replace(this.client.asUrl(change.fileName),
					new Range(
						textChange.start.line - 1, textChange.start.offset - 1,
						textChange.end.line - 1, textChange.end.offset - 1),
					textChange.newText);
			});
		});
		return {
			title: action.description,
			command: this.commandId,
			arguments: [source, workspaceEdit]
		};
	}

	private onCodeAction(source: Source, workspaceEdit: WorkspaceEdit) {
		workspace.applyEdit(workspaceEdit).then(success => {
			if (!success) {
				return Promise.reject<boolean>(false);
			}

			let firstEdit: TextEdit | null = null;
			for (const [uri, edits] of workspaceEdit.entries()) {
				if (uri.fsPath === source.uri.fsPath) {
					firstEdit = edits[0];
					break;
				}
			}

			if (!firstEdit) {
				return true;
			}

			const newLines = firstEdit.newText.match(/\n/g);
			const editedRange = new Range(
				new Position(firstEdit.range.start.line, 0),
				new Position(firstEdit.range.end.line + 1 + (newLines ? newLines.length : 0), 0));

			// TODO: Workaround for https://github.com/Microsoft/TypeScript/issues/12249
			// apply formatting to the source range until TS returns formatted results
			return commands.executeCommand('vscode.executeFormatRangeProvider', source.uri, editedRange, source.formattingOptions || {}).then((edits: TextEdit[]) => {
				if (!edits || !edits.length) {
					return false;
				}
				const workspaceEdit = new WorkspaceEdit();
				workspaceEdit.set(source.uri, edits);
				return workspace.applyEdit(workspaceEdit);
			});
		});
	}
}


text:
(function(module, io) {
    module.exports = {
        "parse uri": function() {
            var http = io.util.parseUri("http://google.com"), https = io.util.parseUri("https://www.google.com:80"), query = io.util.parseUri("google.com:8080/foo/bar?foo=bar");
            http.protocol.should().eql("http");
            http.port.should().eql("");
            http.host.should().eql("google.com");
            https.protocol.should().eql("https");
            https.port.should().eql("80");
            https.host.should().eql("www.google.com");
            query.port.should().eql("8080");
            query.query.should().eql("foo=bar");
            query.path.should().eql("/foo/bar");
            query.relative.should().eql("/foo/bar?foo=bar");
        },
        "unique uri": function() {
            var protocol = io.util.parseUri("http://google.com"), noprotocol = io.util.parseUri("google.com"), https = io.util.parseUri("https://google.com"), path = io.util.parseUri("https://google.com/google.com/com/?foo=bar");
            if ("object" == typeof window) {
                io.util.uniqueUri(protocol).should().eql("http://google.com:3000");
                io.util.uniqueUri(noprotocol).should().eql("http://google.com:3000");
            } else {
                io.util.uniqueUri(protocol).should().eql("http://google.com:80");
                io.util.uniqueUri(noprotocol).should().eql("http://google.com:80");
            }
            io.util.uniqueUri(https).should().eql("https://google.com:443");
            io.util.uniqueUri(path).should().eql("https://google.com:443");
        },
        "chunk query string": function() {
            io.util.chunkQuery("foo=bar").should().be.a("object");
            io.util.chunkQuery("foo=bar").foo.should().eql("bar");
        },
        "merge query strings": function() {
            var base = io.util.query("foo=bar", "foo=baz"), add = io.util.query("foo=bar", "bar=foo");
            base.should().eql("?foo=baz");
            add.should().eql("?foo=bar&bar=foo");
            io.util.query("", "").should().eql("");
            io.util.query("foo=bar", "").should().eql("?foo=bar");
            io.util.query("", "foo=bar").should().eql("?foo=bar");
        },
        request: function() {
            var type = typeof io.util.request();
            type.should().eql("object");
        },
        "is array": function() {
            io.util.isArray([]).should().be_true;
            io.util.isArray({}).should().be_false;
            io.util.isArray("str").should().be_false;
            io.util.isArray(new Date()).should().be_false;
            io.util.isArray(true).should().be_false;
            io.util.isArray(arguments).should().be_false;
        },
        "merge, deep merge": function() {
            var start = {
                foo: "bar",
                bar: "baz"
            }, duplicate = {
                foo: "foo",
                bar: "bar"
            }, extra = {
                ping: "pong"
            }, deep = {
                level1: {
                    foo: "bar",
                    level2: {
                        foo: "bar",
                        level3: {
                            foo: "bar",
                            rescursive: deep
                        }
                    }
                }
            }, deeper = {
                foo: "bar",
                level1: {
                    foo: "baz",
                    level2: {
                        foo: "foo",
                        level3: {
                            foo: "pewpew",
                            rescursive: deep
                        }
                    }
                }
            };
            io.util.merge(start, duplicate);
            start.foo.should().eql("foo");
            start.bar.should().eql("bar");
            io.util.merge(start, extra);
            start.ping.should().eql("pong");
            start.foo.should().eql("foo");
            io.util.merge(deep, deeper);
            deep.foo.should().eql("bar");
            deep.level1.foo.should().eql("baz");
            deep.level1.level2.foo.should().eql("foo");
            deep.level1.level2.level3.foo.should().eql("pewpew");
        },
        defer: function(next) {
            var now = +new Date();
            io.util.defer(function() {
                (new Date() - now >= (io.util.webkit ? 100 : 0)).should().be_true();
                next();
            });
        },
        indexOf: function() {
            var data = [ "socket", 2, 3, 4, "socket", 5, 6, 7, "io" ];
            io.util.indexOf(data, "socket", 1).should().eql(4);
            io.util.indexOf(data, "socket").should().eql(0);
            io.util.indexOf(data, "waffles").should().eql(-1);
        }
    };
})("undefined" == typeof module ? module = {} : module, "undefined" == typeof io ? require("socket.io-client") : io, "undefined" == typeof should ? require("should") : should);


text:
package org.apache.derby.client.am;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Calendar;

import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ParameterMetaData;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Time;
import java.sql.Timestamp;

import org.apache.derby.client.am.stmtcache.StatementKey;

/**
 * A wrapper class for a physical Derby prepared statement.
 * <p>
 * The idea behind the logical prepared statement is to allow reuse of the
 * physical prepared statement. In general the logical entity will forward all
 * calls to the physical entity. A few methods have special implementations, the
 * most important one being {@link #close}. Each method will check that the
 * logical statement is still open before the call is forwarded to the
 * underlying physical statement.
 *
 * @see LogicalStatementEntity
 */
public class LogicalPreparedStatement
    extends LogicalStatementEntity
    implements java.sql.PreparedStatement {

    /**
     * Creates a new logical prepared statement.
     *
     * @param physicalPs underlying physical statement
     * @param stmtKey key for the physical statement
     * @param cacheInteractor creating statement cache interactor
     * @throws IllegalArgumentException if {@code cache} is {@code null}
     */
    public LogicalPreparedStatement(java.sql.PreparedStatement physicalPs,
                                    StatementKey stmtKey,
                                    StatementCacheInteractor cacheInteractor) {
        super(physicalPs, stmtKey, cacheInteractor);
    }

    public int executeUpdate() throws SQLException {
        return getPhysPs().executeUpdate();
    }

    public void addBatch() throws SQLException {
         getPhysPs().addBatch();
    }

    public void clearParameters() throws SQLException {
         getPhysPs().clearParameters();
    }

    public boolean execute() throws SQLException {
        return getPhysPs().execute();
    }

    public void setByte(int parameterIndex, byte x) throws SQLException {
         getPhysPs().setByte(parameterIndex, x);
    }

    public void setDouble(int parameterIndex, double x) throws SQLException {
         getPhysPs().setDouble(parameterIndex, x);
    }

    public void setFloat(int parameterIndex, float x) throws SQLException {
         getPhysPs().setFloat(parameterIndex, x);
    }

    public void setInt(int parameterIndex, int x) throws SQLException {
         getPhysPs().setInt(parameterIndex, x);
    }

    public void setNull(int parameterIndex, int sqlType) throws SQLException {
         getPhysPs().setNull(parameterIndex, sqlType);
    }

    public void setLong(int parameterIndex, long x) throws SQLException {
         getPhysPs().setLong(parameterIndex, x);
    }

    public void setShort(int parameterIndex, short x) throws SQLException {
         getPhysPs().setShort(parameterIndex, x);
    }

    public void setBoolean(int parameterIndex, boolean x) throws SQLException {
         getPhysPs().setBoolean(parameterIndex, x);
    }

    public void setBytes(int parameterIndex, byte[] x) throws SQLException {
         getPhysPs().setBytes(parameterIndex, x);
    }

    public void setAsciiStream(int parameterIndex, InputStream x, int length)
            throws SQLException {
         getPhysPs().setAsciiStream(parameterIndex, x, length);
    }

    public void setBinaryStream(int parameterIndex, InputStream x, int length)
            throws SQLException {
         getPhysPs().setBinaryStream(parameterIndex, x, length);
    }

    @Deprecated
    public void setUnicodeStream(int parameterIndex, InputStream x, int length)
            throws SQLException {
         getPhysPs().setUnicodeStream(parameterIndex, x, length);
    }

    public void setCharacterStream(int parameterIndex, Reader reader, int length)
            throws SQLException {
         getPhysPs().setCharacterStream(parameterIndex, reader, length);
    }

    public void setObject(int parameterIndex, Object x) throws SQLException {
         getPhysPs().setObject(parameterIndex, x);
    }

    public void setObject(int parameterIndex, Object x, int targetSqlType)
                throws SQLException {
         getPhysPs().setObject(parameterIndex, x, targetSqlType);
    }

    public void setObject(int parameterIndex, Object x,
                          int targetSqlType, int scale)
            throws SQLException {
         getPhysPs().setObject(parameterIndex, x, targetSqlType, scale);
    }

    public void setNull(int paramIndex, int sqlType, String typeName)
            throws SQLException {
         getPhysPs().setNull(paramIndex, sqlType, typeName);
    }

    public void setString(int parameterIndex, String x) throws SQLException {
         getPhysPs().setString(parameterIndex, x);
    }

    public void setBigDecimal(int parameterIndex, BigDecimal x)
            throws SQLException {
         getPhysPs().setBigDecimal(parameterIndex, x);
    }

    public void setURL(int parameterIndex, URL x) throws SQLException {
         getPhysPs().setURL(parameterIndex, x);
    }

    public void setArray(int i, Array x) throws SQLException {
         getPhysPs().setArray(i, x);
    }

    public void setBlob(int i, Blob x) throws SQLException {
         getPhysPs().setBlob(i, x);
    }

    public void setClob(int i, Clob x) throws SQLException {
         getPhysPs().setClob(i, x);
    }

    public void setDate(int parameterIndex, Date x) throws SQLException {
         getPhysPs().setDate(parameterIndex, x);
    }

    public ParameterMetaData getParameterMetaData() throws SQLException {
        return getPhysPs().getParameterMetaData();
    }

    public void setRef(int i, Ref x) throws SQLException {
         getPhysPs().setRef(i, x);
    }

    public ResultSet executeQuery() throws SQLException {
        return getPhysPs().executeQuery();
    }

    public ResultSetMetaData getMetaData() throws SQLException {
        return getPhysPs().getMetaData();
    }

    public void setTime(int parameterIndex, Time x) throws SQLException {
         getPhysPs().setTime(parameterIndex, x);
    }

    public void setTimestamp(int parameterIndex, Timestamp x)
            throws SQLException {
         getPhysPs().setTimestamp(parameterIndex, x);
    }

    public void setDate(int parameterIndex, Date x, Calendar cal)
            throws SQLException {
         getPhysPs().setDate(parameterIndex, x, cal);
    }

    public void setTime(int parameterIndex, Time x, Calendar cal)
            throws SQLException {
         getPhysPs().setTime(parameterIndex, x, cal);
    }

    public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal)
            throws SQLException {
         getPhysPs().setTimestamp(parameterIndex, x, cal);
    }

    public int getFetchDirection() throws SQLException {
        return getPhysPs().getFetchDirection();
    }

    public int getFetchSize() throws SQLException {
        return getPhysPs().getFetchSize();
    }

    public int getMaxFieldSize() throws SQLException {
        return getPhysPs().getMaxFieldSize();
    }

    public int getMaxRows() throws SQLException {
        return getPhysPs().getMaxRows();
    }

    public int getQueryTimeout() throws SQLException {
        return getPhysPs().getQueryTimeout();
    }

    public int getResultSetConcurrency() throws SQLException {
        return getPhysPs().getResultSetConcurrency();
    }

    public int getResultSetHoldability() throws SQLException {
        return getPhysPs().getResultSetHoldability();
    }

    public int getResultSetType() throws SQLException {
        return getPhysPs().getResultSetType();
    }

    public int getUpdateCount() throws SQLException {
        return getPhysPs().getUpdateCount();
    }

    public void cancel() throws SQLException {
         getPhysPs().cancel();
    }

    public void clearBatch() throws SQLException {
         getPhysPs().clearBatch();
    }

    public void clearWarnings() throws SQLException {
         getPhysPs().clearWarnings();
    }

    public boolean getMoreResults() throws SQLException {
        return getPhysPs().getMoreResults();
    }

    public int[] executeBatch() throws SQLException {
        return getPhysPs().executeBatch();
    }

    public void setFetchDirection(int direction) throws SQLException {
         getPhysPs().setFetchDirection(direction);
    }

    public void setFetchSize(int rows) throws SQLException {
         getPhysPs().setFetchSize(rows);
    }

    public void setMaxFieldSize(int max) throws SQLException {
         getPhysPs().setMaxFieldSize(max);
    }

    public void setMaxRows(int max) throws SQLException {
         getPhysPs().setMaxRows(max);
    }

    public void setQueryTimeout(int seconds) throws SQLException {
         getPhysPs().setQueryTimeout(seconds);
    }

    public boolean getMoreResults(int current) throws SQLException {
        return getPhysPs().getMoreResults(current);
    }

    public void setEscapeProcessing(boolean enable) throws SQLException {
         getPhysPs().setEscapeProcessing(enable);
    }

    public int executeUpdate(String sql) throws SQLException {
        return getPhysPs().executeUpdate(sql);
    }

    public void addBatch(String sql) throws SQLException {
         getPhysPs().addBatch(sql);
    }

    public void setCursorName(String name) throws SQLException {
         getPhysPs().setCursorName(name);
    }

    public boolean execute(String sql) throws SQLException {
        return getPhysPs().execute(sql);
    }

    public int executeUpdate(String sql, int autoGeneratedKeys)
            throws SQLException {
        return getPhysPs().executeUpdate(sql, autoGeneratedKeys);
    }

    public boolean execute(String sql, int autoGeneratedKeys)
            throws SQLException {
        return getPhysPs().execute(sql, autoGeneratedKeys);
    }

    public int executeUpdate(String sql, int[] columnIndexes)
            throws SQLException {
        return getPhysPs().executeUpdate(sql, columnIndexes);
    }

    public boolean execute(String sql, int[] columnIndexes)
            throws SQLException {
        return getPhysPs().execute(sql, columnIndexes);
    }

    public Connection getConnection() throws SQLException {
        return getPhysPs().getConnection();
    }

    public ResultSet getGeneratedKeys() throws SQLException {
        return getPhysPs().getGeneratedKeys();
    }

    public ResultSet getResultSet() throws SQLException {
        return getPhysPs().getResultSet();
    }

    public SQLWarning getWarnings() throws SQLException {
        return getPhysPs().getWarnings();
    }

    public int executeUpdate(String sql, String[] columnNames)
            throws SQLException {
        return getPhysPs().executeUpdate(sql, columnNames);
    }

    public boolean execute(String sql, String[] columnNames)
            throws SQLException {
        return getPhysPs().execute(sql, columnNames);
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        return getPhysPs().executeQuery(sql);
    }

    ////////////////////////////////////////////////////////////////
    //
    //  ADDED BY JDBC 4.2
    //
    ////////////////////////////////////////////////////////////////

    public  long    executeLargeUpdate() throws SQLException
    {
        return ((PreparedStatement) getPhysPs()).executeLargeUpdate();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<DexEntry>
  <General>
    <Name>Granbull</Name>
    <SpeciesName>Fairy</SpeciesName>
    <GrowthGroup>Fast</GrowthGroup>
    <EggGroup1>Field</EggGroup1>
    <EggGroup2>Fairy</EggGroup2>
  </General>
</DexEntry>


text:
<?php defined('DIRECT') OR exit('No direct script access allowed');

class App
{
	protected $config;
	protected $controller;
	protected $method;
	protected $params = [];
	protected $routes;
	protected $url;

	public function __construct()
	{
		// Getting config file
		$this->config 		= $this->loadFile(APP_DIR . 'config/config');

		// Setting default controller and method
		$this->controller 	= $this->config['default_controller'];
		$this->method 		= $this->config['default_method'];

		// Getting current URL
		$this->url			= $this->parseURL();

		// Getting routes
		$this->routes 		= $this->loadFile(APP_DIR . 'config/routes');

		if($this->run() === false) {
			// Getting Controller
			$this->set_controller($this->url);

			// Getting Method
			$this->set_action($this->url);

			// Getting parameters
			$this->set_params($this->url);
		}

		// Composer Autoload
		if($this->config['composer'] == true) {
			if(file_exists('vendor/autoload.php'))
				require_once('vendor/autoload.php');
			else
				echo 'UYARI: Composer yükleyicisi bulunamadı.';
		}

		call_user_func_array([$this->controller, $this->method], $this->params);
	}

	private function run()
	{
		$matched = 0;
        $url = ltrim(str_replace(BASE_DIR,'',$_SERVER['REQUEST_URI']), '/');

        foreach($this->routes as $key => $value) {
            $key = '/^' . str_replace('/', '\/', $key) . '$/';

            if(preg_match($key, $url)) {
                $matched++;
                preg_match_all($key, $url, $matches);
                array_shift($matches);
                $target = explode('/', $value);

                if(file_exists(APP_DIR . 'controllers/' . ucfirst($target[0]) . '.php')) {
                    $this->controller = $this->makeURL(ucfirst($target[0]));
                    $this->loadFile(APP_DIR . 'controllers/' . $this->controller);
                    $this->controller = new $this->controller;
                } else {
                    $this->loadFile(APP_DIR . 'views/errors/error_404');
					die();
                }

                $this->method = $target[1];

                unset($target[0]);
                unset($target[1]);
                sort($target);

                foreach($matches as $indis => $match) {
                    $target[$indis] = $match[0];
                }

                $this->params = $target ? array_values($target) : [];
            }
        }

        if($matched > 0)
            return true;
        else
            return false;
	}

	/**
	 * Setting Controller
	 * @param 	array $url
	 * @return 	void
	 */
	private function set_controller($url)
	{
		if(isset($url[0])) {
			if (file_exists(APP_DIR . 'controllers/' . $this->makeURL($url[0]) . '.php')) {
				$this->controller = $this->makeURL($url[0]);
				$this->loadFile(APP_DIR . 'controllers/' . $this->controller);
				$this->controller = new $this->controller;
			} else {
				$this->loadFile(APP_DIR . 'views/errors/error_404');
				die();
			}
			unset($this->url[0]);
		} else {
			$this->loadFile(APP_DIR . 'controllers/' . $this->controller);
			$this->controller = new $this->controller;
		}
	}

	/**
	 * Setting Action
	 * @param 	array $url
	 * @return 	void
	 */
	private function set_action($url)
	{
		if (isset($url[1])) {
			if ($url[1] != 'index') {
				if (method_exists($this->controller, $url[1])) {
					$this->method = $url[1];
				} else {
					$this->loadFile(APP_DIR . 'views/errors/error_404');
					die();
				}
			}
			unset($this->url[1]);
		}
	}

	/**
	 * Setting Parameters
	 * @param 	array $url
	 * @return 	void
	 */
	private function set_params($url)
	{
		$this->params = $url ? array_values($url) : [];
	}

	/**
	 * Parsing URL
	 * @return array
	 */
	public function parseURL()
	{
		if (isset($_GET['url'])) {
			return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
		}
	}

	/**
	 * Making URL
	 * @param 	string $queryString
	 * @return 	string
	 */
	public function makeURL($queryString)
    {
        $queryString = ucwords(strtolower(str_replace(['-','_','%20'], [' ',' ',' '], $queryString)));
        $queryString = str_replace(' ', '_', $queryString);
        return $queryString;
    }

    /**
     * Loading file
     * @param 	string $fileName
     * @return 	void
     */
    public function loadFile($fileName) {
        $fileName 	= $fileName . '.php';
        if (file_exists($fileName)) {
            return require_once $fileName;
        } else {
        	$code 	= 1005;
        	$text 	= 'Böyle bir dosya bulunmamaktadır. {' . $fileName . '}';
        	require_once APP_DIR . 'views/errors/error_system.php';
            die();
        }
    }
}


text:
@interface XHMoreGameTableViewController ()

@property (nonatomic, strong) UIImageView *topImageView;

@property (nonatomic, strong) XHHorizontalGridView *horizontalGridView;

@end

@implementation XHMoreGameTableViewController

#pragma mark - Propertys

- (UIImageView *)topImageView {
    if (!_topImageView) {
        _topImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 160)];
        _topImageView.image = [UIImage imageNamed:@"AlbumHeaderBackgrounImage"];
    }
    return _topImageView;
}

- (XHHorizontalGridView *)horizontalGridView {
    if (!_horizontalGridView) {
        _horizontalGridView = [[XHHorizontalGridView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 100)];
    }
    return _horizontalGridView;
}

#pragma mark - DataSource

- (void)loadDataSource {
    NSMutableArray *gridItems = [[NSMutableArray alloc] initWithCapacity:3];
    for (int i = 1; i <= 16; i ++) {
        XHHorizontalGridItem *gridItem = [[XHHorizontalGridItem alloc] init];
        gridItem.title = @"天天哭跑";
        gridItem.subtitle = @"第一名";
        gridItem.image = [UIImage imageNamed:[NSString stringWithFormat:@"dgame%ld", random() % 2]];
        [gridItems addObject:gridItem];
    }
    self.dataSource = [NSMutableArray arrayWithObjects:gridItems, @[@"game1", @"game2", @"game3", @"game3", @"game2", @"game3", @"game2", @"game3", @"game2", @"game3", @"game1", @"game1", @"game3", @"game2"], nil];
}

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = NSLocalizedStringFromTable(@"Gamge", @"MessageDisplayKitString", @"游戏");

    [self configureBarbuttonItemStyle:XHBarbuttonItemStyleMore action:^{
        DLog(@"游戏更多");
    }];

    self.tableView.tableHeaderView = self.topImageView;

    [self loadDataSource];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.dataSource.count)
        return 0;
    if (section) {
        return [self.dataSource[section] count];
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier;
    if (indexPath.section) {
        cellIdentifier = @"CellIdentifier";
    } else {
        cellIdentifier = @"horCellIdentifier";
    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

        if (!indexPath.section) {
            [cell.contentView addSubview:self.horizontalGridView];
        }
    }

    if (indexPath.section) {
        cell.imageView.image = [UIImage imageNamed:self.dataSource[indexPath.section][indexPath.row]];
        cell.textLabel.text = @"全民打怪兽";
        cell.detailTextLabel.text = @"第一名";
    } else {
        self.horizontalGridView.gridItems = self.dataSource[indexPath.section];
        [self.horizontalGridView reloadData];
    }

    return cell;
}

#pragma mark - UITableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section) {
        return 60;
    } else {
        return 100;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (!section) {
        return @"已下载的游戏(3)";
    } else {
        return @"未下载的游戏(15)";
    }
}

@end


text:
<?php

namespace Skvn\Crud\Traits;

use Illuminate\Support\Str;
use Skvn\Crud\Exceptions\ConfigException;
use Skvn\Crud\Exceptions\UniqueException;

trait ModelSlugTrait
{
    //    protected  static  $slugColumn = 'slug';

    public static function bootModelSlugTrait()
    {
        static :: saving(function ($instance) {
            //            if ($instance->eventsDisabled)
//            {
//                return true;
//            }
            return $instance->processSlug();
        });
    }

    public static function slugColumn()
    {
        return defined('static::SLUG') ? static :: SLUG : 'slug';
    }

    public function getFrontUrlAttribute()
    {
        if (! defined('static::SLUG_URL')) {
            throw new ConfigException('Url pattern not defined');
        }
        if ($this->getAttribute(static :: slugColumn())) {
            return sprintf(static :: SLUG_URL, $this->getAttribute(static :: slugColumn()));
        } else {
            return sprintf(static :: SLUG_URL, $this->getKey());
        }
    }

    protected function processSlug()
    {
        $column = static :: slugColumn();
        if (defined('static::SLUG_IMMUTABLE') && $this->getOriginal($column)) {
            $this->setAttribute($column, $this->getOriginal($column));

            return;
        }
        try {
            $this->setAttribute($column, $this->generateSlug($this->getAttribute($column)));
        } catch (UniqueException $e) {
            var_dump($e->getMessage());
            //var_dump($e->getTraceAsString());
            $this->addError($column, $e->getMessage());

            return false;
        }
    }

    protected function generateSlug($slug)
    {
        if (empty($slug)) {
            $slug = defined('static::SLUG_SOURCE') ? $this->getAttribute(static :: SLUG_SOURCE) : $this->getTitle();
            $slug = $this->app['skvn.cms']->translitRussian($slug);
            $slug = Str :: slug($slug);
        }
        $slug = $this->generateUniqueSlug($slug);

        return $slug;
    }

    private function generateUniqueSlug($slug)
    {
        //        $column = static :: slugColumn();
        $valid = $this->validateSlug($slug);
        if ($valid === -99) {
            if (defined('static::SLUG_FORCE_TRANSLIT')) {
                $slug = $this->app['skvn.cms']->translitRussian($slug);
                $slug = Str :: slug($slug);
            } else {
                throw new UniqueException('Slug('.$slug.') in model '.$this->classShortName.'#'.$this->getKey().' not in URI format. Acceptable format is [a-zA-Z0-9_-]');
            }
        } elseif ($valid < 0) {
            if (defined('static::SLUG_GENERATE_NEXT')) {
                return $slug.'.'.(abs($valid) + 1);
            }
            if (defined('static::SLUG_GENERATE_ID') && $this->exists) {
                return $slug.'.'.$this->getKey();
            }
            throw new UniqueException('Slug column('.$slug.') for model '.$this->classShortName.'#'.$this->getKey().' is not unique');
        }

        return $slug;
    }

    public function validateSlug($slug)
    {
        if (! preg_match('#^[a-zA-Z0-9_-]+$#', $slug)) {
            return -99;
        }
        $column = static :: slugColumn();
        $exists = $this->app['db']->table($this->table)->where($column, 'like', $slug)->where('id', '<>', $this->getKey())->get();
        if (count($exists) > 0) {
            return count($exists);
        }

        return 0;
    }

    public static function findBySlug($slug)
    {
        $class = get_called_class();
        $column = $class :: slugColumn();

        return $class :: where($column, $slug)->firstOrFail();
    }

    public function slugTransliterate($args = [])
    {
        if (! empty($args['source']) && ! empty($args[$args['source']])) {
            $slug = $this->app['skvn.cms']->translitRussian($args[$args['source']]);
            $slug = Str :: slug($slug);

            return $slug;
        }
    }
}


text:
Ember.Inflector.inflector.uncountable('Trello');

var attr = DS.attr;

Mello.Trello = DS.Model.extend({
    enabled: attr('boolean'),
    appKey: attr('string'),
    appToken: attr('string'),
    boardId: attr('string'),
    listId: attr('string'),
    userId: attr('string'),
    labelKey: attr('string'),

    appTokenUrl: function() {
        return 'https://trello.com/1/authorize?key=' + this.get('appKey') + '&name=Mello&response_type=token&scope=read,write';
    }.property('appKey'),

    appBoardsUrl: function() {
        return 'https://trello.com/1/members/me/boards?fields=boards%2Cname&key' + this.get('appKey') + '&token=' + this.get('appToken');
    }.property('appKey', 'appToken'),

    appListsUrl: function() {
        return 'https://trello.com/1/boards/' + this.get('boardId') + '/lists?fields=name&key' + this.get('appKey') + '&token=' + this.get('appToken');
    }.property('appKey', 'appToken', 'boardId'),

    appUserUrl: function() {
        return 'https://trello.com/1/members/me?fields=id,username&key' + this.get('appKey') + '&token=' + this.get('appToken');
    }.property('appKey', 'appToken'),

    appLabelsUrl: function() {
        return 'https://trello.com/1/boards/' + this.get('boardId') + '?fields=labelNames&key' + this.get('appKey') + '&token=' + this.get('appToken');
    }.property('appKey', 'appToken', 'boardId')

});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/display_teams_general_row"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp" >

    <TextView
        android:id="@+id/display_row_main_team"
        style="@style/DisplayRow"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
         >
    </TextView>

    <TextView
        android:id="@+id/display_row_main_nickname"
        style="@style/DisplayRow"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </TextView>

    <TextView
        android:id="@+id/display_row_main_wins"
        style="@style/DisplayRow"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1">
    </TextView>

    <TextView
        android:id="@+id/display_row_main_losses"
        style="@style/DisplayRow"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </TextView>

    <TextView
        android:id="@+id/display_row_main_total_score"
        style="@style/DisplayRow"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </TextView>

</LinearLayout>


text:
import { SpectronApplication } from '../spectron/application';

export class Window {

	constructor(private spectron: SpectronApplication) {

	}

	public async getTitle(): Promise<string> {
		return this.spectron.client.getTitle();
	}

}


text:
![](https://travis-ci.org/howwayla/taipeiAttractions.svg?branch=master)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org)

## License
taipeiAttractions is released under the MIT license.


text:
function NoamRefresher( params ) {
  this.params = params;
  this.time = 0;
  if(!this.params.cb){
    this.params.cb = function(results){
      console.log(results);
    }
  }

  if(!this.params.errorcb){
    this.params.errorcb = function(error){
      console.log("ERROR: ");
      console.log(error);
    }
  }
}

NoamRefresher.prototype.go = function( ) {
  var params = this.params;
  var self = this;

  var softRefresh = function() {
    populateFromUrl( params.asyncRefreshRoute );
  };

  var hardRefresh = function() {
    populateFromUrl( params.refreshRoute );
  };

  var populateFromUrl = function( route ) {
    $.ajax({
      url: route,
      data: {'time': self.time},
      dataType: 'json',
      success: function( results ){
        self.time = results['time'];
        setTimeout( softRefresh, 1);
        params.cb( results );
      },
      error: function(error) {
        params.errorcb( error );
        setTimeout( hardRefresh, 1000);
      }
    });
  };

  hardRefresh();
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_material_light"
    android:padding="16dp"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_new_image_camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/btn_txt_new_image_camera"/>

    <Button
        android:id="@+id/btn_new_image_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/btn_txt_new_image_gallery"/>

    <Button
        android:id="@+id/btn_new_image_cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:text="@string/btn_txt_new_image_cancel"/>
</LinearLayout>


text:
<?php
  global $siteConfig;
  global $photospath;
  global $explorerElements;

  $title = str_replace(PHOTOS_PATH, '', $photospath);
  if($title !== '') {
    $title = explode('/', $title);
    $title = photos_folder_name_to_title($title[count($title) -1]);
    if($title['title'] !== '') {
      $title = implode(' - ', $title);
    }
    else {
      $title = $title['folder'];
    }
    $siteConfig['title'] = $title;
  }

  $explorerElements = photos_elements();

  if(isset($explorerElements['description']) && $explorerElements['description'] !== '') {
    $siteConfig['site-description'] = $explorerElements['description'];
  }

  $globalConfig = get_global_config();

  $pathFolder = str_replace(PHOTOS_PATH, CACHE_PATH, $photospath);
  $config = get_config_file($pathFolder . '/config');

  $search = array('data' => []);
  foreach (array('identities', 'tags') as $type) {
    foreach($config[$type] as $value => $files) {
      $search['data'] []= array(
        'id' => $type . '-' . implode('_', explode(' ', $value)),
        'name' => $value,
        'cls' => $type
      );
    }
  }

  add_html_data('search', $search);

  $path = str_replace(PHOTOS_PATH, '', $photospath);
  $path = $path === '' ? '/' : $path;
  add_html_data('path', array('path' => $path));

  if(user_connected()) {
    hook_menu(function() {
?>
    <input class="but-filter-toggle but-filter-photos" data-filter="photo" type="button" value="" />
    <input class="but-filter-toggle but-filter-videos" data-filter="video" type="button" value="" />

    <input class="but-menu" type="button" value="..." />

<?php
    });
  }

  add_css('/vendor/isotope/css/style.css');
  add_css('/features/explorer/assets/explorer-viewer.css');
  add_css('/features/explorer/assets/explorer.css');
  add_css('/features/explorer/assets/explorer-worker.css');

  require ROOT_PATH . '/features/common/common-header.php';
?>

  <?php if($siteConfig['body_css'] == 'page-index' && count($globalConfig['featured']) > 0) { ?>

    <?php
      $index = -1;
      $globalConfig['featured'] = array_reverse($globalConfig['featured']);

      foreach($globalConfig['featured'] as $featured) {
        $index++
    ?>

    <a href="<?php echo $featured['url']; ?>" class="featured-item <?php echo $index % 2 ? 'odd' : ''; ?>">
      <img class="featured-preview no-animation" src="<?php echo $featured['picture']; ?>" />

        <?php echo $featured['title']; ?>
        <?php echo $featured['description']; ?>

    <?php } ?>

  <?php } ?>

  <div class="explorer-container" data-album="<?php echo htmlentities(json_encode($explorerElements)); ?>">

Cet album est vide

      <?php function admin_menu($type) { ?>
        <?php if(user_is_admin()) { ?>

            <?php if($type == 'album') { ?>

            <?php } else { ?>

            <?php if($type == 'video') { ?>

            <?php } ?>

            <?php } ?>

Titre

            <input class="ask-title" type="text" />

Description

            <textarea class="ask-input"></textarea>
            <input class="ask-submit-1" type="button" value="✔" />

              <input class="ask-submit-cancel" type="button" value="Annuler" />

          <?php if($type != 'album') { ?>

Devenir le logo de cette page ou de la page parente ?

              <input class="ask-submit-1" type="button" value="Cette page" /><input class="ask-submit-2" type="button" value="Page parente" />

                <input class="ask-submit-cancel" type="button" value="Annuler" />

Devenir la bannière de cette page ou de la page parente ?

              <input class="ask-submit-1" type="button" value="Cette page" /><input class="ask-submit-2" type="button" value="Page parente" />

                <input class="ask-submit-cancel" type="button" value="Annuler" />

Mots clés

              <textarea class="ask-input">{{tagsValue}}</textarea>
              <input class="ask-submit-1" type="button" value="✔" />

                <input class="ask-submit-cancel" type="button" value="Annuler" />

Identités

              <textarea class="ask-input">{{identitiesValue}}</textarea>
              <input class="ask-submit-1" type="button" value="✔" />

                <input class="ask-submit-cancel" type="button" value="Annuler" />

            <?php if($type == 'video') { ?>

Régénérer les miniatures de la vidéo en fonction du numéro de la frame :

              <input class="ask-frame" type="text" value="{{frame}}" />
              <input class="ask-submit-1" type="button" value="✔" />

                <input class="ask-submit-cancel" type="button" value="Annuler" />

            <?php } ?>

          <?php } ?>

        <?php } ?>
      <?php } ?>

{{title_title}}{{title_folder}}

              {{description}}

                {{number_photos}} {{_photos}}
                |
                {{number_videos}} {{_videos}}

          <?php admin_menu('album'); ?>

          <?php admin_menu('photo'); ?>

          <?php admin_menu('video'); ?>

          <video x-webkit-airplay="allow" controls="controls" preload="none" template-poster="{{sizes_1920x1080}}" template-src="{{src}}"></video>

    <input class="explorer-viewer-menu-button" type="button" value="..." />

  <?php add_javascript('/vendor/jquery.hashchange/jquery.hashchange.min.js') ?>
  <?php add_javascript('/vendor/isotope/jquery.isotope.min.js') ?>
  <?php add_javascript('/vendor/hammer.js/hammer.min.js') ?>
  <?php add_javascript('/features/photos/assets/photos.js') ?>
  <?php add_javascript('/features/explorer/assets/explorer-viewer.js') ?>
  <?php add_javascript('/features/explorer/assets/explorer.js') ?>
  <?php add_javascript('/features/explorer/assets/explorer-worker.js') ?>

<?php require ROOT_PATH . '/features/common/common-footer.php'; ?>


text:
require "bundler/setup"
require "pry"
require "debug" if RUBY_VERSION.to_f >= 2.6

# this enables sidekiq's server mode
require "sidekiq/cli"
# require "support/test_sidekiq_app/app"

require "sentry-ruby"

require 'simplecov'

SimpleCov.start do
  project_name "sentry-sidekiq"
  root File.join(__FILE__, "../../../")
  coverage_dir File.join(__FILE__, "../../coverage")
end

if ENV["CI"] && ENV["CODECOV"] == "1"
  require 'codecov'
  SimpleCov.formatter = SimpleCov::Formatter::Codecov
end

require "sentry-sidekiq"

DUMMY_DSN = 'http://12345:67890@sentry.localdomain/sentry/42'

RSpec.configure do |config|
  # Enable flags like --only-failures and --next-failure
  config.example_status_persistence_file_path = ".rspec_status"

  # Disable RSpec exposing methods globally on `Module` and `main`
  config.disable_monkey_patching!

  config.expect_with :rspec do |c|
    c.syntax = :expect
  end

  config.before :each do
    # Make sure we reset the env in case something leaks in
    ENV.delete('SENTRY_DSN')
    ENV.delete('SENTRY_CURRENT_ENV')
    ENV.delete('SENTRY_ENVIRONMENT')
    ENV.delete('SENTRY_RELEASE')
    ENV.delete('sidekiq_ENV')
    ENV.delete('RACK_ENV')
  end

  config.before :all do
    Sidekiq.logger = Logger.new(nil)
  end
end

def build_exception
  1 / 0
rescue ZeroDivisionError => e
  e
end

def build_exception_with_cause(cause = "exception a")
  begin
    raise cause
  rescue
    raise "exception b"
  end
rescue RuntimeError => e
  e
end

def build_exception_with_two_causes
  begin
    begin
      raise "exception a"
    rescue
      raise "exception b"
    end
  rescue
    raise "exception c"
  end
rescue RuntimeError => e
  e
end

def build_exception_with_recursive_cause
  backtrace = []

  exception = double("Exception")
  allow(exception).to receive(:cause).and_return(exception)
  allow(exception).to receive(:message).and_return("example")
  allow(exception).to receive(:backtrace).and_return(backtrace)
  exception
end

class HappyWorker
  include Sidekiq::Worker

  def perform
    crumb = Sentry::Breadcrumb.new(message: "I'm happy!")
    Sentry.add_breadcrumb(crumb)
    Sentry.set_tags mood: 'happy'
  end
end

class SadWorker
  include Sidekiq::Worker

  def perform
    crumb = Sentry::Breadcrumb.new(message: "I'm sad!")
    Sentry.add_breadcrumb(crumb)
    Sentry.set_tags :mood => 'sad'

    raise "I'm sad!"
  end
end

class VerySadWorker
  include Sidekiq::Worker

  def perform
    crumb = Sentry::Breadcrumb.new(message: "I'm very sad!")
    Sentry.add_breadcrumb(crumb)
    Sentry.set_tags :mood => 'very sad'

    raise "I'm very sad!"
  end
end

class ReportingWorker
  include Sidekiq::Worker

  def perform
    Sentry.capture_message("I have something to say!")
  end
end

class RetryWorker
  include Sidekiq::Worker

  sidekiq_options retry: 1

  def perform
    1/0
  end
end

class ZeroRetryWorker
  include Sidekiq::Worker

  sidekiq_options retry: 0

  def perform
    1/0
  end
end

def execute_worker(processor, klass)
  klass_options = klass.sidekiq_options_hash || {}
  options = {}

  # for Ruby < 2.6
  klass_options.each do |k, v|
    options[k.to_sym] = v
  end

  msg = Sidekiq.dump_json(jid: "123123", class: klass, args: [], **options)
  work = Sidekiq::BasicFetch::UnitOfWork.new('queue:default', msg)
  process_work(processor, work)
end

def process_work(processor, work)
  processor.send(:process, work)
rescue StandardError
  # do nothing
end

def perform_basic_setup
  Sentry.init do |config|
    config.dsn = DUMMY_DSN
    config.logger = ::Logger.new(nil)
    config.background_worker_threads = 0
    config.transport.transport_class = Sentry::DummyTransport
    yield config if block_given?
  end
end


text:
azure.mgmt.storage.v2017_06_01.operations module
================================================

.. automodule:: azure.mgmt.storage.v2017_06_01.operations
    :members:
    :undoc-members:
    :show-inheritance:


text:
define(
"dojo/cldr/nls/asa/currency", //begin v1.x content
{
	"CHF_displayName": "faranga ya Uthwithi",
	"EUR_displayName": "yuro",
	"CAD_displayName": "dola ya Kanada",
	"GBP_displayName": "pauni ya Uingeredha",
	"JPY_displayName": "tharafu ya Kijapani",
	"AUD_displayName": "dola ya Authtralia",
	"CNY_displayName": "yuan renminbi ya China",
	"USD_displayName": "dola ya Marekani"
}
//end v1.x content
);


text:
echo_section "Installing minimal KDE applications"

ensure_pkg dolphin
ensure_pkg dolphin-plugins
ensure_pkg kate
ensure_pkg kcalc
ensure_pkg konsole


text:
__author__ = 'xdy'

class Queue:
    def __init__(self):
        self.container = []

    def enqueue(self, value):
        self.container.append(value)

    def dequeue(self):
        if self.container:
            queue_head = self.container[0]
            self.container = self.container[1:]
            return queue_head

    def __nonzero__(self):
        return len(self.container) > 0


text:
using UnityEngine;
using System.Collections;

public class OffsetOnNormal : MonoBehaviour
{
  public float offset = 1;
  public GameObject offsetGameObject;

  private Vector3 startPosition;

  void Awake()
  {
    startPosition = transform.position;
  }

	// Use this for initialization
	void OnEnable () {
    RaycastHit verticalHit;
    Physics.Raycast(startPosition, Vector3.down, out verticalHit);
    if(offsetGameObject!=null) transform.position = offsetGameObject.transform.position + verticalHit.normal * offset;
    else {
      transform.position = verticalHit.point + verticalHit.normal * offset;
    }
	}

	// Update is called once per frame
	void Update () {

	}
}


text:
class CmdByeHandler : public ICmdHandler {

	public:
		virtual QString cmd();
		virtual void handle(QJsonObject obj, IWebSocketClient *wsc);
};

#endif // CLOUDSTREAMER_CMD_HANDLERS_CMD_BYE_HANDLER_H


text:
Building an Energy Efficient Denver

The energy used in commercial buildings, apartments and condos is responsible for 57% of the greenhouse gas emissions in Denver. Together we can cut that by 20% for $1.3 billion in energy savings. The first step in improving energy efficiency is to measure it. You know the miles per gallon of your car, but do you know the 1-100 ENERGY STAR score of the buildings where you live and work? Click on the markers above to find out!

5.5% of buildings enrolled of Denver has benchmarked with ENERGY STAR. Help us get to 100%!

 -- What is an ENERGY STAR score? The 1-100 ENERGY STAR score benchmarks, or measures, the energy performance of buildings. 50 is the national average score, and any score above 75 can qualify for ENERGY STAR certification.

 -- What is EUI? The energy use intensity shows the energy intensity in kbtu per square foot..

 -- Do More! Make your own space energy efficient and get the company where you work to sign up for our Lease for Efficiency Challenge. Click for more info - DenverGov.org

 -- Frequently Asked Questions


text:
package main

import (
	"fmt"
	"github.com/4ydx/glmenu"
	"github.com/4ydx/gltext"
	"github.com/go-gl/glfw/v3.1/glfw"
	"github.com/go-gl/mathgl/mgl32"
	"os"
)

func optionMenuInit(window *glfw.Window, font *gltext.Font) (err error) {
	topMargin := float32(50)
	leftMargin := float32(30)
	width, height := window.GetSize()
	optionMenu, err = glmenu.NewMenu(font, float32(width), float32(height), mgl32.Vec2{})
	if err != nil {
		fmt.Println("error loading font")
		os.Exit(1)
	}
	optionMenu.ResizeWindow(float32(width), float32(height))
	optionMenu.Background = mgl32.Vec4{1, 1, 1, 1}
	optionMenu.TextScaleRate = 0.05

	label1 := optionMenu.NewLabel("Music Volume")

	label1.Text.SetColor(0.5, 0.5, 0.5)
	label1.OnClick = func(label *glmenu.Label, xPos, yPos float64, button glmenu.MouseClick, isBox bool) {
		fmt.Println("clicked", xPos, yPos)
	}
	label1.OnHover = func(label *glmenu.Label, xPos, yPos float64, button glmenu.MouseClick, isBox bool) {
		label.Text.AddScale(optionMenu.TextScaleRate)
	}
	label1.OnNotHover = func(label *glmenu.Label) {
		label.Text.AddScale(-optionMenu.TextScaleRate)
	}

	label3 := optionMenu.NewLabel("Back")

	label3.Text.SetColor(0.5, 0.5, 0.5)
	label3.OnClick = func(label *glmenu.Label, xPos, yPos float64, button glmenu.MouseClick, isBox bool) {
		optionMenu.Toggle()
		mainMenu.Toggle()
	}
	label3.OnHover = func(label *glmenu.Label, xPos, yPos float64, button glmenu.MouseClick, isBox bool) {
		label.Text.AddScale(optionMenu.TextScaleRate)
	}
	label3.OnNotHover = func(label *glmenu.Label) {
		label.Text.AddScale(-optionMenu.TextScaleRate)
	}

	label1.Text.SetPosition(-float32(width)/2.0+leftMargin, float32(height)/2.0-topMargin)
	label1.Text.Justify(gltext.AlignLeft)
	label3.Text.SetPosition(-float32(width)/2.0+leftMargin, float32(height)/2.0-topMargin-label1.Text.Height)
	label3.Text.Justify(gltext.AlignLeft)

	label1.NewShadow(1.5, 0, 0, 0)
	label3.NewShadow(1.5, 0, 0, 0)
	return
}


text:
          View your licences

          Returns

          Add licences or give access


text:
package msgraph

import "time"

// PurchaseInvoice undocumented
type PurchaseInvoice struct {
	// Entity is the base model of PurchaseInvoice
	Entity
	// Number undocumented
	Number *string `json:"number,omitempty"`
	// InvoiceDate undocumented
	InvoiceDate *Date `json:"invoiceDate,omitempty"`
	// DueDate undocumented
	DueDate *Date `json:"dueDate,omitempty"`
	// VendorInvoiceNumber undocumented
	VendorInvoiceNumber *string `json:"vendorInvoiceNumber,omitempty"`
	// VendorID undocumented
	VendorID *UUID `json:"vendorId,omitempty"`
	// VendorNumber undocumented
	VendorNumber *string `json:"vendorNumber,omitempty"`
	// VendorName undocumented
	VendorName *string `json:"vendorName,omitempty"`
	// PayToName undocumented
	PayToName *string `json:"payToName,omitempty"`
	// PayToContact undocumented
	PayToContact *string `json:"payToContact,omitempty"`
	// PayToVendorID undocumented
	PayToVendorID *UUID `json:"payToVendorId,omitempty"`
	// PayToVendorNumber undocumented
	PayToVendorNumber *string `json:"payToVendorNumber,omitempty"`
	// ShipToName undocumented
	ShipToName *string `json:"shipToName,omitempty"`
	// ShipToContact undocumented
	ShipToContact *string `json:"shipToContact,omitempty"`
	// BuyFromAddress undocumented
	BuyFromAddress *PostalAddressType `json:"buyFromAddress,omitempty"`
	// PayToAddress undocumented
	PayToAddress *PostalAddressType `json:"payToAddress,omitempty"`
	// ShipToAddress undocumented
	ShipToAddress *PostalAddressType `json:"shipToAddress,omitempty"`
	// CurrencyID undocumented
	CurrencyID *UUID `json:"currencyId,omitempty"`
	// CurrencyCode undocumented
	CurrencyCode *string `json:"currencyCode,omitempty"`
	// PricesIncludeTax undocumented
	PricesIncludeTax *bool `json:"pricesIncludeTax,omitempty"`
	// DiscountAmount undocumented
	DiscountAmount *int `json:"discountAmount,omitempty"`
	// DiscountAppliedBeforeTax undocumented
	DiscountAppliedBeforeTax *bool `json:"discountAppliedBeforeTax,omitempty"`
	// TotalAmountExcludingTax undocumented
	TotalAmountExcludingTax *int `json:"totalAmountExcludingTax,omitempty"`
	// TotalTaxAmount undocumented
	TotalTaxAmount *int `json:"totalTaxAmount,omitempty"`
	// TotalAmountIncludingTax undocumented
	TotalAmountIncludingTax *int `json:"totalAmountIncludingTax,omitempty"`
	// Status undocumented
	Status *string `json:"status,omitempty"`
	// LastModifiedDateTime undocumented
	LastModifiedDateTime *time.Time `json:"lastModifiedDateTime,omitempty"`
	// PurchaseInvoiceLines undocumented
	PurchaseInvoiceLines []PurchaseInvoiceLine `json:"purchaseInvoiceLines,omitempty"`
	// Vendor undocumented
	Vendor *Vendor `json:"vendor,omitempty"`
	// Currency undocumented
	Currency *Currency `json:"currency,omitempty"`
}

// PurchaseInvoiceLine undocumented
type PurchaseInvoiceLine struct {
	// Entity is the base model of PurchaseInvoiceLine
	Entity
	// DocumentID undocumented
	DocumentID *UUID `json:"documentId,omitempty"`
	// Sequence undocumented
	Sequence *int `json:"sequence,omitempty"`
	// ItemID undocumented
	ItemID *UUID `json:"itemId,omitempty"`
	// AccountID undocumented
	AccountID *UUID `json:"accountId,omitempty"`
	// LineType undocumented
	LineType *string `json:"lineType,omitempty"`
	// Description undocumented
	Description *string `json:"description,omitempty"`
	// UnitCost undocumented
	UnitCost *int `json:"unitCost,omitempty"`
	// Quantity undocumented
	Quantity *int `json:"quantity,omitempty"`
	// DiscountAmount undocumented
	DiscountAmount *int `json:"discountAmount,omitempty"`
	// DiscountPercent undocumented
	DiscountPercent *int `json:"discountPercent,omitempty"`
	// DiscountAppliedBeforeTax undocumented
	DiscountAppliedBeforeTax *bool `json:"discountAppliedBeforeTax,omitempty"`
	// AmountExcludingTax undocumented
	AmountExcludingTax *int `json:"amountExcludingTax,omitempty"`
	// TaxCode undocumented
	TaxCode *string `json:"taxCode,omitempty"`
	// TaxPercent undocumented
	TaxPercent *int `json:"taxPercent,omitempty"`
	// TotalTaxAmount undocumented
	TotalTaxAmount *int `json:"totalTaxAmount,omitempty"`
	// AmountIncludingTax undocumented
	AmountIncludingTax *int `json:"amountIncludingTax,omitempty"`
	// InvoiceDiscountAllocation undocumented
	InvoiceDiscountAllocation *int `json:"invoiceDiscountAllocation,omitempty"`
	// NetAmount undocumented
	NetAmount *int `json:"netAmount,omitempty"`
	// NetTaxAmount undocumented
	NetTaxAmount *int `json:"netTaxAmount,omitempty"`
	// NetAmountIncludingTax undocumented
	NetAmountIncludingTax *int `json:"netAmountIncludingTax,omitempty"`
	// ExpectedReceiptDate undocumented
	ExpectedReceiptDate *Date `json:"expectedReceiptDate,omitempty"`
	// Item undocumented
	Item *Item `json:"item,omitempty"`
	// Account undocumented
	Account *Account `json:"account,omitempty"`
}


text:
'use strict';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var fs = require('fs');
var path = require('path');

var alphabet = require('alphabet').lower;
var handlebars = require('handlebars');
var objectMerge = require('object-merge');
var is = require('annois');
var zip = require('annozip');

var UMD = function UMD(code, options) {
    if(!code) {
        throw new Error('Missing code to convert!');
    }

    EventEmitter.call(this);
    this.code = code;
    this.options = options || {};

    this.template = this.loadTemplate(this.options.template);
};

inherits(UMD, EventEmitter);

UMD.prototype.loadTemplate = function loadTemplate(filepath) {
    var tplPath,
        exists = fs.existsSync;

    if (filepath) {
        if (exists(filepath)) {
            tplPath = filepath;
        }
        else {
            tplPath = path.join(__dirname, 'templates', filepath + '.hbs');

            if (!exists(tplPath)) {
                tplPath = path.join(__dirname, 'templates', filepath);

                if (!exists(tplPath)) {
                    this.emit('error', 'Cannot find template file "' + filepath + '".');
                    return;
                }
            }
        }
    }
    else {
        tplPath = path.join(__dirname, 'templates', 'umd.hbs');
    }

    try {
        return handlebars.compile(fs.readFileSync(tplPath, 'utf-8'));
    }
    catch (e) {
        this.emit('error', e.message);
    }
};

UMD.prototype.generate = function generate() {
    var options = this.options,
        code = this.code,
        ctx = objectMerge({}, options);

    var depsOptions = objectMerge(
        getDependencyDefaults(this.options.globalAlias),
        convertDependencyArrays(options.deps) || {}
    );

    var defaultDeps = depsOptions['default'].items;
    var deps = defaultDeps ? defaultDeps || defaultDeps.items || [] : [];
    var dependency, dependencyType, items, prefix, separator, suffix;

    for (dependencyType in depsOptions) {
        dependency = depsOptions[dependencyType];

        items = dependency.items || defaultDeps || [];

        // extract possible dependency names for objects
        items = items.map(function(item) {
            if(is.object(item)) {
                return Object.keys(item)[0];
            }

            return item;
        });

        prefix = dependency.prefix || '';
        separator = dependency.separator || ', ';
        suffix = dependency.suffix || '';

        ctx[dependencyType + 'Dependencies'] = {
            normal: items.map(function(item){ return 'root["' + item + '"]'; }),
            params: convertToAlphabet(items),
            wrapped: items.map(wrap(prefix, suffix)).join(separator),
        };
    }

    // supports ['dependency'] and [{dependency: 'functionParameter'}]
    ctx.dependencies = deps.map(function(dep) {
        if(is.string(dep)) {
            return dep;
        }

        if(is.object(dep)) {
            return dep[Object.keys(dep)[0]];
        }
    }).filter(id).join(', ');

    deps.join(', ');

    ctx.code = code;

    return this.template(ctx);
};

function convertToAlphabet(items) {
    return items.map(function(_, i) {
        return alphabet[i] + i;
    });
}

function wrap(pre, post) {
    pre = pre || '';
    post = post || '';

    return function (v) {
        return pre + v + post;
    };
}

function convertDependencyArrays(deps) {
    if(!deps) {
        return;
    }

    return zip.toObject(zip(deps).map(function(pair) {
        if(is.array(pair[1])) {
            return [pair[0], {
                items: pair[1]
            }];
        }

        return pair;
    }));
}

function getDependencyDefaults(globalAlias) {
    return {
        'default': {
            items: null,
        },
        amd: {
            items: null,
            prefix: '\"',
            separator: ',',
            suffix: '\"',
        },
        cjs: {
            items: null,
            prefix: 'require(\"',
            separator: ',',
            suffix: '\")',
        },
        global: {
            items: null,
            prefix: globalAlias? globalAlias + '.': '\"',
            separator: ',',
            suffix: '\"',
        }
    };
}

module.exports = function(code, options) {
    var u = new UMD(code, options);

    return u.generate();
};

function id(a) {return a;}


text:
package com.google.api.codegen.viewmodel.metadata;

import com.google.api.codegen.SnippetSetRunner;
import com.google.api.codegen.config.VersionBound;
import com.google.api.codegen.packagegen.PackagingArtifactType;
import com.google.api.codegen.viewmodel.FileHeaderView;
import com.google.api.codegen.viewmodel.ViewModel;
import com.google.auto.value.AutoValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;

@AutoValue
public abstract class PackageMetadataView implements ViewModel {

  @Override
  public String resourceRoot() {
    return SnippetSetRunner.SNIPPET_RESOURCE_ROOT;
  }

  @Override
  public abstract String templateFileName();

  @Override
  public abstract String outputPath();

  @Nullable
  public abstract PackagingArtifactType artifactType();

  @Nullable
  public abstract String packageName();

  @Nullable
  public abstract String identifier();

  @Nullable
  public abstract VersionBound packageVersionBound();

  @Nullable
  public abstract VersionBound gaxVersionBound();

  @Nullable
  public abstract VersionBound gaxGrpcVersionBound();

  public boolean hasGaxGrpcVersionBound() {
    return gaxGrpcVersionBound() != null;
  }

  @Nullable
  public abstract VersionBound gaxHttpVersionBound();

  public boolean hasGaxHttpVersionBound() {
    return gaxHttpVersionBound() != null;
  }

  @Nullable
  public abstract VersionBound grpcVersionBound();

  public boolean hasGrpcVersionBound() {
    return grpcVersionBound() != null;
  }

  @Nullable
  public abstract VersionBound protoVersionBound();

  @Nullable
  public abstract List<PackageDependencyView> protoPackageDependencies();

  @Nullable
  public abstract List<PackageDependencyView> additionalDependencies();

  public List<PackageDependencyView> dependencies() {
    List<PackageDependencyView> dependencies = new ArrayList<PackageDependencyView>();
    if (protoPackageDependencies() != null) {
      dependencies.addAll(protoPackageDependencies());
    }
    if (additionalDependencies() != null) {
      dependencies.addAll(additionalDependencies());
    }
    Collections.sort(dependencies);
    return dependencies;
  }

  @Nullable
  public abstract List<PackageDependencyView> protoPackageTestDependencies();

  @Nullable
  public abstract VersionBound authVersionBound();

  public abstract String fullName();

  public abstract String shortName();

  public abstract String protoPackageName();

  @Nullable
  public abstract String grpcPackageName();

  public abstract String gapicPackageName();

  public abstract String majorVersion();

  public abstract String protoPath();

  @Nullable
  public abstract String versionPath();

  @Nullable
  public abstract String rootNamespace();

  @Nullable
  public abstract String versionNamespace();

  public abstract String author();

  public abstract String email();

  public abstract String homepage();

  public abstract String licenseName();

  @Nullable
  public abstract String developmentStatus();

  public abstract boolean hasMultipleServices();

  public abstract boolean hasSmokeTests();

  // TODO(landrito) Currently only Ruby/Python supports using fileHeaderView. Switch all metadata
  // gen to use this field.
  @Nullable
  public abstract FileHeaderView fileHeader();

  @Nullable
  public abstract String credentialsClassName();

  // Python-specific configuration
  @Nullable
  public abstract List<String> namespacePackages();

  @Nullable
  public abstract List<String> apiModules();

  @Nullable
  public abstract List<String> typeModules();

  @Nullable
  public abstract List<String> clientModules();

  @Nullable
  public abstract ReadmeMetadataView readmeMetadata();

  @Nullable
  public abstract String smokeTestProjectVariable();

  @Nullable
  public abstract String smokeTestKeyfileVariable();

  @Nullable
  public abstract String smokeTestJsonKeyVariable();

  @Nullable
  public abstract String projectVariable();

  @Nullable
  public abstract String jsonKeyVariable();

  public abstract boolean publishProtos();

  public static Builder newBuilder() {
    return new AutoValue_PackageMetadataView.Builder().hasSmokeTests(false);
  }

  @AutoValue.Builder
  public abstract static class Builder {
    public abstract Builder outputPath(String val);

    public abstract Builder templateFileName(String val);

    public abstract Builder packageName(String packageName);

    public abstract Builder identifier(String val);

    public abstract Builder artifactType(PackagingArtifactType val);

    public abstract Builder packageVersionBound(VersionBound val);

    public abstract Builder gaxVersionBound(VersionBound val);

    public abstract Builder gaxGrpcVersionBound(VersionBound val);

    public abstract Builder gaxHttpVersionBound(VersionBound val);

    public abstract Builder grpcVersionBound(VersionBound val);

    public abstract Builder protoVersionBound(VersionBound val);

    public abstract Builder protoPackageDependencies(List<PackageDependencyView> val);

    @Nullable
    public abstract Builder protoPackageTestDependencies(List<PackageDependencyView> val);

    /** Additional dependencies. Used for conditionally added dependencies. */
    public abstract Builder additionalDependencies(List<PackageDependencyView> val);

    public abstract Builder authVersionBound(VersionBound val);

    /** The full name of the API, including branding. E.g., "Stackdriver Logging". */
    public abstract Builder fullName(String val);

    /** A single-word short name of the API. E.g., "logging". */
    public abstract Builder shortName(String val);

    /** The base name of the proto client library package. E.g., "proto-google-cloud-logging-v1". */
    public abstract Builder protoPackageName(String val);

    /** The base name of the gRPC client library package. E.g., "grpc-google-cloud-logging-v1". */
    public abstract Builder grpcPackageName(String val);

    /** The base name of the GAPIC client library package. E.g., "gapic-google-cloud-logging-v1". */
    public abstract Builder gapicPackageName(String val);

    /** The major version of the API, as used in the package name. E.g., "v1". */
    public abstract Builder majorVersion(String val);

    /** The path to the API protos in the googleapis repo. */
    public abstract Builder protoPath(String val);

    /* The path to the generated version index file. */
    public abstract Builder versionPath(String val);

    /** The root namespace of the services found within this package, without major version. */
    public abstract Builder rootNamespace(String val);

    /** The namespace of the services found within this package. */
    public abstract Builder versionNamespace(String val);

    /** The author of the package. */
    public abstract Builder author(String val);

    /** The email of the author of the package. */
    public abstract Builder email(String val);

    /** The URL of the homepage of the author of the package. */
    public abstract Builder homepage(String val);

    /** The name of the license that the package is licensed under. */
    public abstract Builder licenseName(String val);

    /** The developement status of the package. E.g., "alpha". */
    public abstract Builder developmentStatus(String val);

    /** Whether the package contains multiple service objects */
    public abstract Builder hasMultipleServices(boolean val);

    /** The packages that should be declared as (Python) namespace packages. */
    public abstract Builder namespacePackages(List<String> val);

    /** The names of the GAPIC modules defining service objects. */
    public abstract Builder apiModules(List<String> val);

    /** The names of the GAPIC modules defining service types. */
    public abstract Builder typeModules(List<String> val);

    /** The names of the GAPIC modules defining clients. */
    public abstract Builder clientModules(List<String> vals);

    /** Whether a smoketest was generated for the package. */
    public abstract Builder hasSmokeTests(boolean val);

    /** File header information such as copyright lines and license lines */
    public abstract Builder fileHeader(FileHeaderView val);

    /** Name of the class that handles authentication for this package */
    public abstract Builder credentialsClassName(String val);

    public abstract Builder readmeMetadata(ReadmeMetadataView val);

    /** Environment variable to determine the Google Cloud project used to run smoke tests. */
    public abstract Builder smokeTestProjectVariable(String s);

    /**
     * Environment variable to determine the Google Cloud service account keyfile used to run smoke
     * tests.
     */
    public abstract Builder smokeTestKeyfileVariable(String s);

    /**
     * Environment variable to determine the contents of the Google Cloud service account keyfile
     * used to run smoke tests.
     */
    public abstract Builder smokeTestJsonKeyVariable(String s);

    /**
     * Environment variable to determine the Google Cloud project used to configure default
     * credentials.
     */
    public abstract Builder projectVariable(String s);

    /**
     * Environment variable to determine the contents of the Google Cloud service account keyfile
     * used to configure default credentials.
     */
    public abstract Builder jsonKeyVariable(String s);

    /** Whether .proto files should be included in the package. */
    public abstract Builder publishProtos(boolean val);

    public abstract PackageMetadataView build();
  }
}


text:
using UnityEngine;
using System.Collections;

public class Singleton<T> : BaseObj where T : MonoBehaviour
{
	protected static T instance;
	public static T Instance
	{
		get
		{
			if(instance == null)
			{
				instance = (T) FindObjectOfType(typeof(T));

				if (instance == null)
				{
					Debug.LogError("An instance of " + typeof(T) +
					               " is needed in the scene, but there is none.");
				}
			}
			return instance;
		}
	}

	new void Awake(){
		base.Awake();
		if(instance == null) { instance = this as T;  }
		else { if(this != instance) Destroy(this.gameObject);}
	}
}


text:
package org.nd4j.graph;

import java.nio.*;
import java.lang.*;
import java.nio.ByteOrder;
import java.util.*;
import com.google.flatbuffers.*;

@SuppressWarnings("unused")
public final class FlatConfiguration extends Table {
  public static void ValidateVersion() { Constants.FLATBUFFERS_1_12_0(); }
  public static FlatConfiguration getRootAsFlatConfiguration(ByteBuffer _bb) { return getRootAsFlatConfiguration(_bb, new FlatConfiguration()); }
  public static FlatConfiguration getRootAsFlatConfiguration(ByteBuffer _bb, FlatConfiguration obj) { _bb.order(java.nio.ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
  public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
  public FlatConfiguration __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }

  public long id() { int o = __offset(4); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
  public byte executionMode() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) : 0; }
  public byte profilingMode() { int o = __offset(8); return o != 0 ? bb.get(o + bb_pos) : 0; }
  public byte outputMode() { int o = __offset(10); return o != 0 ? bb.get(o + bb_pos) : 0; }
  public boolean timestats() { int o = __offset(12); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
  public long footprintForward() { int o = __offset(14); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
  public long footprintBackward() { int o = __offset(16); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
  public byte direction() { int o = __offset(18); return o != 0 ? bb.get(o + bb_pos) : 0; }

  public static int createFlatConfiguration(FlatBufferBuilder builder,
      long id,
      byte executionMode,
      byte profilingMode,
      byte outputMode,
      boolean timestats,
      long footprintForward,
      long footprintBackward,
      byte direction) {
    builder.startTable(8);
    FlatConfiguration.addFootprintBackward(builder, footprintBackward);
    FlatConfiguration.addFootprintForward(builder, footprintForward);
    FlatConfiguration.addId(builder, id);
    FlatConfiguration.addDirection(builder, direction);
    FlatConfiguration.addTimestats(builder, timestats);
    FlatConfiguration.addOutputMode(builder, outputMode);
    FlatConfiguration.addProfilingMode(builder, profilingMode);
    FlatConfiguration.addExecutionMode(builder, executionMode);
    return FlatConfiguration.endFlatConfiguration(builder);
  }

  public static void startFlatConfiguration(FlatBufferBuilder builder) { builder.startTable(8); }
  public static void addId(FlatBufferBuilder builder, long id) { builder.addLong(0, id, 0L); }
  public static void addExecutionMode(FlatBufferBuilder builder, byte executionMode) { builder.addByte(1, executionMode, 0); }
  public static void addProfilingMode(FlatBufferBuilder builder, byte profilingMode) { builder.addByte(2, profilingMode, 0); }
  public static void addOutputMode(FlatBufferBuilder builder, byte outputMode) { builder.addByte(3, outputMode, 0); }
  public static void addTimestats(FlatBufferBuilder builder, boolean timestats) { builder.addBoolean(4, timestats, false); }
  public static void addFootprintForward(FlatBufferBuilder builder, long footprintForward) { builder.addLong(5, footprintForward, 0L); }
  public static void addFootprintBackward(FlatBufferBuilder builder, long footprintBackward) { builder.addLong(6, footprintBackward, 0L); }
  public static void addDirection(FlatBufferBuilder builder, byte direction) { builder.addByte(7, direction, 0); }
  public static int endFlatConfiguration(FlatBufferBuilder builder) {
    int o = builder.endTable();
    return o;
  }
  public static void finishFlatConfigurationBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); }
  public static void finishSizePrefixedFlatConfigurationBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); }

  public static final class Vector extends BaseVector {
    public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }

    public FlatConfiguration get(int j) { return get(new FlatConfiguration(), j); }
    public FlatConfiguration get(FlatConfiguration obj, int j) {  return obj.__assign(__indirect(__element(j), bb), bb); }
  }
}


text:
Influence map
=============

Download the influence map
:download:`PDF </../output/rasmodel_im.pdf>`
:download:`PNG </../output/rasmodel_im.png>`

.. image:: /../output/rasmodel_im.png
    :width: 800px


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;

namespace Simple.Data.Ado
{
    internal static class DataParameterCollectionEx
    {
        public static object GetValue(this IDataParameterCollection parameterCollection, string parameterName)
        {
            var parameter = parameterCollection[parameterName] as DbParameter;
            return parameter != null ? parameter.Value : null;
        }
    }
}


text:
.. _modulelist:

Function Module List
====================

VLCP function modules are classes that can be loaded to / unloaded from the server dynamically.
With different modules loaded, VLCP can provide very different functions. Users may decide which
functions they would like to use by configurating ``server.startup`` configuration.

.. _startup:

==============================
Server Start/Stop and Modules
==============================

When VLCP server starts, all startup modules in ``server.startup`` are loaded into
server and started. They each start their own routines to provide their services.
Some modules have dependencies on other modules, the dependencies are automatically
started first.

The ``server.startup`` configuration is a tuple of *loading paths* of modules.
A module is actually a Python class derived from :py:class:`vlcp.service.module.Module`.
The *loading path* of a module is the full path of the Python module file contains the
class, followed by a dot and the class name, like ``vlcp.service.connection.httpserver.HttpServer``.
The *module name* of a module is the lower-cased class name, like ``httpserver``.
VLCP modules with the same *module name* cannot be loaded or used together.

Server stop when all the routines stop, this is usually when:

   * All connections and server sockets are closed, and all pended jobs are done

   * The server receives an end signal (SIGINT, SIGTERM) and stops all the routines

   * All modules are unloaded

.. _moduleapis:

===========
Module API
===========

Modules provide functions through a lot of methods, the most important one of which
is the **Module API**. Module APIs are methods exposed by the module to be called
from other modules, or directly from the end user.

Parameters for Module APIs are always provided with keyword-arguments: arguments
positions do not matter.

.. _modulecallfromwebapi:

^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Call Module API from WebAPI
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A management module :ref:`module_webapi` exposes all module APIs through a management
HTTP service. Through this management function, you can call module APIs with *curl*::

   curl -g -d 'param1=value1&param2=value2' \
      'http://localhost:8081/modulename/apiname'

The URL path of the request should be /*modulename*/*apiname*, where *modulename* is the
module name i.e. the lower-cased class name, and *apiname* is the API name i.e. the
lower-cased method name.

By default, the management API supports HTTP GET (with query string), HTTP POST (with standard form data),
and HTTP POST with JSON-format POST data. Though use the HTTP GET/POST format is usually the easiest way to
call the API in Shell command-line, when integrating with other systems JSON-format POST may be more
convient.

\`\` quoted expression is a VLCP-specified extension. Some APIs need data types other than strings for its
parameters. When a string parameter is quoted by \`\`, VLCP recognizes it as a literal expression in Python.
You may use numbers, string, tuples, list, dictionary, sets and any combinations of them in a quoted expression::

   curl -g -d 'complexparam=`[1,2,{"name":("value",set(1,2,3))}]`' \
      'http://localhost:8081/modulename/apiname'

Make sure to surround the \`\` expression with \'\' to prevent it from excuting as a shell command.

Also notice that '\[\]' have special meanings in *curl*, that is why we use ``-g`` option to turn it off.

The return value of the module API is formatted with JSON-format, return with ``{"result": <data...>}``
format. If any error occurs, the HTTP request returns a 4xx or 5xx HTTP status, with a JSON body
``{"error": "<errormessage>"}``. Exception details can be found in system logs.

.. _modulecallfromdebuggingconsole:

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Call Module API from Debugging Console
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

When using debugging console module :ref:`module_console`, you can use callapi() method to call module
APIs easily in the debugging console as other modules. This method accepts keyword-arguments. for example::

    for m in callapi(container, "objectdb", "getonce",key="xx"):
        yield m

will call objectdb module api getonce.

.. note:: debugging console module will also start telnet server on localhost:9923
          you can choose telnet it when server run in daemon mode.

.. _moduleapidiscovery:

^^^^^^^^^^^^^^^^^^^^
Module API Discovery
^^^^^^^^^^^^^^^^^^^^

Every module supports a special API ``discovery``. When discovery is called, a list of supported endpoints
and their descriptions are returned. With an extra parameter ``details=true``, it also returns information
for arguments and their default values. For example, you can call::

   curl -g 'http://localhost:8081/viperflow/discover?details=true' | python -m json.tool

To view the API details of module `viperflow`.

.. _reloadmodules:

======================================
Dynamic Load / Unload / Reload Modules
======================================

If :ref:`module_manager` module is loaded, you can use its APIs to load, unload or reload modules
on the fly. When reloading modules, the files containing VLCP module classes are reloaded to use
the latest code on disk, so it is possible to upgrade modules without stopping the service.

.. note:: This should be considered as an advanced feature. Not all modules are strictly tested
          against reloading. Use this function with caution.

.. _allmodulelist:

================
All Module List
================

These are modules currently shipped with VLCP and vlcp-docker-plugin.

.. note:: This is a generated list. Not all module APIs are designed to be used by end users directly.
          Lots of them are providing services for other modules.

.. contents::
   :local:

.. include:: gensrc/allmodulelist.inc

.. _proxymodulelist:

==================
Proxy Module List
==================

Proxy modules are configurable modules that proxy abstract API requests to different implementations. See
:ref:`configkey_proxy` for more information.

.. include:: gensrc/allproxymodules.inc


text:
namespace armnnUtils
{

namespace
{

enum class NodeState
{
    Visiting,
    Visited,
};

template <typename TNodeId>
armnn::Optional<TNodeId> GetNextChild(TNodeId node,
                                      std::function<std::vector<TNodeId>(TNodeId)> getIncomingEdges,
                                      std::map<TNodeId, NodeState>& nodeStates)
{
    for (TNodeId childNode : getIncomingEdges(node))
    {
        if (nodeStates.find(childNode) == nodeStates.end())
        {
            return childNode;
        }
        else
        {
            if (nodeStates.find(childNode)->second == NodeState::Visiting)
            {
                return childNode;
            }
        }
    }

    return {};
}

template<typename TNodeId>
bool TopologicallySort(
    TNodeId initialNode,
    std::function<std::vector<TNodeId>(TNodeId)> getIncomingEdges,
    std::vector<TNodeId>& outSorted,
    std::map<TNodeId, NodeState>& nodeStates)
{
    std::stack<TNodeId> nodeStack;

    // If the node is never visited we should search it
    if (nodeStates.find(initialNode) == nodeStates.end())
    {
        nodeStack.push(initialNode);
    }

    while (!nodeStack.empty())
    {
        TNodeId current = nodeStack.top();

        nodeStates[current] = NodeState::Visiting;

        auto nextChildOfCurrent = GetNextChild(current, getIncomingEdges, nodeStates);

        if (nextChildOfCurrent)
        {
            TNodeId nextChild = nextChildOfCurrent.value();

            // If the child has not been searched, add to the stack and iterate over this node
            if (nodeStates.find(nextChild) == nodeStates.end())
            {
                nodeStack.push(nextChild);
                continue;
            }

            // If we re-encounter a node being visited there is a cycle
            if (nodeStates[nextChild] == NodeState::Visiting)
            {
                return false;
            }
        }

        nodeStack.pop();

        nodeStates[current] = NodeState::Visited;
        outSorted.push_back(current);
    }

    return true;
}

}

// Sorts a directed acyclic graph (DAG) into a flat list such that all inputs to a node are before the node itself.
// Returns true if successful or false if there is an error in the graph structure (e.g. it contains a cycle).
// The graph is defined entirely by the "getIncomingEdges" function which the user provides. For a given node,
// it must return the list of nodes which are required to come before it.
// "targetNodes" is the list of nodes where the search begins - i.e. the nodes that you want to evaluate.
// This is an iterative implementation based on https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
template<typename TNodeId, typename TTargetNodes>
bool GraphTopologicalSort(
    const TTargetNodes& targetNodes,
    std::function<std::vector<TNodeId>(TNodeId)> getIncomingEdges,
    std::vector<TNodeId>& outSorted)
{
    outSorted.clear();
    std::map<TNodeId, NodeState> nodeStates;

    for (TNodeId targetNode : targetNodes)
    {
        if (!TopologicallySort(targetNode, getIncomingEdges, outSorted, nodeStates))
        {
            return false;
        }
    }

    return true;
}

}


text:
from io import StringIO
import unittest

from allauth.account.models import EmailAddress, EmailConfirmation

from django.conf import settings
from django.contrib import auth
from django.core import mail, management
from django.db import IntegrityError
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from django.utils import timezone

from rest_framework.test import APITestCase

from mock import patch

from common.testing import BrowserTestCase, get_or_create_user, SmokeTestCase
from private_sharing.models import DataRequestProject

from .models import Member

UserModel = auth.get_user_model()

class SmokeTests(SmokeTestCase):
    """
    A simple GET test for all of the simple URLs in the site.
    """

    anonymous_urls = ["/account/login/", "/account/password/reset/", "/account/signup/"]

    authenticated_or_anonymous_urls = [
        "/",
        "/about/",
        "/activity/favorite-trance-tracks/",
        "/activity/groovy-music/",
        "/api/public/datafiles/",
        "/api/public/datatypes/",
        "/api/public/members/",
        "/api/public/projects/",
        "/api/public-data/?username=beau",
        "/api/public-data/?created_start=2/14/2016&created_end=2/14/2016",
        "/api/public-data/sources-by-member/",
        "/api/public-data/members-by-source/",
        "/beau/",
        "/community-guidelines/",
        "/contact-us/",
        "/copyright/",
        "/data-use/",
        "/member/beau/",
        "/members/",
        "/members/page/1/",
        "/members/?sort=username",
        "/members/page/1/?sort=username",
        "/public-data/",
        "/public-data-api/",
        "/news/",
        "/create/",
        "/terms/",
        "/gdpr/",
    ]

    redirect_urls = [
        "/account/delete/",
        "/member/beau/email/",
        "/member/me/",
        "/member/me/account-settings/",
        "/member/me/change-email/",
        "/member/me/change-name/",
        "/member/me/connections/",
        # '/member/me/connections/delete/1/',
        "/member/me/edit/",
        "/member/me/joined/",
        "/member/me/data/",
        "/member/me/research-data/delete/pgp/",
        "/member/me/research-data/delete/american_gut/",
        "/member/me/research-data/delete/runkeeper/",
        "/member/me/send-confirmation-email/",
        "/public-data/activate-1-overview/",
        "/public-data/activate-2-information/",
        # require a POST
        # '/public-data/activate-3-quiz/',
        # '/public-data/activate-4-signature/',
        # 301 redirect
        # '/public-data/toggle-sharing/',
        "/public-data/deactivate/",
    ]

    authenticated_urls = redirect_urls + [
        "/account/password/",
        (
            "/oauth2/authorize/?origin=external&response_type=code"
            "&scope=go-viral%20read%20write&client_id=example-id-15"
        ),
    ]

    def test_custom_404(self):
        self.assert_status_code("/does-not-exist/", status_code=404)

    def test_custom_500(self):
        with self.assertRaises(Exception):
            self.assert_status_code("/raise-exception/", status_code=500)

@override_settings(SSLIFY_DISABLE=True)
class OpenHumansUserTests(TestCase):
    """
    Tests for our custom User class.
    """

    fixtures = ["open_humans/fixtures/test-data.json"]

    def setUp(self):  # noqa
        get_or_create_user("user1")

    def test_lookup_by_username(self):
        user1 = auth.authenticate(username="user1", password="user1")

        self.assertEqual(user1.username, "user1")

    def test_lookup_by_email(self):
        user1 = auth.authenticate(username="user1@test.com", password="user1")

        self.assertEqual(user1.username, "user1")

    def test_redirect_on_login(self):
        """
        Redirect to previous page on login.
        """
        first_redirect = "/"
        first_response = self.client.post(
            reverse("account_login"),
            {"next": first_redirect, "login": "chickens", "password": "asdfqwerty"},
        )
        self.assertEqual(first_response.status_code, 302)
        self.assertEqual(first_response.url, first_redirect)

        second_redirect = "/api/public-data/?source=direct-sharing-1"
        second_response = self.client.post(
            reverse("account_login"),
            {"next": second_redirect, "login": "chickens", "password": "asdfqwerty"},
        )
        self.assertEqual(second_response.status_code, 302)
        self.assertEqual(second_response.url, second_redirect)

    def test_password_reset(self):
        """
        Test that password reset works and that we we redirect to the proper
        place when a password reset is made.
        """

        redirect = "/"
        response_request_reset = self.client.post(
            reverse("account_reset_password"),
            {"next_t": redirect, "email": "froopla@borknorp.com"},
        )
        self.assertEqual(response_request_reset.status_code, 302)
        # We should now have mail in the outbox
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, "[Open Humans] Password Reset E-mail")
        reset_url = [
            item
            for item in mail.outbox[0].body.split("\n")
            if "account/password/reset/key" in item
        ][0]
        key = reset_url.split("/")[7]
        # Go ahead and reset the mailbox
        mail.outbox = []
        do_reset_response = self.client.get(reset_url)
        self.assertEqual(do_reset_response.status_code, 200)
        self.assertContains(do_reset_response, "Set your new password")

        do_reset_post_response = self.client.post(
            reset_url, {"password": "asdfqwerty", "password_confirm": "asdfqwerty"}
        )
        self.assertEqual(do_reset_post_response.status_code, 302)
        self.assertEqual(do_reset_post_response.url, redirect)

    def test_lowercase_unique(self):
        # Create a lowercase user2
        UserModel.objects.create_user("user2", "user2@test.com", "user2")

        # Creating an uppercase USER2 should fail
        self.assertRaises(
            IntegrityError,
            UserModel.objects.create_user,
            "USER2",
            "other+user2@test.com",
            "user2",
        )

@unittest.skip("The way the django-oauth model handles the primary key has changed")
class CommandTests(TestCase):
    """
    Tests for our management commands.
    """

    fixtures = ["open_humans/fixtures/test-data.json"]

    def setUp(self):
        self.output = StringIO()

    def test_bulk_email(self):
        try:
            import sys

            out, sys.stdout = sys.stdout, StringIO()
            management.call_command("bulk_email", "-h", stdout=self.output)
            sys.stdout = out
        except SystemExit as e:
            if e.code != 0:
                raise e

    def test_setup_api(self):
        management.call_command("setup_api", stdout=self.output)

    def test_update_badges(self):
        management.call_command("update_badges", stdout=self.output)

    def test_user_connections_json(self):
        management.call_command(
            "user_connections_json", "/dev/null", stdout=self.output
        )

    def test_stats(self):
        management.call_command("stats", "--days=365", stdout=self.output)

class WsgiTests(TestCase):
    """
    Tests for our WSGI application.
    """

    @staticmethod
    def test_import():
        from .wsgi import application  # noqa, pylint: disable=unused-variable

class WelcomeEmailTests(TestCase):
    """
    Tests for our welcome email.
    """

    @patch("open_humans.signals.send_mail")
    def test_send_welcome_email(self, mock):
        user = get_or_create_user("email_test_user")

        member = Member(user=user)
        member.save()

        email = user.emailaddress_set.all()[0]
        email.verified = False
        email.save()

        confirmation = EmailConfirmation.create(email)
        confirmation.sent = timezone.now()
        confirmation.save()

        # confirm the email; this sends the email_confirmed signals
        confirmed_email = confirmation.confirm(request=mock)

        self.assertTrue(confirmed_email is not None)
        self.assertTrue(mock.called)
        self.assertEqual(mock.call_count, 1)
        self.assertEqual(mock.call_args[0][-1][0], "email_test_user@test.com")

class OpenHumansBrowserTests(BrowserTestCase):
    """
    Browser tests of general Open Humans functionality.
    """

    @unittest.skipIf(settings.NOBROWSER, "skipping browser tests")
    def test_create_user(self):
        driver = self.driver

        driver.get(self.live_server_url)

        driver.find_element_by_class_name("signup-link").click()

        username = self.wait_for_element_id("signup-username")

        username.clear()
        username.send_keys("test_123")

        name = driver.find_element_by_id("signup-name")

        name.clear()
        name.send_keys("Test Testerson")

        email = driver.find_element_by_id("email-address")

        email.clear()
        email.send_keys("test@example.com")

        password = driver.find_element_by_id("signup-password")

        password.clear()
        password.send_keys("testing123")

        password_confirm = driver.find_element_by_id("signup-password-confirm")

        password_confirm.clear()
        password_confirm.send_keys("testing123")

        driver.find_element_by_name("terms").click()

        driver.find_element_by_id("create-account").click()

        self.assertEqual(
            "Please verify your email address.",
            driver.find_element_by_css_selector(
                ".call-to-action-3 > .container > h3"
            ).text,
        )

    @unittest.skipIf(settings.NOBROWSER, "skipping browser tests")
    def test_remove_connection(self):
        driver = self.driver

        self.login()

        driver.get(self.live_server_url + "/member/me/connections/")

        driver.find_element_by_xpath(
            "(//a[contains(text(),'Remove connection')])[1]"
        ).click()
        driver.find_element_by_name("remove_datafiles").click()
        driver.find_element_by_css_selector("label").click()
        driver.find_element_by_css_selector("input.btn.btn-danger").click()

@override_settings(SSLIFY_DISABLE=True)
class HidePublicMembershipTestCase(APITestCase):
    """
    Tests whether or not membership in public data activities is properly
    hidden when requested.
    """

    fixtures = ["open_humans/fixtures/test-data.json"]

    def test_public_api(self):
        """
        Tests the public API endpoints.
        """
        user = UserModel.objects.get(username="bacon")
        project = DataRequestProject.objects.get(id=1)
        project_member = project.active_user(user)

        project_member.set_visibility(visible_status=False)
        results = self.client.get("/api/public-data/members-by-source/").data["results"]
        result = {}
        for item in results:
            if item["source"] == "direct-sharing-1":
                result = item
        assert result["usernames"] == []

        project_member.set_visibility(visible_status=True)
        results = self.client.get("/api/public-data/members-by-source/").data["results"]
        result = {}
        for item in results:
            if item["source"] == "direct-sharing-1":
                result = item
        assert result["usernames"] == ["bacon"]