text:
package org.apache.isis.viewer.wicket.ui.pages.accmngt;

import java.util.Map;

import org.apache.wicket.MetaDataKey;
import org.apache.wicket.util.collections.MostRecentlyUsedMap;
import org.apache.wicket.util.time.Duration;
import org.apache.wicket.util.time.Time;

/**
 * A map that contains the emails to be verified. It has a constraint on the maximum entries that it
 * can contain, and a constraint on the duration of time an entry is considered valid/non-expired
 */
public class AccountConfirmationMap extends MostRecentlyUsedMap<String, Object>
{
	private static final long serialVersionUID = 1L;

	public static final MetaDataKey<AccountConfirmationMap> KEY = new MetaDataKey<AccountConfirmationMap>() {
	};

	/**
	 * The actual object that is stored as a value of the map. It wraps the email and
	 * assigns it a creation time.
	 */
	private static class Value
	{
		/** the original email to store */
		private String email;

		/** the time when this email is stored */
		private Time creationTime;
	}

	/**
	 * The duration of time before a {@link Value} is considered as expired
	 */
	private final Duration lifetime;

	/**
	 * Construct.
	 *
	 * @param maxEntries
	 *            how much entries this map can contain
	 * @param lifetime
	 *            the duration of time to keep an entry in the map before considering it expired
	 */
	public AccountConfirmationMap(int maxEntries, Duration lifetime)
	{
		super(maxEntries);

		this.lifetime = lifetime;
	}

	@Override
	protected synchronized boolean removeEldestEntry(java.util.Map.Entry<String, Object> eldest)
	{
		boolean removed = super.removeEldestEntry(eldest);
		if (removed == false)
		{
			Value value = (Value)eldest.getValue();
			if (value != null)
			{
				Duration elapsedTime = Time.now().subtract(value.creationTime);
				if (lifetime.lessThanOrEqual(elapsedTime))
				{
					removedValue = value.email;
					removed = true;
				}
			}
		}
		return removed;
	}

	@Override
	public String put(String key, Object email)
	{
		if (!(email instanceof String))
		{
			throw new IllegalArgumentException(AccountConfirmationMap.class.getSimpleName() +
				" can store only instances of " + String.class.getSimpleName() + ": " + email);
		}

		Value value = new Value();
		value.creationTime = Time.now();
		value.email = (String)email;

		Value oldValue;
		synchronized (this)
		{
			oldValue = (Value)super.put(key, value);
		}

		return oldValue != null ? oldValue.email : null;
	}

	@Override
	public String get(Object key)
	{
		String result = null;
		Value value;
		synchronized (this)
		{
			value = (Value)super.get(key);
		}
		if (value != null)
		{
			Duration elapsedTime = Time.now().subtract(value.creationTime);
			if (lifetime.greaterThan(elapsedTime))
			{
				result = value.email;
			}
			else
			{
				// expired, remove it
				remove(key);
			}
		}
		return result;
	}

	@Override
	public String remove(Object key)
	{
		Value removedValue;
		synchronized (this)
		{
			removedValue = (Value)super.remove(key);
		}

		return removedValue != null ? removedValue.email : null;
	}

	@Override
	public void putAll(Map<? extends String, ?> m)
	{
		throw new UnsupportedOperationException();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.example.tefservices;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// wip debug
		Toast.makeText(getApplicationContext(), " MainActivity [onCreate]", Toast.LENGTH_LONG).show();

		setContentView(R.layout.activity_main);

		// add the buttons defined in the .xml
		Button btnStart = (Button) findViewById(R.id.startBtn);
		Button btnStop = (Button) findViewById(R.id.stopBtn);

		// add the click liteners to the above declared buttons
		btnStart.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// actually start the service
				startService( new Intent(getBaseContext(), MyServices.class) );

			}
		});

		btnStop.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// actually start the service
				stopService( new Intent(getBaseContext(), MyServices.class) );

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


text:
package com.glevel.dungeonhero.models;

/**
 * Created by guillaume on 1/14/15.
 */
public interface Levelable {

    public int getLevel();

}


text:
Seperated interleaved example
=============================

Introduction
------------

This example is taken from Listing S5 in the 2013 JBNMR nmrglue paper.  In
this example a pseudo-3D NMRPipe data set is seperated into 2D data sets using
the script `seperate.py`.

Instructions
------------

Execute `python seperate.py` to seperate the pseudo-3D data set into 2D data
sets.  Six directories with names `techo_XXXX.fid` will be created.


text:
import { AdventureDataModel } from './adventure-data.model';

export class AdventureModel {
    objectId: string;
    ownerId: string;
    created: number;
    name: string;
    description: string;
    titlePhoto: string;
    data: AdventureDataModel[];
    length: number;
}


text:
(function (angular) {
    'use strict';

    var module = angular.module('drf-form-field', [
        'drf-form-field.templates',
        'angular-bind-html-compile'
    ]);

    module.directive('drfFormField', [
        '$templateCache',
        function (
            $templateCache
        ) {
            return {
                restrict: 'A',
                scope: true,
                replace: true,
                transclude: true,
                template: function (elem, attrs) {
                    var templateBase = 'templates/drf/form-field/';
                    var defaultTemplate = 'form-field.html';
                    var templateUrl = templateBase + (angular.isDefined(attrs.type) ? attrs.type + '.html' : defaultTemplate);
                    return $templateCache.get(templateUrl) || $templateCache.get(templateBase + defaultTemplate);
                },
                link: function (scope, element, attrs, ctrl, transcludeFn) {
                    // Define a default object, so that assigning
                    // scope.label to scope.field.label does not fall over
                    // if scope.field is undefined whilst waiting for an
                    // API response. We'll also need to watch that property on the
                    // scope for changes and update it.
                    scope.field = scope.$eval(attrs.drfFormField) || {};

                    scope.$watch(attrs.drfFormField, function (field) {
                        scope.field = scope.$eval(attrs.drfFormField) || {};
                    });

                    scope.$watch('field', function (field) {
                        scope.label = angular.isDefined(attrs.label) ? attrs.label : scope.field.label;
                        scope.id = angular.isDefined(attrs.fieldId) ? attrs.fieldId : scope.field.id;
                    });

                    transcludeFn(function (clone) {
                        var transcludeContainer = angular.element(element[0].querySelector('.transclude-container'));
                        transcludeContainer.replaceWith(clone);
                    });
                }
            };
        }
    ]);
}(window.angular));


text:
cd `dirname $0`/..

mvn clean test
bin/extract_snippets.sh

rm -rf doc
cp -r target/doc/src/test/java/doc/ doc

#pandoc target/classes/main/index.md \
#--template=target/classes/main/template.html \
#--smart \
#--standalone \
#--toc \
#-o target/classes/main/index.html


text:
<!--

-->
<dom-module id="simpl-datatables-shared-styles">
	<template>
		<style include="scrollbar-css">
			:host table.responsive.dataTables {
				width: 100%;
				max-width: 100%;
				font-size: 12px;
				cursor: default;
				border: 0 none;
				-webkit-user-select: text;
				-moz-user-select: text;
				-ms-user-select: text;
				user-select: text;
				@apply --simpl-datatables-table;
			}

			:host table.responsive.dataTables thead tr {
				height: 24px;
				@apply --simpl-datatables-header-row;

			}
			@media screen and (max-width: 767px) {
				:host table.responsive.dataTables thead tr {
					height: 28px;
					@apply --simpl-datatables-header-row;
				}
			}

			:host table.responsive.dataTables tbody tr {
				@apply --simpl-datatables-body-row;

			}
			:host div.dataTables_scrollHead {
				@apply --simpl-datatables-scroll-head;
			}
			:host div.dataTables_scrollBody {
				@apply --simpl-datatables-scroll-body;
			}
			:host div.dataTables_empty {
				@apply --simpl-datatables-empty;
      }
			@media screen and (max-width: 767px) {
				:host table.responsive.dataTables tbody tr {
					@apply --simpl-datatables-body-row;
				}
			}

			:host table.responsive.dataTables tbody tr.selected {
				@apply --simpl-datatables-body-row-selected;
      }
			:host table.responsive.dataTables thead tr th {
				@apply --simpl-datatables-header-cell;
      }
			:host table.responsive.dataTables tbody tr td {
				@apply --simpl-datatables-data-cell;
      }
			:host table.responsive.dataTables tbody tr td.noSwipe {
				user-select:all;
      }
      :host table.responsive.dataTables tfoot tr th {
				@apply --simpl-datatables-footer-cell;
      }

			:host table.responsive.dataTables.dtr-column > tbody > tr > td.control:before{
				@apply --simpl-datatables-control;
			}
      :host table.responsive.dataTables.dtr-column > tbody > tr > th.control:before {
				@apply --simpl-datatables-control;
			}

			:host table.responsive.dataTables > tbody > tr.child span.dtr-title {
				@apply --simpl-datatables-detail-title;
			}

			:host  #dataTablesId_length {
				max-width: 170px;
				font-size: 12px;
				margin-bottom: 2px;
				float: left;
			}
			:host  #dataTablesId_length select {
				font-size: 11px;
				width: 50px;
			}
			:host  #dataTablesId_length label {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				display: block;
			}
			:host  #dataTablesId_filter label {
				font-size: 12px;
				margin-top: 2px;
			}
			:host  #dataTablesId_filter input {
				width: 90px;
				margin-top: 2px;
				@apply --simpl-datatables-filter;
			}
			:host  table.dataTable td {
				height: 24px;
			}
			:host  table.dataTable.dtr-column > tbody > tr > td.control:before,
			:host  table.dataTable.dtr-column > tbody > tr > th.control:before {
				margin-top: -10px;
				line-height: 16px;
				@apply --simpl-datatables-detail-opener;
			}
			:host.firefox  table.dataTable.dtr-column > tbody > tr > td.control:before,
			:host.firefox  table.dataTable.dtr-column > tbody > tr > th.control:before {
				line-height: 14px !important;
			}
			:host  table.dataTable.dtr-inline.collapsed > tbody > tr > td:first-child:before,
			:host table.dataTable.dtr-inline.collapsed > tbody > tr > th:first-child:before {
				top: 6px;
				font-size: 16px;
				line-height: 16px;
				font-weight: 800;
				border: var(--simpl-datatables-detailbutton-border, 2px solid white);
				border-radius: var(--simpl-datatables-detailbutton-border-radius, 3px);
				box-shadow: var(--simpl-datatables-detailbutton-box-shadow, 0 0 3px #444);
				color: var(--simpl-datatables-detailbutton-closed-color, black);
				background: var(--simpl-datatables-detailbutton-closed-background, brown);
			}
			:host.firefox  table.dataTable.dtr-inline.collapsed > tbody > tr > td:first-child:before,
			:host.firefox  table.dataTable.dtr-inline.collapsed > tbody > tr > th:first-child:before {
				top: 4px !important;
			}
			:host table.dataTable.dtr-inline.collapsed > tbody > tr.parent > td:first-child:before,
			:host table.dataTable.dtr-inline.collapsed > tbody > tr.parent > th:first-child:before {
				color: var(--simpl-datatables-detailbutton-open-color, black);
				background: var(--simpl-datatables-detailbutton-open-background, gray);
			}
			:host  table.dataTable.dtr-inline.collapsed > tbody > tr.selected > td:first-child:before,
			:host table.dataTable.dtr-inline.collapsed > tbody > tr.selected > th:first-child:before {
				color: var(--simpl-datatables-detailbutton-closed-selected-color, white);
			}
			:host  table.responsive.dataTables thead tr th,
			:host  table.responsive.dataTables tfoot tr th {
				color: var(--simpl-datatables-header-color, --secondary-text-color);
				background: var(--simpl-datatables-header-background, --light-primary);
			}
			:host  .dataTables_scroll {
				border-bottom: var(--simpl-datatables-scroll-border-bottom, --light-primary);
			}
			:host  table.responsive.dataTables thead th,
			:host  table.responsive.dataTables thead td {
				border-top: var(--simpl-datatables-border-top, --secondary-text-color);
				border-bottom: var(--simpl-datatables-border-bottom, --light-primary);
			}
			:host  #dataTablesId[aria-describedby] {
				border-bottom: 0px solid #e0e0e0;
			}
			:host  #dataTablesId.border thead tr th:first-child {
				border-left: 1px solid gray;
				border-top-left-radius: 3px;
			}
			:host  #dataTablesId.border thead tr th:last-child {
				border-right: 1px solid gray;
				border-top-right-radius: 3px;
			}
			:host  #dataTablesId.border tbody tr td:first-child {
				border-left: 1px solid gray;
			}
			:host  #dataTablesId.border tbody tr td:last-child {
				border-right: 1px solid gray;
			}
			:host table.responsive.dataTables tbody tr td:not(:first-child) {
				padding: var(--simpl-datatables-cell-padding, 2px 8px 3px);
				line-height: 1.0;
			}
			:host  table.responsive.dataTables tbody tr td:first-child {
				padding: var(--simpl-datatables-cell-padding-first, 3px 28px 3px);
			}
			table.dataTable thead th,
			table.dataTable tfoot th {
				text-align: left;
			}
			:host  table.dataTable thead th,
			:host  table.dataTable tfoot th {
				padding: var(--simpl-datatables-header-padding, 0em 0.625em 0em);
				line-height: 1.6;
			}
			:host  table.responsive.dataTables tbody tr.odd.selected,
			:host  table.dataTable.display tbody tr.odd.selected,
			:host  table.responsive.dataTables tbody tr.even.selected,
			:host  table.dataTable.display tbody tr.even.selected {
				color: var(--simpl-datatables-selected-color, --secondary-text-color);
				background: var(--simpl-datatables-selected-background, --light-primary);
			}
			:host  table.responsive.dataTables thead tr th:first-child {
				padding: 0px 30px 0px;
			}
			:host  table.responsive.dataTables .dtr-title {
				font-size: 13px;
			}
			:host  table.responsive.dataTables .dtr-data {
				white-space: normal;
				font-size: 12px;
			}
			:host table.responsive.dataTables td {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
			:host  .paginate_enabled_previous,
			:host  .paginate_enabled_next {
				font-size: 2.2em !important;
				font-weight: bold !important;
				cursor: pointer;
			}
			:host /deep/ .paginate_disabled_previous,
			:host /deep/ .paginate_disabled_next {
				font-size: 2.2em !important;
				cursor: normal;
				visibility: hidden;
			}
			:host  .paginate_disabled_previous,
			:host  .paginate_enabled_previous {
				margin-right: 25px;
			}
			:host  .dataTables_info {
				float: left !important;
				text-align: left !important;
				@apply --simpl-datatables-info;
			}
			:host  .dataTables_paginate {
				text-align: right !important;
				padding: 0px !important;
			}
			:host  .dataTables_paginate {
				margin-top: 0.05em !important;
				@apply --simpl-datatables-paginate;
			}
			:host  .dataTables_scrollBody {
				overflow-x: hidden !important;
			}
			:host  .dataTables_wrapper.no-footer .dataTables_scrollBody {
				border-bottom: 0px solid #111;
			}
			:host  .dataTables_wrapper {
				height:100%;
			}
			:host > div {
				color: var(--simpl-datatables-container-color, --secondary-text-color);
				background: var(--simpl-datatables-container-background, --light-primary);
			}
			:host table.dataTables.responsive {
				color: var(--simpl-datatables-table-color, --secondary-text-color);
				background: var(--simpl-datatables-table-background, --light-primary);
				margin-bottom: 0em;
				border: solid 0px;
				border-collapse: initial;
				border-spacing: 0;
			}
			:host  .dataTables_paginate.paging_two_button {
				margin-right: 4px;
			}
			:host  table.dataTable > tbody > tr.child ul li {
				border-bottom: 1px solid #efefef;
				padding: 0em 0;
			}
			:host.firefox table.dataTable > tbody > tr.child ul li {
				border-bottom: 1px solid #efefef;
				padding: 0.2em 0;
			}
			:host  span.dtr-data {
				display: inline-block;
			}

			:host  table.dataTables >thead tr th.control,
      :host  table.dataTables >tbody tr td.control {
        padding: 0 !important;
				min-width:35px;
        width: var(--simpl-datatables-control-width, 35px) !important;
        max-width: var(--simpl-datatables-control-width, 35px);
        display: var(--simpl-datatables-control-display, table-cell);
      }

			input {
        border: 1px solid #b0abab;
        min-height: 20px;
        border-radius: 3px;
      }

		</style>
	</template>
</dom-module>


text:
layout:     post
title:      backache
date:       2017-05-14 22:54:03
summary:
categories: drawing
---
![backache](/images/diary/backache.png "It fucking hurts.")


text:
import STORE from "store";
import RENDERER from "renderer";

export default class OfflinePlaybackWebSocketEndpoint {
    constructor(serverAddr) {
        this.serverAddr = serverAddr;
        this.websocket = null;
        this.lastUpdateTimestamp = 0;
        this.lastSeqNum = -1;
        this.requestTimer = null;
        this.processTimer = null;
        this.frameData = {}; // cache frames
        this.routingTime2Path = {};
    }

    initialize(params) {
        if (params && params.id && params.map) {
            STORE.playback.setRecordId(params.id);
            STORE.playback.setMapId(params.map);
        } else {
            console.error("ERROR: missing required parameter(s)");
            return;
        }

        if (params.url) {
            this.serverUrl = `${location.protocol}//${params.url}`;
        }

        try {
            this.websocket = new WebSocket(this.serverAddr);
        } catch (error) {
            console.error("Failed to establish a connection: " + error);
            setTimeout(() => {
                this.initialize(params);
            }, 1000);
            return;
        }
        this.websocket.onopen = event => {
            this.requestGroundMeta(STORE.playback.mapId);
        };
        this.websocket.onmessage = event => {
            const message = JSON.parse(event.data);

            switch (message.type) {
                case "GroundMetadata":
                    RENDERER.updateGroundMetadata(this.serverUrl, message.data);
                    this.requestFrameCount(STORE.playback.recordId);
                    break;
                case "FrameCount":
                    STORE.playback.setNumFrames(message.data);
                    if (STORE.playback.hasNext()) {
                        this.requestSimulationWorld(STORE.playback.recordId, STORE.playback.next());
                    }
                    break;
                case "RoutePath":
                    this.routingTime2Path[message.routingTime] = message.routePath;
                    break;
                case "SimWorldUpdate":
                    this.checkMessage(message);
                    STORE.setInitializationStatus(true);

                    const world = (typeof message.world) === "string"
                        ? JSON.parse(message.world): message.world;

                    if (world.routePath) {
                        this.routingTime2Path[world.routingTime] = world.routePath;
                    } else if (!(world.routingTime in this.routingTime2Path)) {
                        // A new routing needs to be fetched from backend.
                        this.requestRoutePath(STORE.playback.recordId, world.sequenceNum);
                    }

                    if (STORE.playback.isSeeking) {
                        this.processSimWorld(world);
                    }

                    if (world.sequenceNum && !(world.sequenceNum in this.frameData)) {
                        this.frameData[world.sequenceNum] = world;
                    }

                    break;
            }
        };
        this.websocket.onclose = event => {
            console.log("WebSocket connection closed, close_code: " + event.code);
            this.initialize(params);
        };
    }

    checkMessage(message) {
        if (this.lastUpdateTimestamp !== 0
            && message.timestamp - this.lastUpdateTimestamp > 150) {
            console.log("Last sim_world_update took " +
                (message.timestamp - this.lastUpdateTimestamp) + "ms");
        }
        this.lastUpdateTimestamp = message.timestamp;
        if (this.lastSeqNum !== -1
            && message.world.sequenceNum > this.lastSeqNum + 1) {
            console.debug("Last seq: " + this.lastSeqNum +
                ". New seq: " + message.world.sequenceNum + ".");
        }
        this.lastSeqNum = message.world.sequenceNum;
    }

    startPlayback(msPerFrame) {
        clearInterval(this.requestTimer);
        this.requestTimer = setInterval(() => {
            if (this.websocket.readyState === this.websocket.OPEN && STORE.playback.initialized()) {
                if (!STORE.playback.hasNext()) {
                    clearInterval(this.requestTimer);
                    this.requestTimer = null;
                    return;
                }

                this.requestSimulationWorld(STORE.playback.recordId, STORE.playback.next());
            }
        }, msPerFrame/2);

        clearInterval(this.processTimer);
        this.processTimer = setInterval(() => {
            if (STORE.playback.initialized()) {
                const frameId = STORE.playback.seekingFrame;
                if (frameId in this.frameData) {
                    this.processSimWorld(this.frameData[frameId]);
                }

                if (STORE.playback.replayComplete) {
                    clearInterval(this.processTimer);
                    this.processTimer = null;
                }
            }
        }, msPerFrame);
    }

    pausePlayback() {
        clearInterval(this.requestTimer);
        clearInterval(this.processTimer);
        this.requestTimer = null;
        this.processTimer = null;
    }

    requestGroundMeta(mapId) {
        this.websocket.send(JSON.stringify({
            type: 'RetrieveGroundMeta',
            mapId: mapId,
        }));
    }

    processSimWorld(world) {
        if (STORE.playback.shouldProcessFrame(world)) {
            if (!world.routePath) {
                world.routePath = this.routingTime2Path[world.routingTime];
            }

            STORE.updateTimestamp(world.timestamp);
            RENDERER.maybeInitializeOffest(
                world.autoDrivingCar.positionX,
                world.autoDrivingCar.positionY);
            RENDERER.updateWorld(world);
            STORE.meters.update(world);
            STORE.monitor.update(world);
            STORE.trafficSignal.update(world);
        }
    }

    requestFrameCount(recordId) {
        this.websocket.send(JSON.stringify({
            type: 'RetrieveFrameCount',
            recordId: recordId,
        }));
    }

    requestSimulationWorld(recordId, frameId) {
        if (!(frameId in this.frameData)) {
            this.websocket.send(JSON.stringify({
                type : "RequestSimulationWorld",
                recordId: recordId,
                frameId: frameId,
            }));
        } else if (STORE.playback.isSeeking) {
            this.processSimWorld(this.frameData[frameId]);
        }
    }

    requestRoutePath(recordId, frameId) {
        this.websocket.send(
            JSON.stringify({
                type: "requestRoutePath",
                recordId: recordId,
                frameId: frameId,
            })
        );
    }
}


text:
#pragma once

#include <memory>
#include <QNetworkAccessManager>

#include "problem.h"
#include "liveevent.h"
#include "userrank.h"
#include "usersubmission.h"
#include "submission.h"
#include "uvalib_global.h"

namespace uva
{

    class UVA_EXPORT Uhunt : public QObject
    {
        Q_OBJECT
    public:

        typedef QMap<Problem::Key, Problem> ProblemMap;

        typedef QMap<LiveEvent::Key, LiveEvent> LiveEventMap;

        /*!
            \brief Initialize the Uhunt object with the application's
                   QNetworkAccessManager.

            \param[in] manager Network access manager used for the application.
         */
        Uhunt(std::shared_ptr<QNetworkAccessManager> manager);

        /*!
            \brief Convert JSON data into a ProblemMap

            \param[in] json utf8 formatted json data

            \return A ProblemMap.
        */
        static ProblemMap problemMapFromJson(const QByteArray &json);

        /*!
            \brief Convert JSON data into a LiveEventMap.

            \param[in] json utf8 formatted json data

            \return  A LiveEventMap.
        */
        static LiveEventMap liveEventMapFromJson(const QByteArray &json);

        /*!
            \brief Converts JSON data into a list of UserRank objects.

            \param[in] json utf8 formatted json data.

            \return List of UserRank structs.
        */
        static QList<UserRank> userRankingsFromJson(const QByteArray &json);

        /*!
            \brief Converts JSON data into a list of user submissions to problems.
            \param[in] json utf8 formatted json data.
            \return List of UserSubmission structs.
        */
        static QList<UserSubmission> userSubmissionsFromJson(const QByteArray &json);

        /*!
            \brief Converts json data into a list of User Submissions.

            \param json utf8 formatted json data.
            \param userID UserID of the user

            \return A QList<UserSubmission>
        */
        static QList<UserSubmission> userSubmissionsFromJson(const QByteArray &json, int userID);

    signals:

        void problemByIdDownloaded(Problem);

        void allProblemsDownloaded(QByteArray);

        void liveEventsDownloaded(Uhunt::LiveEventMap);

        void userIDDownloaded(QString userName, int userID);

        void userSubmissionsJsonDownloaded(const QByteArray&, int userId, int lastSub);

        void userSubmissionsByUserIDDownloaded(QList<UserSubmission>);

        void userSubmissionsByProblemIDDownloaded(QList<UserSubmission>);

        void userRanksByPositionDownloaded(QList<UserRank>);

        void userRanksByUserIDDownloaded(QList<UserRank>);

        void userSubmissionsByProblemRankDownloaded(QList<UserSubmission>);

        void userRankOnProblemDownloaded(QList<UserSubmission>);

    public slots:

        /*!
            \brief Accesses the Uhunt API to get get a problem by its id.

            Emits problemByIdDownloaded() when finished successfully.
        */
        void problemById(int problemID);

        /*!
            \brief Accesses the Uhunt API to get all problem meta data available
                    in the UVA Online Judge as Json data. Use
                    Uhunt::problemMapFromJson() to convert the data.

            The downloaded json should be saved to a file. This function
            should not be called often.

            The download is approximately 500kb. Emits allProblemsDownloaded()
            when finished successfully.
        */
        void allOnlineJudgeProblems();

        /*!
            \brief  Accesses the Uhunt API to get the live judging queue.
                    Use the latest live event ID from the downloaded events
                    for subsequent calls to this function.

            Emits liveEventsDownloaded() when finished.

            \param[in] lastSubmissionID ID of the submission from where the list
                        should begin. The value 0 means latest 100 submissions.
        */
        void liveEvents(quint64 lastSubmissionID = 0);

        /*!
            \brief Accesses the Uhunt API to get the ID of a user from
                   the username.

            Emits userIDDownloaded() when finished.

            \param[in] userName Username of the user.
        */
        void userIDFromUserName(const QString& userName);

        /*!
            \brief Accesses the Uhunt API to get the submissions to problems
                   of a user from the user's ID.

            Emits userSubmissionsByUserIDDownloaded() when finished.

            \param[in] userID ID of the user.
            \param[in] lastSub ID of the submission from where the list should
                       begin. The value 0 means the list should start from
                       the very first submission.
        */
        void userSubmissionsByUserID(int userID, int lastSubmissionID = 0);

        /*!
            \brief Accesses the Uhunt API to get rankings centered on a
                   specific user.

            set above and below to 0 to get the user with userID's ranking.

            Emits userRanksByUserIDDownloaded() when finished.

            \param[in] userID ID of the user
            \param[in] nAbove Number of users above the userId
            \param[in] nBelow Number of users below the userId
        */
        void userRanksByUserID(int userID, int above = 10, int below = 10);

        /*!
            \brief Accesses the Uhunt API to get user rankings starting from a
                   certain position, and ending at the starting rank + count - 1.

             Emits userRanksByPositionDownloaded() when finished.

            \param[in] startPos Rank from where the list starts.
            \param[in] count Number of rankings to retrieve.
        */
        void userRanksByPosition(int startPos = 1, int count = 100);

        /*!
            \brief Accesses the Uhunt API to get a list of submissions to a
                    specific problem.

            Emits userSubmissionsOnProblemDownloaded() when finished.

            \param[in] problemID ID of the problem
            \param[in] startTime Time from when to start in UNIX timestamp
            \param[in] endTime Time from when to stop in UNIX timestamp
        */
        void userSubmissionsByProblemID(int problemID, quint64 startTime, quint64 endTime);

        /*!
            \brief Accesses the Uhunt API to get a list of user submissions
                   to a problem based on the users rank to that problem.

            Emits userSubmissionsByProblemRankDownloaded() when finished.

            \param[in] problemID ID of the problem.
            \param[in] startRank Rank to start from.
            \param[in] count Number of submissions on the list.
        */
        void userSubmissionsByProblemRank(int problemId, int startRank = 1, int count = 25);

        /*!
            \brief Gets a list of submissions on a problem focusing the rank of an user.

            Emits userSubmissionsByProblemRankDownloaded() when finished.

            \param[in] problemID ID of the problem
            \param[in] userID Id of the user
            \param[in] above Number of user listed below
            \param[in] below Number of user listed above
        */
        //void userSubmissionsByProblem(int problemID, int userId, int above = 10, int below = 10);

    private:

        QNetworkReply* createNetworkRequest(QString url);

        std::shared_ptr<QNetworkAccessManager> mNetworkManager;
    };
}


text:
package com.intellij.diagnostic.logging;

import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import consulo.ui.image.Image;
import org.jdom.Element;

import javax.annotation.Nullable;

/**
 * User: anna
 * Date: 22-Mar-2006
 */
public class LogFilter implements JDOMExternalizable {
  public String myName;
  private Image myIcon;

  public LogFilter(final String name, final Image icon) {
    myName = name;
    myIcon = icon;
  }

  public LogFilter(String name) {
    myName = name;
  }

  //read external
  public LogFilter() {
  }

  @Override
  public String toString() {
    return myName;
  }

  public void setIcon(final Image icon) {
    myIcon = icon;
  }

  public boolean isAcceptable(String line){
    return true;
  }

  public String getName(){
    return myName;
  }

  @Nullable
  public Image getIcon() {
    return myIcon;
  }

  @Override
  public void readExternal(Element element) throws InvalidDataException {
    DefaultJDOMExternalizer.readExternal(this, element);
  }

  @Override
  public void writeExternal(Element element) throws WriteExternalException {
    DefaultJDOMExternalizer.writeExternal(this, element);
  }
}


text:
import { run } from '@ember/runloop';
import { NAMESPACES, NAMESPACES_BY_ID } from '@ember/-internals/metal';

function NamespacesAssert(env) {
  this.env = env;
}

NamespacesAssert.prototype = {
  reset: function() {},
  inject: function() {},
  assert: function() {
    let { assert } = QUnit.config.current;

    if (NAMESPACES.length > 0) {
      assert.ok(false, 'Should not have any NAMESPACES after tests');
      run(() => {
        let namespaces = NAMESPACES.slice();
        for (let i = 0; i < namespaces.length; i++) {
          namespaces[i].destroy();
        }
      });
    }
    let keys = Object.keys(NAMESPACES_BY_ID);
    if (keys.length > 0) {
      assert.ok(false, 'Should not have any NAMESPACES_BY_ID after tests');
      for (let i = 0; i < keys.length; i++) {
        delete NAMESPACES_BY_ID[keys[i]];
      }
    }
  },
  restore: function() {},
};

export default NamespacesAssert;


text:
'use strict';

var path = require('path');
var execFile = require('child_process').execFile;
var parseHelp = require('parse-help');
var assign = require('lodash').assign;

/**
 * The Completer is in charge of handling `yo-complete` behavior.
 * @constructor
 * @param  {Environment} env A yeoman environment instance
 */
var Completer = module.exports = function (env) {
  this.env = env;
};

/**
 * Completion event done
 *
 * @param {String}   data   Environment object as parsed by tabtab
 * @param {Function} done   Callback to invoke with completion results
 */
Completer.prototype.complete = function (data, done) {
  if (data.last !== 'yo' && !/^-/.test(data.last)) {
    return this.generator(data, done);
  }

  this.env.lookup(function (err) {
    if (err) {
      return done(err);
    }

    var meta = this.env.getGeneratorsMeta();
    var results = Object.keys(meta).map(this.item('yo'), this);
    done(null, results);
  }.bind(this));
};

/**
 * Generator completion event done
 *
 * @param {String}   data   Environment object as parsed by tabtab
 * @param {Function} done   Callback to invoke with completion results
 */
Completer.prototype.generator = function (data, done) {
  var last = data.last;
  var bin = path.join(__dirname, '../cli.js');

  execFile('node', [bin, last, '--help'], function (err, out) {
    if (err) {
      return done(err);
    }

    var results = this.parseHelp(last, out);
    done(null, results);
  }.bind(this));
};

/**
 * Helper to format completion results into { name, description } objects
 *
 * @param {String}   data   Environment object as parsed by tabtab
 * @param {Function} done   Callback to invoke with completion results
 */
Completer.prototype.item = function (desc, prefix) {
  prefix = prefix || '';
  return function (item) {
    var name = typeof item === 'string' ? item : item.name;
    desc = typeof item !== 'string' && item.description ? item.description : desc;
    desc = desc.replace(/^#?\s*/g, '');
    desc = desc.replace(/:/g, '->');
    desc = desc.replace(/'/g, ' ');

    return {
      name: prefix + name,
      description: desc
    };
  };
};

/**
 * parse-help wrapper. Invokes parse-help with stdout result, returning the
 * list of completion items for flags / alias.
 *
 * @param {String}   last  Last word in COMP_LINE (completed line in command line)
 * @param {String}   out   Help output
 */
Completer.prototype.parseHelp = function (last, out) {
  var help = parseHelp(out);
  var alias = [];
  var results = Object.keys(help.flags).map(function (key) {
    var flag = help.flags[key];
    if (flag.alias) {
      alias.push(assign({}, flag, { name: flag.alias }));
    }
    flag.name = key;
    return flag;
  }).map(this.item(last, '--'), this);

  results = results.concat(alias.map(this.item(last.replace(':', '_'), '-'), this));
  results = results.filter(function (r) {
    return r.name !== '--help' && r.name !== '-h';
  });

  return results;
};


text:
import './chunk-1fafdf15.js';
import './helpers.js';
import './chunk-6985c8ce.js';
import './chunk-d0a313ea.js';
import './chunk-cdfca85b.js';
import { r as registerComponent, u as use } from './chunk-cca88db8.js';
import './chunk-1fd9f1ff.js';
import './chunk-1196ee55.js';
import './chunk-42f463e6.js';
import './chunk-4d76806f.js';
import './chunk-eb60b35a.js';
import './chunk-77ffdf8b.js';
import { T as Timepicker } from './chunk-381ae107.js';
export { T as BTimepicker } from './chunk-381ae107.js';

var Plugin = {
  install: function install(Vue) {
    registerComponent(Vue, Timepicker);
  }
};
use(Plugin);

export default Plugin;


text:
using namespace seqan;

int main ()
{

    typedef Index<DnaString,IndexQGram<OneGappedShape>> TIndex;
    TIndex index("CATGATTACATA");
	stringToShape(indexShape(index),"1101");
	hash(indexShape(index),"AC-T");

	for (unsigned i = 0; i < length(getOccurrences(index, indexShape(index))); ++i)
	{
		std::cout << getOccurrences(index, indexShape(index))[i] << std::endl;
	}

    return 0;

}


text:
<?php
if(!isset($_SESSION)) { session_start(); }
require_once ("config.php");
require_once ("mysql.php");
require_once ("functions.php");
include("header.php");

//	Is an admin using this?
[$user_provider, $user_providerID, $user_name] = get_user_details(true);

//	Hardcoded for @edent
if ("twitter" == $user_provider && 14054507 == $user_providerID)
{
	$originalID  = $_POST["originalID"];
	$duplicateID = $_POST["duplicateID"];
	if ($originalID != null && $duplicateID != null)
	{
		merge_benches($originalID, $duplicateID);
		echo "Redirected {$duplicateID}
";
	}
?>
	<form action="merge.php" method="post" autocomplete="off">
	Original:  <input type="text" name="originalID" autofocus>

	Duplicate: <input type="text" name="duplicateID">

	<input type="submit" value="Merge Benches">
	</form>

<?php
} else {
	die();
}

include("footer.php");


text:
import dnuconfig.settings
from dnuconfig.dnuconfig import DNUConfig

YES = 'Yes'
NO = 'No'

if __name__ == '__main__':
    config = DNUConfig()
    config.set_domain(raw_input('Domain (site address): '))
    uses_virtualenv = False
    VIRTUALENV_DIR = None
    if (raw_input('Do You using virtealenv? y/n: ').lower() in ['y', 'yes']):
        config.set_virtualenv(uses=True, directory=raw_input('Path to virtualenv: '))

    config.set_django_settings_module(
        module=raw_input('Define django settings module [settings]: '.format(dnuconfig.settings.DJANGO_SETTINGS_MODULE)))

    config.set_module_to_run(raw_input('Define module to run [{}]'.format(dnuconfig.settings.MODULE_TO_RUN)))
    config.set_project_dir(directory=raw_input('Define project directory: '))
    config.set_app_name(raw_input('Define main application name (where is the wsgi module): '))


text:
"""Test check utilities."""
# Authors: MNE Developers
#          Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD-3-Clause
import os
import os.path as op
import sys

import numpy as np
import pytest
from pathlib import Path

import mne
from mne import read_vectorview_selection
from mne.datasets import testing
from mne.io.pick import pick_channels_cov, _picks_to_idx
from mne.utils import (check_random_state, _check_fname, check_fname, _suggest,
                       _check_subject, _check_info_inv, _check_option, Bunch,
                       check_version, _path_like, _validate_type, _on_missing,
                       requires_nibabel, _safe_input, _check_ch_locs,
                       _check_sphere)

data_path = testing.data_path(download=False)
base_dir = op.join(data_path, 'MEG', 'sample')
fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')
fname_event = op.join(base_dir, 'sample_audvis_trunc_raw-eve.fif')
fname_fwd = op.join(base_dir, 'sample_audvis_trunc-meg-vol-7-fwd.fif')
fname_mgz = op.join(data_path, 'subjects', 'sample', 'mri', 'aseg.mgz')
reject = dict(grad=4000e-13, mag=4e-12)

@testing.requires_testing_data
def test_check(tmp_path):
    """Test checking functions."""
    pytest.raises(ValueError, check_random_state, 'foo')
    pytest.raises(TypeError, _check_fname, 1)
    _check_fname(Path('./foo'))
    fname = tmp_path / 'foo'
    with open(fname, 'wb'):
        pass
    assert op.isfile(fname)
    _check_fname(fname, overwrite='read', must_exist=True)
    orig_perms = os.stat(fname).st_mode
    os.chmod(fname, 0)
    if not sys.platform.startswith('win'):
        with pytest.raises(PermissionError, match='read permissions'):
            _check_fname(fname, overwrite='read', must_exist=True)
    os.chmod(fname, orig_perms)
    os.remove(fname)
    assert not op.isfile(fname)
    pytest.raises(IOError, check_fname, 'foo', 'tets-dip.x', (), ('.fif',))
    pytest.raises(ValueError, _check_subject, None, None)
    pytest.raises(TypeError, _check_subject, None, 1)
    pytest.raises(TypeError, _check_subject, 1, None)
    # smoke tests for permitted types
    check_random_state(None).choice(1)
    check_random_state(0).choice(1)
    check_random_state(np.random.RandomState(0)).choice(1)
    if check_version('numpy', '1.17'):
        check_random_state(np.random.default_rng(0)).choice(1)

@testing.requires_testing_data
@pytest.mark.parametrize('suffix',
                         ('_meg.fif', '_eeg.fif', '_ieeg.fif',
                          '_meg.fif.gz', '_eeg.fif.gz', '_ieeg.fif.gz'))
def test_check_fname_suffixes(suffix, tmp_path):
    """Test checking for valid filename suffixes."""
    new_fname = tmp_path / op.basename(fname_raw).replace('_raw.fif', suffix)
    raw = mne.io.read_raw_fif(fname_raw).crop(0, 0.1)
    raw.save(new_fname)
    mne.io.read_raw_fif(new_fname)

def _get_data():
    """Read in data used in tests."""
    # read forward model
    forward = mne.read_forward_solution(fname_fwd)
    # read data
    raw = mne.io.read_raw_fif(fname_raw, preload=True)
    events = mne.read_events(fname_event)
    event_id, tmin, tmax = 1, -0.1, 0.15

    # decimate for speed
    left_temporal_channels = read_vectorview_selection('Left-temporal')
    picks = mne.pick_types(raw.info, meg=True,
                           selection=left_temporal_channels)
    picks = picks[::2]
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    del picks

    raw.info.normalize_proj()  # avoid projection warnings

    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                        baseline=(None, 0.), preload=True, reject=reject)

    noise_cov = mne.compute_covariance(epochs, tmin=None, tmax=0.)

    data_cov = mne.compute_covariance(epochs, tmin=0.01, tmax=0.15)

    return epochs, data_cov, noise_cov, forward

@testing.requires_testing_data
def test_check_info_inv():
    """Test checks for common channels across fwd model and cov matrices."""
    epochs, data_cov, noise_cov, forward = _get_data()

    # make sure same channel lists exist in data to make testing life easier
    assert epochs.info['ch_names'] == data_cov.ch_names
    assert epochs.info['ch_names'] == noise_cov.ch_names

    # check whether bad channels get excluded from the channel selection
    # info
    info_bads = epochs.info.copy()
    info_bads['bads'] = info_bads['ch_names'][1:3]  # include two bad channels
    picks = _check_info_inv(info_bads, forward, noise_cov=noise_cov)
    assert [1, 2] not in picks
    # covariance matrix
    data_cov_bads = data_cov.copy()
    data_cov_bads['bads'] = data_cov_bads.ch_names[0]
    picks = _check_info_inv(epochs.info, forward, data_cov=data_cov_bads)
    assert 0 not in picks
    # noise covariance matrix
    noise_cov_bads = noise_cov.copy()
    noise_cov_bads['bads'] = noise_cov_bads.ch_names[1]
    picks = _check_info_inv(epochs.info, forward, noise_cov=noise_cov_bads)
    assert 1 not in picks

    # test whether reference channels get deleted
    info_ref = epochs.info.copy()
    info_ref['chs'][0]['kind'] = 301  # pretend to have a ref channel
    picks = _check_info_inv(info_ref, forward, noise_cov=noise_cov)
    assert 0 not in picks

    # pick channels in all inputs and make sure common set is returned
    epochs.pick_channels([epochs.ch_names[ii] for ii in range(10)])
    data_cov = pick_channels_cov(data_cov, include=[data_cov.ch_names[ii]
                                                    for ii in range(5, 20)])
    noise_cov = pick_channels_cov(noise_cov, include=[noise_cov.ch_names[ii]
                                                      for ii in range(7, 12)])
    picks = _check_info_inv(epochs.info, forward, noise_cov=noise_cov,
                            data_cov=data_cov)
    assert list(range(7, 10)) == picks

def test_check_option():
    """Test checking the value of a parameter against a list of options."""
    allowed_values = ['valid', 'good', 'ok']

    # Value is allowed
    assert _check_option('option', 'valid', allowed_values)
    assert _check_option('option', 'good', allowed_values)
    assert _check_option('option', 'ok', allowed_values)
    assert _check_option('option', 'valid', ['valid'])

    # Check error message for invalid value
    msg = ("Invalid value for the 'option' parameter. Allowed values are "
           "'valid', 'good', and 'ok', but got 'bad' instead.")
    with pytest.raises(ValueError, match=msg):
        assert _check_option('option', 'bad', allowed_values)

    # Special error message if only one value is allowed
    msg = ("Invalid value for the 'option' parameter. The only allowed value "
           "is 'valid', but got 'bad' instead.")
    with pytest.raises(ValueError, match=msg):
        assert _check_option('option', 'bad', ['valid'])

def test_path_like():
    """Test _path_like()."""
    str_path = str(base_dir)
    pathlib_path = Path(base_dir)
    no_path = dict(foo='bar')

    assert _path_like(str_path) is True
    assert _path_like(pathlib_path) is True
    assert _path_like(no_path) is False

def test_validate_type():
    """Test _validate_type."""
    _validate_type(1, 'int-like')
    with pytest.raises(TypeError, match='int-like'):
        _validate_type(False, 'int-like')

@requires_nibabel()
@testing.requires_testing_data
def test_suggest():
    """Test suggestions."""
    names = mne.get_volume_labels_from_aseg(fname_mgz)
    sug = _suggest('', names)
    assert sug == ''  # nothing
    sug = _suggest('Left-cerebellum', names)
    assert sug == " Did you mean 'Left-Cerebellum-Cortex'?"
    sug = _suggest('Cerebellum-Cortex', names)
    assert sug == " Did you mean one of ['Left-Cerebellum-Cortex', 'Right-Cerebellum-Cortex', 'Left-Cerebral-Cortex']?"  # noqa: E501

def test_on_missing():
    """Test _on_missing."""
    msg = 'test'
    with pytest.raises(ValueError, match=msg):
        _on_missing('raise', msg)
    with pytest.warns(RuntimeWarning, match=msg):
        _on_missing('warn', msg)
    _on_missing('ignore', msg)

    with pytest.raises(ValueError,
                       match='Invalid value for the \'on_missing\' parameter'):
        _on_missing('foo', msg)

def _matlab_input(msg):
    raise EOFError()

def test_safe_input(monkeypatch):
    """Test _safe_input."""
    monkeypatch.setattr(mne.utils.check, 'input', _matlab_input)
    with pytest.raises(RuntimeError, match='Could not use input'):
        _safe_input('whatever', alt='nothing')
    assert _safe_input('whatever', use='nothing') == 'nothing'

@testing.requires_testing_data
def test_check_ch_locs():
    """Test _check_ch_locs behavior."""
    info = mne.io.read_info(fname_raw)
    assert _check_ch_locs(info=info)

    for picks in ([0], [0, 1], None):
        assert _check_ch_locs(info=info, picks=picks)

    for ch_type in ('meg', 'mag', 'grad', 'eeg'):
        assert _check_ch_locs(info=info, ch_type=ch_type)

    # drop locations for EEG
    picks_eeg = _picks_to_idx(info=info, picks='eeg')
    for idx in picks_eeg:
        info['chs'][idx]['loc'][:3] = np.nan

    # EEG tests should fail now
    assert _check_ch_locs(info=info, picks=picks_eeg) is False
    assert _check_ch_locs(info=info, ch_type='eeg') is False

    # tests for other (and "all") channels should still pass
    assert _check_ch_locs(info=info)
    assert _check_ch_locs(info=info, ch_type='mag')

# Check a bunch of version schemes as of 2022/03/01
# We don't have to get this 100% generalized, but it would be nice if all
# of these worked.
@pytest.mark.parametrize('version, want, have_unstripped', [
    # test some dev cases
    ('1.23.0.dev0+782.g1168868df6', '1.23', False),  # NumPy
    ('1.9.0.dev0+1485.b06254e', '1.9', False),  # SciPy
    ('3.6.0.dev1651+g30d6161406', '3.6', False),  # matplotlib
    ('1.1.dev0', '1.1', False),  # sklearn
    ('0.56.0dev0+39.gef1ba4c10', '0.56', False),  # numba
    ('9.1.0.rc1', '9.1', False),  # VTK
    ('0.3dev0', '0.3', False),  # mne-connectivity
    ('0.2.2.dev0', '0.2.2', False),  # mne-qt-browser
    ('3.2.2+150.g1e93bd5d', '3.2.2', True),  # nibabel
    # test some stable cases
    ('1.2.3', '1.2.3', True),
    ('1.2', '1.2', True),
    ('1', '1', True),
])
def test_strip_dev(version, want, have_unstripped, monkeypatch):
    """Test that stripping dev works."""
    monkeypatch.setattr(
        mne.utils.check, 'import_module',
        lambda x: Bunch(__version__=version))
    got_have_unstripped, same_version = check_version(
        version, want, strip=False, return_version=True)
    assert same_version == version
    assert got_have_unstripped is have_unstripped
    have, simpler_version = check_version(
        'foo', want, return_version=True)  # strip=True is the default
    assert have, (simpler_version, version)

    def looks_stable(version):
        try:
            [int(x) for x in version.split('.')]
        except ValueError:
            return False
        else:
            return True

    if looks_stable(version):
        assert 'dev' not in version
        assert 'rc' not in version
        assert simpler_version == version
    else:
        assert simpler_version != version
    assert 'dev' not in simpler_version
    assert 'rc' not in simpler_version
    assert not simpler_version.endswith('.')
    assert looks_stable(simpler_version)

@testing.requires_testing_data
def test_check_sphere_verbose():
    """Test that verbose is handled properly in _check_sphere."""
    info = mne.io.read_info(fname_raw)
    with info._unlock():
        info['dig'] = info['dig'][:20]
    with pytest.warns(RuntimeWarning, match='may be inaccurate'):
        _check_sphere('auto', info)
    with mne.use_log_level('error'):
        _check_sphere('auto', info)


text:
package main

import (
	"math/rand"
	"os"
	"path/filepath"
	"reflect"
	"strconv"
	"testing"
	"time"

	"github.com/boltdb/bolt"
)

func TestMain(m *testing.M) {
	db = MustOpenDB()
	exitVal := m.Run()
	db.MustClose()

	os.Exit(exitVal)
}

func randInt() int {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return r.Intn(10000)
}

func tempfilePath(prefix string) string {
	var name string
	dir := os.TempDir()
	conflict := true

	for i := 0; i < 10000; i++ {
		name = filepath.Join(dir, prefix+strconv.Itoa(randInt()))

		if _, err := os.Stat(name); os.IsNotExist(err) {
			conflict = false
			break
		}
	}

	if conflict {
		panic("couldn't find a suitable tempfile path")
	}

	return name
}

func MustOpenDB() *DB {
	bdb, err := bolt.Open(tempfilePath("nogo-db-"), 0666, nil)
	if err != nil {
		panic(err)
	}

	return &DB{bdb}
}

func (db *DB) Reset() {
	db.Update(func(tx *bolt.Tx) error {
		// Delete bucket
		tx.DeleteBucket(blacklistKey)
		return nil
	})

	if err := db.Update(func(tx *bolt.Tx) error {
		// Create bucket
		_, err := tx.CreateBucket(blacklistKey)
		return err
	}); err != nil {
		panic(err)
	}
}

func (db *DB) MustClose() {
	defer os.Remove(db.Path())

	if err := db.Close(); err != nil {
		panic(err)
	}
}

func testEqual(t *testing.T, msg string, args ...interface{}) bool {
	if !reflect.DeepEqual(args[len(args)-2], args[len(args)-1]) {
		t.Errorf(msg, args...)
		return false
	}
	return true
}


text:
package org.dbflute.erflute.editor.view.action.edit;

import java.util.ArrayList;
import java.util.List;

import org.dbflute.erflute.core.DisplayMessages;
import org.dbflute.erflute.editor.controller.editpart.element.node.DiagramWalkerEditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.ui.actions.SelectAllAction;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchPart;

public class SelectAllContentsAction extends SelectAllAction {

    private final IWorkbenchPart part;

    public SelectAllContentsAction(IWorkbenchPart part) {
        super(part);
        this.part = part;
        setText(DisplayMessages.getMessage("action.title.select.all"));

        setActionDefinitionId("org.eclipse.ui.edit.selectAll");
    }

    @Override
    public void run() {
        final GraphicalViewer viewer = (GraphicalViewer) part.getAdapter(GraphicalViewer.class);
        if (viewer != null) {
            final List<DiagramWalkerEditPart> children = new ArrayList<>();

            for (final Object child : viewer.getContents().getChildren()) {
                if (child instanceof DiagramWalkerEditPart) {
                    final DiagramWalkerEditPart editPart = (DiagramWalkerEditPart) child;
                    if (editPart.getFigure().isVisible()) {
                        children.add(editPart);
                    }
                }
            }

            viewer.setSelection(new StructuredSelection(children));
        }
    }
}


text:
"""Checksum."""
import threading
import hashlib
import zlib
import traceback
import contextlib
import mmap
from . import whirlpool
from . import tiger
from . import sum_hashes

DEFAULT_CHECKSUM = "md5"
VALID_HASH = []

active_thread = None

def get_hash(name):
    """Get hash."""

    try:
        return hashlib.new(name)
    except Exception:
        return _additional_hashes[name]()

class HashThread(threading.Thread):
    """Thread hashing."""

    def __init__(self, f, obj):
        """Initialize."""

        self.hash = False
        self.file_obj = f
        self.obj = obj
        self.abort = False
        self.error = None
        self.count = 0
        threading.Thread.__init__(self)

    def kill(self):
        """Kill the thread."""

        self.abort = True

    def run(self):
        """Run command."""

        try:
            with contextlib.closing(mmap.mmap(self.file_obj.fileno(), 0, access=mmap.ACCESS_READ)) as m:
                chunk = m.read(4096)
                while chunk and not self.abort:
                    self.obj.update(chunk)
                    chunk = m.read(4096)
                    self.count += len(chunk)
        except Exception:
            self.error = str(traceback.format_exc())

class ZlibAlgorithm:
    """`Zlib` hash algorithm."""

    __algorithm = None
    __name = None
    __digest_size = 0
    __hash = 0

    @property
    def name(self):
        """The hash name."""

        return self.__name

    @property
    def digest_size(self):
        """Size of the digest."""

        return self.__digest_size

    def algorithm(self, name, digest_size, start, arg):
        """The main algorithm."""

        self.__algorithm = getattr(zlib, name)
        self.__name = name
        self.__digest_size = digest_size
        self.__hash = start
        self.update(arg)

    def copy(self):
        """Get copy."""

        import copy
        return copy.deepcopy(self)

    def digest(self):
        """Get digest."""

        return None if self.__algorithm is None else self.__hash & 0xffffffff

    def hexdigest(self):
        """Get hex digest."""

        return None if self.__algorithm is None else '%08x' % (self.digest())

    def update(self, arg):
        """Update the hash."""

        if self.__algorithm is not None:
            self.__hash = self.__algorithm(arg, self.__hash)

class crc32(ZlibAlgorithm):  # noqa
    """`crc32` hash."""

    def __init__(self, arg=b''):
        """Initialize."""

        self.algorithm('crc32', 4, 0, arg)

class adler32(ZlibAlgorithm):  # noqa
    """`adler32` hash."""

    def __init__(self, arg=b''):
        """Initialize."""

        self.algorithm('adler32', 4, 1, arg)

def _verify_hashes(hashes):
    """Verify the hashes are valid."""

    for item in hashes:
        try:
            hashlib.new(item)
            VALID_HASH.append(item)
        except Exception:
            pass

_available_hashes = list(set([x.lower() for x in hashlib.algorithms_available]))
_verify_hashes(_available_hashes)

_additional_hashes = {
    'adler32': adler32,
    'crc32': crc32,
    'sum8': sum_hashes.sum8,
    'sum16': sum_hashes.sum16,
    'sum24': sum_hashes.sum24,
    'sum32': sum_hashes.sum32,
    'xor8': sum_hashes.xor8,
    'tiger': tiger.tiger,
    'whirlpool': whirlpool.whirlpool
}

for k, v in _additional_hashes.items():
    try:
        hashlib.new(k)
    except Exception:
        VALID_HASH.append(k)

VALID_HASH.sort()


text:
var gulp = require('gulp');

var browserify = require('gulp-browserify');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var jsonminify = require('gulp-jsonminify');
var uglify = require('gulp-uglify');

var bower = './bower_components';
var node = './node_modules';

var paths = {
  geojson: ['app/json/countries.js'],
  scripts: 'app/src/**',
  startpoint: 'app/src/app.js',
  css: 'app/css/**.*',
  html: 'app/index.html',
  libs: [
    bower + '/jquery/dist/jquery.min.js',
    bower + '/d3/d3.min.js',
    bower + '/leaflet-dist/leaflet.js',
    bower + '/underscore/underscore.js',
    bower + '/backbone/backbone.js',
  ]
};

gulp.task('default', ['clean', 'concat-libs', 'copy-assets', 'browserify', 'watch']);

gulp.task('clean', function () {
  gulp.src('./deploy/app.js', {
    read: false
  })
    .pipe(clean());
});

gulp.task('concat-libs', function () {
  gulp.src(paths.libs)
    .pipe(concat('libs.js'))
    .pipe(gulp.dest('./deploy'));
});

gulp.task("copy-assets", function () {
  gulp.src(paths.css)
    .pipe(gulp.dest("./deploy/css"));

  gulp.src("app/json/countries.js")
    .pipe(gulp.dest("./deploy/json"));

  gulp.src(paths.html)
    .pipe(gulp.dest("./deploy/"));
});

gulp.task('browserify', function () {
  gulp.src(paths.startpoint)
    .pipe(browserify({
      insertGlobals: false,
      debug: false
    }))
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./deploy'));
});

gulp.task('watch', function () {
  gulp.watch(paths.scripts, ['browserify']);
  gulp.watch(paths.css, ['copy-assets']);
  gulp.watch(paths.html, ['copy-assets']);
});

// Utility task
gulp.task('minify-json', function () {
  gulp.src(paths.geojson)
    .pipe(jsonminify())
    .pipe(gulp.dest('app/json'));
});


text:
package de.codesourcery.lsystems.lsystem;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import de.codesourcery.lsystems.lsystem.Token.TokenType;

public class ExpressionLexer implements TokenStream
{
	private static boolean DEBUG=false;

	private final List<Token> tokens = new ArrayList<>();

	private final Scanner scanner;
	private final StringBuilder buffer = new StringBuilder();

	public static TokenSeq parse(String s) {
		ExpressionLexer lexer = new ExpressionLexer(s);
		final List<Token> tok = new ArrayList<>();
		while( ! lexer.eof() ) {
			tok.add( lexer.next() );
		}
		return TokenSeq.create( tok );
	}

	protected static final class Scanner {

		private final String s;
		private int index;
		private char currentSymbol;

		public Scanner(String s) {
			this.s = s;
			currentSymbol = s.charAt(0);
		}

		public boolean eof() {
			return index >= s.length();
		}

		public char peek() {
			if ( eof() ) {
				throw new IllegalStateException("Already at EOF");
			}
			return currentSymbol;
		}

		public char next() {
			char c = currentSymbol;
			index++;
			if ( index < s.length() ) {
				currentSymbol = s.charAt(index);
			}
			return c;
		}

		public char next(char c)
		{
			if ( peek() != c ) {
				throw new RuntimeException("Expected '"+c+"' but got '"+peek()+"' at offset "+getOffset());
			}
			return next();
		}

		public int getOffset() {
			return index;
		}
	}

	public ExpressionLexer(String s)
	{
		if ( DEBUG) {
			System.out.println("PARSING >"+s+"<");
		}
		this.scanner = new Scanner(s);
	}

	public boolean eof()
	{
		if ( tokens.isEmpty() ) {
			parseTokens();
		}
		return tokens.isEmpty();
	}

	private void parseTokens()
	{
		while ( ! scanner.eof() && Character.isWhitespace( scanner.peek() ) )
		{
			scanner.next();
		}

		if ( scanner.eof() ) {
			return;
		}

		// careful , the cases in this switch need to be in line with the switch in parseToken()
		if ( DEBUG ) {
			System.out.println("Peek(): "+scanner.peek());
		}
		switch( scanner.peek() )
		{
			case '[':
				tokens.add( parseToken(TokenType.PUSH_STATE ) );
				break;
			case ']':
				tokens.add( parseToken(TokenType.POP_STATE ) );
				break;
			case 'g':
				tokens.add( parseToken(TokenType.COLOR_GREEN) );
				break;
			case 'b':
				tokens.add( parseToken(TokenType.COLOR_BLUE) );
				break;
			case 'r':
				tokens.add( parseToken(TokenType.COLOR_RED ) );
				break;
			case 'c':
				tokens.add( parseToken(TokenType.DRAW_CIRCLE ) );
				break;
			case 'C':
				tokens.add( parseToken(TokenType.DRAW_FILLED_CIRCLE ) );
				break;
			case 'f':
				tokens.add( parseToken(TokenType.FORWARD_NODRAW ) );
				break;
			case 'F':
				tokens.add( parseToken(TokenType.FORWARD) );
				break;
			case '+':
				tokens.add( parseToken(TokenType.ROTATE_LEFT) );
				break;
			case '-':
				tokens.add( parseToken(TokenType.ROTATE_RIGHT) );
				break;
			default:
				tokens.add( parseToken(TokenType.CHARACTERS) );
				break;
		}
	}

	private boolean isKnownSymbol(char c)
	{
		// careful , the cases in this switch need to be in line with the switch in parseTokens()
		switch(c)
		{
			case '[':
			case ']':
			case 'g':
			case 'b':
			case 'r':
			case 'c':
			case 'C':
			case 'f':
			case 'F':
			case '+':
			case '-':
				return true;
			default:
				return false;
		}
	}

	private Token parseToken(TokenType tokenType)
	{
		final String literal;
		if ( TokenType.CHARACTERS.equals(tokenType) )
		{
			buffer.setLength( 0 );
			while ( ! scanner.eof() && ! isKnownSymbol( scanner.peek() ) ) {
				buffer.append( scanner.next() );
			}
			literal = buffer.toString();
		} else {
			literal = Character.toString( scanner.next() );
		}

		List<String> params = null;
		if ( !scanner.eof() && tokenType.supportsParameters() && scanner.peek() == '(' )
		{
			final int argListOffset = scanner.getOffset();
			scanner.next('(');

			params = new ArrayList<>();
			final StringBuilder currentParam = new StringBuilder();
			while ( ! scanner.eof() && scanner.peek() != ')' )
			{
				if ( Character.isWhitespace( scanner.peek() ) ) {
					scanner.next();
					continue;
				}
				if ( scanner.peek() == ',' && ! currentParam.toString().isEmpty() )
				{
					scanner.next(',');
					params.add( currentParam.toString() );
					currentParam.setLength(0);
					continue;
				}
				currentParam.append( scanner.next() );
			}

			if ( scanner.eof() ) {
				throw new RuntimeException("Missing ')' at index "+scanner.getOffset());
			}
			if ( ! currentParam.toString().isEmpty() ) {
				params.add( currentParam.toString() );
			}
			scanner.next(')');

			if ( params.size() < tokenType.getMinParameterCount() || params.size() > tokenType.getMaxParameterCount() ) {
				throw new RuntimeException("Argument at index "+argListOffset+" has wrong parameter count "+params.size()+" , needs to be ["+
						tokenType.getMinParameterCount()+","+tokenType.getMaxParameterCount()+"]");
			}
		}
		Token result = new Token(tokenType,literal , params );
		if ( DEBUG ) {
			System.out.println(">> "+result+" (type:"+tokenType+")");
		}
		return result;
	}

	public Token next()
	{
		if ( eof() ) {
			throw new IllegalStateException("Already at EOF");
		}
		return tokens.remove(0);
	}

	public Token peek()
	{
		if ( eof() ) {
			throw new IllegalStateException("Already at EOF");
		}
		return tokens.get(0);
	}

	@Override
	public Iterator<Token> iterator()
	{
		return new Iterator<Token>() {

			@Override
			public boolean hasNext() {
				return ! eof();
			}

			@Override
			public Token next() {
				return ExpressionLexer.this.next();
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException("remove()");
			}
		};
	}
}


text:
namespace mscorlib
{
	namespace System
	{
		namespace Runtime
		{
			namespace ExceptionServices
			{

				//Public Methods Tests

				// Method Throw
				//		Signature:
				TEST(mscorlib_System_Runtime_ExceptionServices_ExceptionDispatchInfo_Fixture,Throw_Test)
				{

				}

				//Public Static Methods Tests

				// Method Capture
				//		Signature: mscorlib::System::Exception source
				TEST(mscorlib_System_Runtime_ExceptionServices_ExceptionDispatchInfo_Fixture,Capture_StaticTest)
				{

				}

				//Public Properties Tests

				// Property SourceException
				//		Return Type: mscorlib::System::Exception
				//			Property Get Method
				TEST(mscorlib_System_Runtime_ExceptionServices_ExceptionDispatchInfo_Fixture,get_SourceException_Test)
				{

				}

			}
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDepartment.Filters;
using MVCDepartment.Models;
using WebMatrix.WebData;

namespace MVCDepartment.Controllers
{
    [InitializeSimpleMembership]
    public class ScheduleController : Controller
    {
        private Entities db = new Entities();

        //
        // GET: /Schedule/

        public ActionResult Index()
        {
            return View(db.Schedules.ToList());
        }

        //
        // GET: /Schedule/Details/5

        public ActionResult Details(int id = 0)
        {
            Schedule schedule = db.Schedules.Find(id);
            if (schedule == null)
            {
                return HttpNotFound();
            }
            return View(schedule);
        }

        //
        // GET: /Schedule/Create

        public ActionResult Create()
        {
            ViewBag.Disciplines = new SelectList(db.Disciplines.AsEnumerable(), "Id", "Name");
            return View();
        }

        //
        // POST: /Schedule/Create

        [HttpPost]
        public ActionResult Create(Schedule schedule)
        {
            if (ModelState.IsValid)
            {
                schedule.Discipline = db.Disciplines.Find(Convert.ToInt32(Request["discipline_id"]));
                schedule.UserAccount = db.UserAccounts.Find(WebSecurity.CurrentUserId);
                db.Schedules.Add(schedule);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(schedule);
        }

        //
        // GET: /Schedule/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Schedule schedule = db.Schedules.Find(id);
            if (schedule == null)
            {
                return HttpNotFound();
            }
            return View(schedule);
        }

        //
        // POST: /Schedule/Edit/5

        [HttpPost]
        public ActionResult Edit(Schedule schedule)
        {
            if (ModelState.IsValid)
            {
                db.Entry(schedule).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(schedule);
        }

        //
        // GET: /Schedule/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Schedule schedule = db.Schedules.Find(id);
            if (schedule == null)
            {
                return HttpNotFound();
            }
            return View(schedule);
        }

        //
        // POST: /Schedule/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Schedule schedule = db.Schedules.Find(id);
            db.Schedules.Remove(schedule);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


text:
[![Gem Version](https://badge.fury.io/rb/gh-trending.svg)](https://badge.fury.io/rb/gh-trending)

# Gh::Trending

A simple gem to parse trending repositories and developers from the github's [trending page](https://github.com/trending).

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'gh-trending'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install gh-trending

## Usage

There are two ways of using this gem:

* To fetch trending repositories:

`Gh::Trending::Repositories.get(language:, time_period:)`

* To fetch trending developers:

`Gh::Trending::Developers.get(language:, time_period:)`

The arguments `language` and `time_period` are provided in hash syntax, and they
are **not** required. Below there are simplified examples

Accepted values for the `time_period` argument (as of **Jun 2017**):

* `:daily` (default) => Will return the trending developers/repositories in the last day
* `:weekly` => Will return the trending developers/repositories in the last week
* `:monthly` => Will return the trending developers/repositories in the last month.

* If you don't provide any value for the `time_period` argument, the value `:daily` is used.
* If you don't provide any value for the `language` argument, it uses the default github's trending page option, which considers **all languages**.
* If you provide an unknown `time_period` argument, an error is raised
* If you don't provide any value for both arguments, this returns the trending developers/repositories for **all languages**, in the **last day**.

### Examples

#### Trending developers

```ruby
Gh::Trending::Developers.get
# => [
# <Gh::Trending::Developer:0x00000002f87760
# @full_name="Dawson Corwin",
# @hot_repository_url="http://denesiklehner.org/josianne",
# @user_profile_url="http://hane.co/camren"
# ,
# ...
# ]
```

* `full_name` => The full name of the developer
* `hot_repository_url` => The name of the repository that is trending for this developer, in the provided `time_period` and `language`.
  * In the example above, since no `language` and `time_period` were provided, the repository `"http://denesiklehner.org/josianne"` is the trending repository of this user, since the last day for any language.
* `user_profile_url` => The github user profile url.

#### Trending repositories

```ruby
Gh::Trending::Repositories.get language: 'javascript'
# => [#<Gh::Trending::Repository:0x000000035231b0
 #  @description="Unicode's answer to Base64",
 #  @language="JavaScript",
 #  @name="/qntm/base65536",
 #  @period_stars=104,
 #  @url="https://github.com/qntm/base65536">,
 # #<Gh::Trending::Repository:0x00000003511d70
 #  @description="Prettier is an opinionated JavaScript formatter.",
 #  @language="JavaScript",
 #  @name="/prettier/prettier",
 #  @period_stars=100,
 #  @url="https://github.com/prettier/prettier">,
 # ]
```
* `description` => The description of the repository
* `language` => Primary programming language of the repository (should match the one provided in the `language` argument, if provided)
* `name` => The name of the repository
* `url` => The github's URL of the repository
* `period_stars` => The number of stars of the repository in the requested `time_period`.

## Dependencies

* [Mechanize](https://github.com/sparklemotion/mechanizes)

## Tests

To run the test suite:

`rake spec`

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
package couponswipe.data.util;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * This interface will define the methods that any ConnectionPool implementation
 * should implement.
 *
 */
public interface IConnectionPool {
	Connection getConnection() throws SQLException;
}


text:
<?php

class Model_ProductHosting extends \RedBean_SimpleModel
{

}


text:
import sys
import warnings

sys.path.append('.')
import gdbutil

true = True
false = False

VERSION = 'v0.8'

class jemalloc:

    def __init__(self, chunks = [], chunk_size = 0, \
        arenas = [], narenas = 0, runs = [], nbins = 0, \
        magrack_size = 0, magaz_flag = false, \
        standalone_flag = false):

        self.chunks = chunks
        self.chunk_size = chunk_size
        self.arenas = arenas
        self.narenas = narenas
        self.nbins = nbins
        self.ntbins = 0
        self.nsbins = 0
        self.nqbins = 0
        self.magrack_size = magrack_size
        self.DWORD_SIZE = gdbutil.get_dword_size()
        self.runs = runs

        self.MAGAZINES = magaz_flag
        self.STANDALONE = standalone_flag

    def __str__(self):

        if self.MAGAZINES == false:
            return '[unmask_jemalloc] [jemalloc] [arenas %02d] [bins %02d]' \
                   ' [runs %02d]' % (self.narenas, self.nbins, len(self.runs))
        else:
            return '[unmask_jemalloc] [jemalloc] [arenas %02d] [bins %02d] ' \
                   '[runs %02d] [magazine rack/tcache size %04d]' % \
                    (self.narenas, self.nbins, len(self.runs), self.magrack_size)

class arena_chunk:

    def __init__(self, addr = 0, arena = 0):

        self.addr = addr
        self.arena = arena

    def __str__(self):

        if self.arena != 0:
            return '[unmask_jemalloc] [chunk %#x] [arena %#x]' % (self.addr, self.arena)
        else:
            return '[unmask_jemalloc] [chunk %#x] [orphan]' % (self.addr)

class arena_run:

    def __init__(self, start = 0, end = 0, size = 0, bin = 0, \
        region_size = 0, reg0_offset = 0, total_regions = 0, \
        free_regions = 0, regions = []):

        self.start = start
        self.end = end
        self.size = size
        self.bin = bin
        self.region_size = region_size
        self.reg0_offset = reg0_offset
        self.total_regions = total_regions
        self.free_regions = free_regions
        self.regions = regions
        self.regs_mask = ''

    def __str__(self):

        return '[unmask_jemalloc] [run %#x] [size %05d] [bin %#x] [region size %04d] ' \
               '[total regions %03d] [free regions %03d]' % \
                (self.start, self.size, self.bin, \
                 self.region_size, self.total_regions, self.free_regions)

class arena_bin:

    def __init__(self, addr, index, runcur):

        self.addr = addr
        self.index = index
        self.run = runcur

    def __str__(self):

        return '[unmask_jemalloc] [bin %02d (%#x)] [size class %04d] [runcur %#x]' % \
            (self.index, self.addr, self.run.region_size, self.run.start)

class region:

    def __init__(self, index = 0, addr = 0, is_free = 1):

        self.index = index
        self.addr = addr
        self.is_free = is_free
        self.content_preview = ''

    def __str__(self):

        str = '[unmask_jemalloc] [region %03d]' % (self.index)

        if self.is_free == 1:
            str += ' [free]'
        elif self.is_free == 0:
            str += ' [used]'

        if self.content_preview != '':
            str += ' [%#x] [%s]' % (self.addr, self.content_preview)
        else:
            str += ' [%#x]' % (self.addr)

        return str

class arena:

    def __init__(self, addr = 0, index = 0, bins = []):

        self.addr = addr
        self.index = index
        self.bins = bins

    def __str__(self):

        return '[unmask_jemalloc] [arena %02d (%#x)] [bins %02d]' % \
            (self.index, self.addr, len(self.bins))

# unit testing
if __name__ == '__main__':
    print('[unmask_jemalloc] unit testing not implemented yet')
    sys.exit(0)

# EOF


text:
<?php
namespace SynergyDataGrid\Grid;
use Zend\Json\Encoder;
/**
 * DatePicker class for DatePicker plugin integration in jQgrid
 *
 * @author Pele Odiase
 * @see http://docs.jquery.com/UI/Datepicker
 * @package mvcgrid
 */
class DatePicker extends Property
{
    /**
     * Javascript function name to attach DatePicker to fields
     *
     * @var string
     */
    protected $_functionName;

    /**
     * JqGrid instance
     *
     * @var string
     */
    protected $_grid;

    /**
     * Default date format for DatePicker control
     * @see http://docs.jquery.com/UI/Datepicker/formatDate
     * @const string
     */
    const DATE_DEFAULTFORMAT = 'MM d, yy';

    /**
     * Default time format for DatetimePicker control
     * @see http://trentrichardson.com/examples/timepicker/
     * @const string
     */
    const TIME_DEFAULTFORMAT = 'hh:mm:ss';

    /**
     * Set up base DatePicker options
     *
     * @param \SynergyDataGrid\Grid\JqGrid $grid JqGrid instance
     * @param array $options array of options
     * @return void
     */
    public function __construct($grid, $options = array())
    {
        $this->setGrid($grid);
        $this->setFunctionName('dp_' . $this->getGrid()->getId());
        $this->setDateFormat(self::DATE_DEFAULTFORMAT);
        $this->setOptions($options);
    }

    /**
     * Get DatePicker javascript function name
     *
     * @return string
     */
    public function getFunctionName()
    {
        return $this->_functionName;
    }

    /**
     * Set DatePicker javascript function name
     * @param string $functionName DatePicker javaqscript function name
     *
     * @return \SynergyDataGrid\DatePicker
     */
    public function setFunctionName($functionName)
    {
        $this->_functionName = $functionName;
        return $this;
    }

    /**
     * Get JqGrid instance
     *
     * @return \SynergyDataGrid\Grid\JqGrid
     */
    public function getGrid()
    {
        return $this->_grid;
    }

    /**
     * Set JqGrid instance
     * @param \SynergyDataGrid\Grid\JqGrid $grid JqGrid instance
     *
     * @return \SynergyDataGrid\DatePicker
     */
    public function setGrid($grid)
    {
        $this->_grid = $grid;
        return $this;
    }

    /**
     * Get jQuery selectors for all dates and dateimes in grid
     *
     * @return array
     */
    protected function _getAllDatesInGrid()
    {
        $grid = $this->getGrid();
        $columns = $grid->getColumns();
        $allDatesInGrid = "";
        $allDatetimesInGrid = "";
        $allDatesInForm = "'";
        $allDatetimesInForm = "'";
        foreach ($columns as $column) {
            if ($column->getDbColumnType() == 'date') {
                $allDatesInGrid .= "'#'+id+'_". $column->getName() . ",'+";
                $allDatesInForm .= "#". $column->getName() . ", ";
            } else if ($column->getDbColumnType() == 'datetime') {
                $allDatetimesInGrid .= "'#'+id+'_". $column->getName() . ",'+";
                $allDatetimesInForm .= "#". $column->getName() . ", ";
            }
        }
        if ($allDatesInGrid) {
            $allDatesInGrid = substr($allDatesInGrid, 0, strlen($allDatesInGrid) - 3) . "'";
            $allDatesInForm = substr($allDatesInForm, 0, strlen($allDatesInForm) - 2) . "'";
        } else {
            $allDatesInGrid = "";
            $allDatesInForm = "";
        }
        if ($allDatetimesInGrid) {
            $this->setTimeFormat(self::TIME_DEFAULTFORMAT);
            $allDatetimesInGrid = substr($allDatetimesInGrid, 0, strlen($allDatetimesInGrid) - 3) . "'";
            $allDatetimesInForm = substr($allDatetimesInForm, 0, strlen($allDatetimesInForm) - 2) . "'";
        } else {
            $allDatetimesInGrid = "";
            $allDatetimesInForm = "";
        }
        return array($allDatesInGrid, $allDatetimesInGrid, $allDatesInForm, $allDatetimesInForm);
    }

    /**
     * Prepare javascript code for binding DatePicker and DatetimePicker to grid fields
     *
     * @return array
     */
    public function prepareDatepicker()
    {
        $datePicker = array();
        list($allDatesInGrid, $allDatetimesInGrid, $allDatesInForm, $allDatetimesInForm) = $this->_getAllDatesInGrid();
        $datePickerFunctionName = $this->getFunctionName();
        $id = $this->getGrid()->getId();
        $datePicker[] =
        "
            function $datePickerFunctionName(id) {
        ";

        if ($allDatesInGrid) {
            $datePicker[] =
                sprintf('
                    if (typeof id != "object") {
                        jQuery(%s, "#%s").datepicker(%s)
                        if (jQuery(%s).is(":focus")) {
                            jQuery(%s).datepicker("show");
                        }
                    }
                    ',
                    $allDatesInGrid,
                    $id,
                    Encoder::encode($this->getOptions(), false, array('enableJsonExprFinder' => true)),
                    $allDatesInGrid,
                    $allDatesInGrid
                    );
            $datePicker[] =
                sprintf('jQuery(%s).datepicker(%s)
                    if (jQuery(%s).is(":focus")) {
                        jQuery(%s).datepicker("show");
                    }
                    ',
                    $allDatesInForm,
                    Encoder::encode($this->getOptions(), false, array('enableJsonExprFinder' => true)),
                    $allDatesInForm,
                    $allDatesInForm
                    );
        }
        if ($allDatetimesInGrid) {
            $datePicker[] =
                sprintf('
                    if (typeof id != "object") {
                        jQuery(%s, "#%s").datetimepicker(%s)
                        if (jQuery(%s).is(":focus")) {
                            jQuery(%s).datetimepicker("show");
                        }
                    }
                    ',
                    $allDatetimesInGrid,
                    $id,
                    Encoder::encode($this->getOptions(), false, array('enableJsonExprFinder' => true)),
                    $allDatetimesInGrid,
                    $allDatetimesInGrid
                    );
            $datePicker[] =
                sprintf('jQuery(%s).datetimepicker(%s)
                    if (jQuery(%s).is(":focus")) {
                        jQuery(%s).datetimepicker("show");
                    }
                    ',
                    $allDatetimesInForm,
                    Encoder::encode($this->getOptions(), false, array('enableJsonExprFinder' => true)),
                    $allDatetimesInForm,
                    $allDatetimesInForm
                    );
        }
        $datePicker[] =
        "
            }
        ";
        return $datePicker;
    }

}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Logical Agents · Notes

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

          Notes

Class notes for Nate Harada

      Home
      About
      Blog

          EECS492

          EECS598

          EECS584

          EECS545

          EECS586

          EECS583

© 2015. All rights reserved.

Logical Agents

  30 Sep 2014

Finish up constraints

Forward Checking

We can reduce our search by forward checking - whenever a variable X is assigned we examine each unassigned Y and delete Y that doesn't fit constraints. Forward checking is good, but we don't actually look ahead to all of our constraints; FC is almost a greedy search.

If we maintain arc consistency, we'll be more stringent and search space is even smaller.

Backjumping

The way we knew in the 4queen problem in notes on where to restart is because we knew where to backjump. To do this we'll create a conflict set containing the past conflicts.

Logic

We want to be able to reason about the world in a way that lets us derive new facts about the world without full knowledge. In the logical framework we'll have a knowledge base, and we want to augment and query it somehow. As an example of logic, we'll introduce wumpus world:

An agent runs through the maze, avoiding the wumpus and pits, while looking for gold. Additionally, the agent can shoot the wumpus (but only has one arrow).

In this world the agent can perceive things in adjacent squares to objects. World is discrete, static, single-agent, sequential, partially observable (arrow and wumpus states are not given by world). We'll cover more next week.

Related Posts

            Classic Optimization
            11 Nov 2015

            Pin Paper
            14 Oct 2015

            Paper Reviews 1 and 2
            12 Oct 2015


text:
package key

import (
	"errors"
	"fmt"
	"reflect"
	"sort"

	"github.com/goulash/errs"
	"github.com/goulash/twikutil"
)

// Error types {{{

var (
	ErrCatch        = errors.New("hidden: should only be used with TyperFunc")
	ErrKeyExists    = errors.New("key already exists in map")
	ErrMissingValue = errors.New("default value required")
	ErrNotTyper     = errors.New("type checker is invalid")
)

type RequiredError struct {
	Name string
}

func (e RequiredError) Error() string { return fmt.Sprintf("%s: required but unset", e.Name) }

type ImplementsError struct {
	Name  string
	Got   reflect.Type
	Wants string
}

func (e ImplementsError) Error() string {
	return fmt.Sprintf("%s: value (type %s) does not implement %s", e.Got, e.Wants)
}

type TypeError struct {
	Name  string
	Got   reflect.Type
	Wants string
}

func NewTypeError(name string, got interface{}, wants interface{}) *TypeError {
	err := &TypeError{Name: name}
	switch t := got.(type) {
	case reflect.Type:
		err.Got = t
	default:
		err.Got = reflect.TypeOf(t)
	}
	switch w := wants.(type) {
	case reflect.Type:
		err.Wants = w.String()
	case string:
		err.Wants = w
	default:
		err.Wants = reflect.TypeOf(wants).String()
	}
	return err
}

func (e TypeError) Error() string {
	return fmt.Sprintf("%s: value (type %v) is not of type %s", e.Name, e.Got, e.Wants)
}

// }}}

// Mode type {{{

type Mode int

const (
	Reserved Mode = 0
	Read     Mode = 1
	Write    Mode = 2
	Required Mode = 4

	ReadWrite Mode = Read | Write
)

// }}}

// KeyMap {{{

type KeyMap map[string]*Key

func NewKeyMap() KeyMap { return make(KeyMap) }

func (km KeyMap) KeyNames() []string {
	ns := make([]string, 0, len(km))
	for k := range km {
		ns = append(ns, k)
	}
	sort.Strings(ns)
	return ns
}

func (km KeyMap) Create(name string, typer, def interface{}, m Mode, desc string) (*Key, error) {
	if km[name] != nil {
		return nil, ErrKeyExists
	}
	k, err := New(name, typer, def, m, desc)
	if err != nil {
		return nil, err
	}
	km[name] = k
	return k, nil
}

func (km KeyMap) CreateAuto(name string, def interface{}, m Mode, desc string) (*Key, error) {
	if km[name] != nil {
		return nil, ErrKeyExists
	}
	k, err := NewAuto(name, def, m, desc)
	if err != nil {
		return nil, err
	}
	km[name] = k
	return k, nil
}

func (km KeyMap) Keys() Keys {
	ks := make(Keys, 0, len(km))
	for _, v := range km {
		ks = append(ks, v)
	}
	sort.Sort(ks)
	return ks
}

func (km KeyMap) Acquire(e *twikutil.Executer, h errs.Handler) error {
	return km.Keys().Acquire(e, h)
}

func (km KeyMap) Apply(e *twikutil.Executer) error {
	return km.Keys().Apply(e)
}

func (km KeyMap) ApplyOrNil(e *twikutil.Executer) error {
	return km.Keys().ApplyOrNil(e)
}

func (km KeyMap) Clobber(e *twikutil.Executer) error {
	return km.Keys().Clobber(e)
}

// }}}

// Keys {{{

type Keys []*Key

func (ks Keys) Len() int           { return len(ks) }
func (ks Keys) Less(i, j int) bool { return ks[i].name < ks[j].name }
func (ks Keys) Swap(i, j int)      { ks[i], ks[j] = ks[j], ks[i] }

func (ks Keys) Acquire(e *twikutil.Executer, h errs.Handler) error {
	for _, k := range ks {
		err := k.Acquire(e)
		if err = h(err); err != nil {
			return err
		}
	}
	return nil
}

func (ks Keys) Apply(e *twikutil.Executer) error {
	for _, k := range ks {
		err := k.Apply(e)
		if err != nil {
			return err
		}
	}
	return nil
}

// ApplyOrNil applies all keys, and keys that are read-only are
// still set to nil.
func (ks Keys) ApplyOrNil(e *twikutil.Executer) error {
	for _, k := range ks {
		err := k.ApplyOrNil(e)
		if err != nil {
			return err
		}
	}
	return nil
}

func (ks Keys) Clobber(e *twikutil.Executer) error {
	for _, k := range ks {
		err := k.Clobber(e)
		if err != nil {
			return err
		}
	}
	return nil
}

// }}}

type Key struct {
	name  string
	desc  string
	mode  Mode
	typer interface{}
	val   interface{}
}

// Must panics if err is not nil and returns the key otherwise.
func Must(k *Key, err error) *Key {
	if err != nil {
		panic(err)
	}
	return k
}

func New(name string, typer, def interface{}, m Mode, desc string) (*Key, error) {
	if !IsTyper(typer) {
		return nil, ErrNotTyper
	}
	k := &Key{
		name:  name,
		desc:  desc,
		mode:  m,
		typer: typer,
	}
	return k, k.Set(def)
}

func NewAuto(name string, def interface{}, m Mode, desc string) (*Key, error) {
	if def == nil {
		return nil, ErrMissingValue
	}
	return &Key{
		name:  name,
		desc:  desc,
		mode:  m,
		typer: reflect.TypeOf(def),
		val:   def,
	}, nil
}

func (k Key) Empty() bool     { return k.val == nil }
func (k Key) Type() string    { return k.typer.(fmt.Stringer).String() }
func (k Key) Name() string    { return k.name }
func (k Key) Desc() string    { return k.desc }
func (k Key) Mode() Mode      { return k.mode }
func (k *Key) SetMode(m Mode) { k.mode = m }

// Get returns a value that is either nil or guaranteed to conform to the defined type.
func (k Key) Get() interface{} { return k.val }

func (k Key) GetOr(def interface{}) interface{} {
	if k.val == nil {
		return def
	}
	return k.val
}

func (k *Key) Set(v interface{}) (err error) {
	// If v is nil, then we're effectively deleting the stored value.
	if v != nil {
		v, err = Check(k.name, k.typer, v)
		if err != nil {
			return err
		}
	}

	k.val = v
	return nil
}

func (k *Key) Acquire(e *twikutil.Executer) error {
	if k.mode&Read == 0 {
		// This key does not want to be updated.
		return nil
	}

	if !e.Has(k.name) {
		if k.mode&Required != 0 {
			return &RequiredError{k.name}
		}
		return nil
	}

	v, _ := e.Get(k.name)
	return k.Set(v)
}

func (k *Key) Apply(e *twikutil.Executer) error {
	if k.mode&Write == 0 {
		return nil
	}
	if !e.Has(k.name) {
		return e.Set(k.name, k.val)
	}
	return nil
}

func (k *Key) ApplyOrNil(e *twikutil.Executer) error {
	if k.mode&Write == 0 {
		return e.Set(k.name, nil)
	}
	if !e.Has(k.name) {
		return e.Set(k.name, k.val)
	}
	return nil
}

func (k *Key) Clobber(e *twikutil.Executer) error {
	if k.mode&Write == 0 {
		return nil
	}

	return e.Set(k.name, k.val)
}

func Check(name string, typer interface{}, v interface{}) (interface{}, error) {
	chkType := func(t reflect.Type) error {
		vt := reflect.TypeOf(v)
		if t.Kind() == reflect.Interface {
			if !vt.Implements(t) {
				return ImplementsError{name, vt, t.String()}
			}
		} else if vt != t {
			return NewTypeError(name, vt, t)
		}
		return nil
	}

	switch t := typer.(type) {
	case reflect.Type:
		return v, chkType(t)
	case Typer:
		v, err := t.Coerce(v)
		if err != nil {
			switch et := err.(type) {
			case *TypeError:
				if et.Name == "" {
					et.Name = name
				}
				return v, et
			case *ImplementsError:
				if et.Name == "" {
					et.Name = name
				}
				return v, et
			}
		}
		return v, err
	default:
		return nil, ErrNotTyper
	}

}


text:
package org.arquillian.extension.governor.github.impl;

import org.arquillian.extension.governor.api.GovernorClient;
import org.arquillian.extension.governor.github.api.Github;
import org.arquillian.extension.governor.github.configuration.GithubGovernorConfiguration;
import org.eclipse.egit.github.core.Comment;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.IssueService;
import org.jboss.arquillian.core.spi.Validate;
import org.jboss.arquillian.test.spi.TestResult;
import org.jboss.arquillian.test.spi.event.suite.After;
import org.jboss.arquillian.test.spi.execution.ExecutionDecision;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * @author Alex Soto
 *
 */
public class GithubGovernorClient implements GovernorClient<Github, GithubGovernorStrategy>
{
    private static final Logger logger = Logger.getLogger(GithubGovernorClient.class.getName());

    private GitHubClient githubClient;
    private GithubGovernorConfiguration githubGovernorConfiguration;
    private IssueService issueService;
    private GithubGovernorStrategy githubGovernorStrategy;

    public GithubGovernorClient(GitHubClient gitHubClient, GithubGovernorConfiguration githubGovernorConfiguration) {
        this.initializeGithubClient(gitHubClient);
        this.setConfiguration(githubGovernorConfiguration);
    }

    @Override
    public ExecutionDecision resolve(Github annotation)
    {
        Validate.notNull(githubClient, "Github REST client must be specified.");
        Validate.notNull(githubGovernorStrategy, "Governor strategy must be specified. Have you already called setGovernorStrategy()?");

        final String githubIssueKey = annotation.value();

        if (githubIssueKey == null || githubIssueKey.length() == 0)
        {
            return ExecutionDecision.execute();
        }

        final Issue githubIssue = getIssue(githubIssueKey);

        // when there is some error while we are getting the issue, we execute that test
        if (githubIssue == null)
        {
            logger.warning(String.format("Github Issue %s couldn't be retrieved from congigured repository.", githubIssueKey));
            return ExecutionDecision.execute();
        }

        return githubGovernorStrategy.annotation(annotation).issue(githubIssue).resolve();
    }

    @Override
    public void close(String issueId)
    {
        Validate.notNull(githubClient, "Github REST client must be specified.");

        Comment comment = null;
        try
        {
            Issue issue = getIssue(issueId);
            issue.setState(IssueService.STATE_CLOSED);
            comment = this.issueService.createComment(this.githubGovernorConfiguration.getRepositoryUser(), this.githubGovernorConfiguration.getRepository(), issueId, getClosingMessage());
            this.issueService.editIssue(this.githubGovernorConfiguration.getRepositoryUser(), this.githubGovernorConfiguration.getRepository(), issue);
        } catch (Exception e)
        {
            if (comment != null) {
                deleteComment(comment);
            }
            // error while getting Issue to close, doing nothing
            //WARN log
        }
    }

    private void deleteComment(Comment comment) {
        try {
            this.issueService.deleteComment(this.githubGovernorConfiguration.getRepositoryUser(), this.githubGovernorConfiguration.getRepository(), comment.getId());
        } catch (IOException e1) {
        }
    }

    @Override
    public void setGovernorStrategy(GithubGovernorStrategy strategy)
    {
        Validate.notNull(strategy, "Github Governor strategy must be specified.");
        this.githubGovernorStrategy = strategy;
    }

    public GitHubClient getGithubClient()
    {
        return githubClient;
    }

    private void setConfiguration(GithubGovernorConfiguration githubGovernorConfiguration)
    {
        Validate.notNull(githubGovernorConfiguration, "Github Governor configuration must be specified.");
        this.githubGovernorConfiguration = githubGovernorConfiguration;
    }

    private void initializeGithubClient(final GitHubClient gitHubClient)
    {
        Validate.notNull(gitHubClient, "Github client must be specified.");
        this.githubClient = gitHubClient;

        this.issueService = new IssueService(this.githubClient);
    }

    private Issue getIssue(String issueNumber) {
        try
        {
            return this.issueService.getIssue(this.githubGovernorConfiguration.getRepositoryUser(), this.githubGovernorConfiguration.getRepository(), issueNumber);
        } catch (Exception e)
        {
            logger.warning(String.format("An exception has occured while getting issue %s. Exception: %s", issueNumber, e.getMessage()));
            return null;
        }
    }
    private String getClosingMessage()
    {
        Validate.notNull(githubGovernorConfiguration, "Github Governor configuration must be set.");

        return String.format(githubGovernorConfiguration.getClosingMessage(), githubGovernorConfiguration.getUsername());
    }

}