text:
package org.kaazing.gateway.transport.http.connector.specification.rfc7231;

import java.io.IOException;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionInitializer;
import org.hamcrest.core.AllOf;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.Rule;
import org.junit.Test;
import org.junit.internal.matchers.ThrowableMessageMatcher;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.kaazing.gateway.transport.LoggingUtils;
import org.kaazing.gateway.transport.http.HttpConnectSession;
import org.kaazing.gateway.transport.http.HttpConnectorRule;
import org.kaazing.gateway.transport.http.HttpMethod;
import org.kaazing.gateway.transport.test.Expectations;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;
import org.kaazing.mina.core.session.IoSessionEx;
import org.kaazing.test.util.ITUtil;

/**
 * Test to validate behavior as specified in RFC 7231 section 4:
 * Request Methods.
 */
public class RedirectionIT {
    private final HttpConnectorRule connector = new HttpConnectorRule();
    private final K3poRule k3po = new K3poRule().setScriptRoot("org/kaazing/specification/http/rfc7231/redirection");

    public JUnitRuleMockery context = new JUnitRuleMockery() {
        {
            setThreadingPolicy(new Synchroniser());
        }
    };

    private TestRule contextRule = ITUtil.toTestRule(context);

    @Rule
    public TestRule chain = RuleChain.outerRule(contextRule).around(connector).around(k3po);

    private final IoHandler handler = context.mock(IoHandler.class);

    private static class ConnectSessionInitializer implements IoSessionInitializer<ConnectFuture> {
        @Override
        public void initializeSession(IoSession session, ConnectFuture future) {
            HttpConnectSession connectSession = (HttpConnectSession) session;
            connectSession.setMethod(HttpMethod.GET);
        }
    }

    @Test
    @Specification({"absolute.location/response"})
    public void absoluteLocationHeader() throws Exception {
        context.checking(new Expectations() {{
            allowing(handler).sessionOpened(with(any(IoSessionEx.class)));
            allowing(handler).sessionCreated(with(any(IoSessionEx.class)));
            allowing(handler).sessionClosed(with(any(IoSessionEx.class)));
            atMost(1).of(handler).exceptionCaught(with(any(IoSessionEx.class)),
                    with(AllOf.allOf(any(IOException.class),ThrowableMessageMatcher.hasMessage(equal(LoggingUtils.EARLY_TERMINATION_OF_IOSESSION_MESSAGE)))));
        }});
        connector.getConnectOptions().put("http.maximum.redirects", 1);
        connector.connect("http://localhost:8000/resource#fragment", handler, new ConnectSessionInitializer());
        k3po.finish();
    }

    @Test
    @Specification({"change.fragment/response"})
    public void changeFragment() throws Exception {
        context.checking(new Expectations() {{
            allowing(handler).sessionOpened(with(any(IoSessionEx.class)));
            allowing(handler).sessionCreated(with(any(IoSessionEx.class)));
            allowing(handler).sessionClosed(with(any(IoSessionEx.class)));
            atMost(1).of(handler).exceptionCaught(with(any(IoSessionEx.class)),
                    with(AllOf.allOf(any(IOException.class),ThrowableMessageMatcher.hasMessage(equal(LoggingUtils.EARLY_TERMINATION_OF_IOSESSION_MESSAGE)))));
        }});
        connector.getConnectOptions().put("http.maximum.redirects", 1);
        connector.connect("http://localhost:8000/resource#fragment", handler, new ConnectSessionInitializer());
        k3po.finish();
    }

    @Test
    @Specification({"relative.location/response"})
    public void relativeLocation() throws Exception {
        context.checking(new Expectations() {{
            allowing(handler).sessionOpened(with(any(IoSessionEx.class)));
            allowing(handler).sessionCreated(with(any(IoSessionEx.class)));
            allowing(handler).sessionClosed(with(any(IoSessionEx.class)));
            atMost(1).of(handler).exceptionCaught(with(any(IoSessionEx.class)),
                    with(AllOf.allOf(any(IOException.class),ThrowableMessageMatcher.hasMessage(equal(LoggingUtils.EARLY_TERMINATION_OF_IOSESSION_MESSAGE)))));
        }});
        connector.getConnectOptions().put("http.maximum.redirects", 1);
        connector.connect("http://localhost:8000/resource#fragment", handler, new ConnectSessionInitializer());
        k3po.finish();
    }
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8" />

		<title>Mask Demo</title>

		<link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css" />

Mask Demo

			<form id="form">

					<input type="text" name="product" id="product" data-required />

					 Product

					<input type="text" name="price" id="price" placeholder="R$ 0,00" data-pattern="^(?:R\$)?\s*(\d+)(?:[,\.](\d)(\d)?)?\d*$" data-mask="R$ ${1},${2:`0`}${3:`0`}" />

					Price

					<select name="category" id="category" data-required>
						<option value="">Select a category</option>

						<option value="1">Gategory 1</option>

						<option value="2">Gategory 2</option>

						<option value="3">Gategory 3</option>
					</select>

					 Category

					<button type="submit" class="btn btn-primary">Send</button>

					<button type="reset" class="btn">Reset</button>

			</form>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BrockAllen.MembershipReboot
{
    public abstract class UserAccount
    {
        public virtual Guid ID { get; protected internal set; }

        [StringLength(50)]
        [Required]
        public virtual string Tenant { get; protected internal set; }

        // If email address is being used as the username then this property
        // should adhere to maximim length constraint for valid email addresses.
        // See Dominic Sayers answer at SO: http://stackoverflow.com/a/574698/99240
        [StringLength(254)]
        [Required]
        public virtual string Username { get; protected internal set; }

        public virtual DateTime Created { get; protected internal set; }
        public virtual DateTime LastUpdated { get; protected internal set; }
        public virtual bool IsAccountApproved { get { return AccountApproved.HasValue; } }
        public virtual DateTime? AccountApproved { get; protected internal set; }
        public virtual bool IsAccountRejected { get { return AccountRejected.HasValue; } }
        public virtual DateTime? AccountRejected { get; protected internal set; }
        public virtual bool IsAccountClosed { get; protected internal set; }
        public virtual DateTime? AccountClosed { get; protected internal set; }

        /// <summary>
        /// Returns true when the account is locked
        /// </summary>
        /// <remarks>
        /// An locked account will not be able to sign in
        /// </remarks>
        public virtual bool IsLoginAllowed { get; protected internal set; }
        public virtual DateTime? LastLogin { get; protected internal set; }
        public virtual DateTime? LastFailedLogin { get; protected internal set; }
        public virtual int FailedLoginCount { get; protected internal set; }

        public virtual DateTime? PasswordChanged { get; protected internal set; }
        public virtual bool RequiresPasswordReset { get; protected internal set; }

        // Maximum length of a valid email address is 254 characters.
        // See Dominic Sayers answer at SO: http://stackoverflow.com/a/574698/99240
        [EmailAddress]
        [StringLength(254)]
        public virtual string Email { get; protected internal set; }
        public virtual bool IsAccountVerified { get; protected internal set; }

        public virtual DateTime? LastFailedPasswordReset { get; protected internal set; }
        public virtual int FailedPasswordResetCount { get; protected internal set; }

        [StringLength(100)]
        public virtual string MobileCode { get; protected internal set; }
        public virtual DateTime? MobileCodeSent { get; protected internal set; }
        [StringLength(20)]
        public virtual string MobilePhoneNumber { get; protected internal set; }
        public virtual DateTime? MobilePhoneNumberChanged { get; protected internal set; }

        public virtual TwoFactorAuthMode AccountTwoFactorAuthMode { get; protected internal set; }
        public virtual TwoFactorAuthMode CurrentTwoFactorAuthStatus { get; protected internal set; }

        [StringLength(100)]
        public virtual string VerificationKey { get; protected internal set; }
        public virtual VerificationKeyPurpose? VerificationPurpose { get; protected internal set; }
        public virtual DateTime? VerificationKeySent { get; protected internal set; }
        [StringLength(100)]
        public virtual string VerificationStorage { get; protected internal set; }

        [StringLength(200)]
        public virtual string HashedPassword { get; protected internal set; }

        public abstract IEnumerable<UserClaim> Claims { get; }
        protected internal abstract void AddClaim(UserClaim item);
        protected internal abstract void RemoveClaim(UserClaim item);

        public abstract IEnumerable<LinkedAccount> LinkedAccounts { get; }
        protected internal abstract void AddLinkedAccount(LinkedAccount item);
        protected internal abstract void RemoveLinkedAccount(LinkedAccount item);

        public abstract IEnumerable<LinkedAccountClaim> LinkedAccountClaims { get; }
        protected internal abstract void AddLinkedAccountClaim(LinkedAccountClaim item);
        protected internal abstract void RemoveLinkedAccountClaim(LinkedAccountClaim item);

        public abstract IEnumerable<UserCertificate> Certificates { get; }
        protected internal abstract void AddCertificate(UserCertificate item);
        protected internal abstract void RemoveCertificate(UserCertificate item);

        public abstract IEnumerable<TwoFactorAuthToken> TwoFactorAuthTokens { get; }
        protected internal abstract void AddTwoFactorAuthToken(TwoFactorAuthToken item);
        protected internal abstract void RemoveTwoFactorAuthToken(TwoFactorAuthToken item);

        public abstract IEnumerable<PasswordResetSecret> PasswordResetSecrets { get; }
        protected internal abstract void AddPasswordResetSecret(PasswordResetSecret item);
        protected internal abstract void RemovePasswordResetSecret(PasswordResetSecret item);
    }
}


text:
import numpy as np
import pandas as pd
from sklearn import linear_model

from dowhy.causal_estimator import CausalEstimate
from dowhy.causal_estimators.propensity_score_estimator import PropensityScoreEstimator

class PropensityScoreWeightingEstimator(PropensityScoreEstimator):
    """ Estimate effect of treatment by weighing the data by
    inverse probability of occurrence.

    Straightforward application of the back-door criterion.

    For a list of standard args and kwargs, see documentation for
    :class:`~dowhy.causal_estimator.CausalEstimator`.

    Supports additional parameters as listed below.

    """
    def __init__(
        self,
        *args,
        min_ps_score=0.05,
        max_ps_score=0.95,
        weighting_scheme='ips_weight',
        propensity_score_model=None,
        recalculate_propensity_score=True,
        propensity_score_column="propensity_score",
        **kwargs):
        """
        :param min_ps_score: Lower bound used to clip the propensity score.
            Default=0.05
        :param max_ps_score: Upper bound used to clip the propensity score.
            Default=0.95
        :param weighting_scheme: Weighting method to use. Can be inverse
            propensity score ("ips_weight", default), stabilized IPS score
            ("ips_stabilized_weight"), or normalized IPS score
            ("ips_normalized_weight").
        :param propensity_score_model: The model used to compute propensity
            score. Can be any classification model that supports fit() and
            predict_proba() methods. If None, use LogisticRegression model as
            the default. Default=None
        :param recalculate_propensity_score: If true, force the estimator to
            estimate the propensity score. To use pre-computed propensity
            scores, set this value to false. Default=True
        :param propensity_score_column: Column name that stores the
            propensity score. Default='propensity_score'
        """
        # Required to ensure that self.method_params contains all the information
        # to create an object of this class
        args_dict = kwargs
        args_dict.update({
            'min_ps_score': min_ps_score,
            'max_ps_score': max_ps_score,
            'weighting_scheme': weighting_scheme
            })
        super().__init__(
            *args,
            propensity_score_model=propensity_score_model,
            recalculate_propensity_score=recalculate_propensity_score,
            propensity_score_column=propensity_score_column,
            **args_dict)

        self.logger.info("INFO: Using Propensity Score Weighting Estimator")
        self.symbolic_estimator = self.construct_symbolic_estimator(
            self._target_estimand)
        self.logger.info(self.symbolic_estimator)
        # Setting method specific parameters
        self.weighting_scheme = weighting_scheme
        self.min_ps_score = min_ps_score
        self.max_ps_score = max_ps_score

    def _estimate_effect(self):
        if self.recalculate_propensity_score is True:
            if self.propensity_score_model is None:
                self.propensity_score_model = linear_model.LogisticRegression()
            self.propensity_score_model.fit(self._observed_common_causes, self._treatment)
            self._data[self.propensity_score_column] = self.propensity_score_model.predict_proba(self._observed_common_causes)[:, 1]
        else:
            # check if user provides the propensity score column
            if self.propensity_score_column not in self._data.columns:
                raise ValueError(f"Propensity score column {self.propensity_score_column} does not exist. Please specify the column name that has your pre-computed propensity score.")
            else:
                self.logger.info(f"INFO: Using pre-computed propensity score in column {self.propensity_score_column}")

        # trim propensity score weights
        self._data[self.propensity_score_column] = np.minimum(self.max_ps_score, self._data[self.propensity_score_column])
        self._data[self.propensity_score_column] = np.maximum(self.min_ps_score, self._data[self.propensity_score_column])

        # ips ==> (isTreated(y)/ps(y)) + ((1-isTreated(y))/(1-ps(y)))
        # nips ==> ips / (sum of ips over all units)
        # icps ==> ps(y)/(1-ps(y)) / (sum of (ps(y)/(1-ps(y))) over all control units)
        # itps ==> ps(y)/(1-ps(y)) / (sum of (ps(y)/(1-ps(y))) over all treatment units)
        ipst_sum = sum(self._data[self._treatment_name[0]] / self._data[self.propensity_score_column])
        ipsc_sum = sum((1 - self._data[self._treatment_name[0]]) / (1-self._data[self.propensity_score_column]))
        num_units = len(self._data[self._treatment_name[0]])
        num_treatment_units = sum(self._data[self._treatment_name[0]])
        num_control_units = num_units - num_treatment_units

        # Vanilla IPS estimator
        self._data['ips_weight'] = (
            self._data[self._treatment_name[0]] / self._data[self.propensity_score_column] +
            (1 - self._data[self._treatment_name[0]]) / (1 - self._data[self.propensity_score_column])
        )
        self._data['tips_weight'] = (
            self._data[self._treatment_name[0]] +
            (1 - self._data[self._treatment_name[0]]) * self._data[self.propensity_score_column] / (1 - self._data[self.propensity_score_column])
        )
        self._data['cips_weight'] = (
            self._data[self._treatment_name[0]] * (1 - self._data[self.propensity_score_column]) / self._data[self.propensity_score_column] + (1 - self._data[self._treatment_name[0]])
        )

        # The Hajek estimator (or the self-normalized estimator)
        self._data['ips_normalized_weight'] = (
            self._data[self._treatment_name[0]] / self._data[self.propensity_score_column] / ipst_sum +
            (1 - self._data[self._treatment_name[0]]) / (1 - self._data[self.propensity_score_column]) / ipsc_sum
        )
        ipst_for_att_sum = sum(self._data[self._treatment_name[0]])
        ipsc_for_att_sum = sum((1-self._data[self._treatment_name[0]])/(1 - self._data[self.propensity_score_column])*self._data[self.propensity_score_column])
        self._data['tips_normalized_weight'] = (
            self._data[self._treatment_name[0]] / ipst_for_att_sum +
            (1 - self._data[self._treatment_name[0]]) * self._data[self.propensity_score_column] / (1 - self._data[self.propensity_score_column]) / ipsc_for_att_sum
        )
        ipst_for_atc_sum = sum(self._data[self._treatment_name[0]] / self._data[self.propensity_score_column] * (1-self._data[self.propensity_score_column]))
        ipsc_for_atc_sum = sum((1 - self._data[self._treatment_name[0]]))
        self._data['cips_normalized_weight'] = (
            self._data[self._treatment_name[0]] * (1 - self._data[self.propensity_score_column]) / self._data[self.propensity_score_column] / ipst_for_atc_sum +
            (1 - self._data[self._treatment_name[0]])/ipsc_for_atc_sum
        )

        # Stabilized weights (from Robins, Hernan, Brumback (2000))
        # Paper: Marginal Structural Models and Causal Inference in Epidemiology
        p_treatment = sum(self._data[self._treatment_name[0]])/num_units
        self._data['ips_stabilized_weight'] = (
            self._data[self._treatment_name[0]] / self._data[self.propensity_score_column] * p_treatment +
            (1 - self._data[self._treatment_name[0]]) / (1 - self._data[self.propensity_score_column]) * (1 - p_treatment)
        )
        self._data['tips_stabilized_weight'] = (
            self._data[self._treatment_name[0]] * p_treatment +
            (1 - self._data[self._treatment_name[0]]) * self._data[self.propensity_score_column] / (1 - self._data[self.propensity_score_column]) * (1 - p_treatment)
        )
        self._data['cips_stabilized_weight'] = (
            self._data[self._treatment_name[0]] * (1 - self._data[self.propensity_score_column]) / self._data[self.propensity_score_column] * p_treatment +
            (1 - self._data[self._treatment_name[0]]) * (1-p_treatment)
        )

        if self._target_units == "ate":
            weighting_scheme_name = self.weighting_scheme
        elif self._target_units == "att":
            weighting_scheme_name = "t" + self.weighting_scheme
        elif self._target_units == "atc":
            weighting_scheme_name = "c" + self.weighting_scheme
        else:
            raise ValueError("Target units string value not supported")

        # Calculating the effect
        self._data['d_y'] = (
            self._data[weighting_scheme_name] *
            self._data[self._treatment_name[0]] *
            self._data[self._outcome_name]
        )
        self._data['dbar_y'] = (
            self._data[weighting_scheme_name] *
            (1 - self._data[self._treatment_name[0]]) *
            self._data[self._outcome_name]
        )
        sum_dy_weights = np.sum(
            self._data[self._treatment_name[0]] * self._data[weighting_scheme_name])
        sum_dbary_weights = np.sum(
            (1 - self._data[self._treatment_name[0]]) * self._data[weighting_scheme_name])
        # Subtracting the weighted means
        est = self._data['d_y'].sum() / sum_dy_weights - self._data['dbar_y'].sum() / sum_dbary_weights

        # TODO - how can we add additional information into the returned estimate?
        estimate = CausalEstimate(estimate=est,
                                  control_value=self._control_value,
                                  treatment_value=self._treatment_value,
                                  target_estimand=self._target_estimand,
                                  realized_estimand_expr=self.symbolic_estimator,
                                  propensity_scores=self._data[self.propensity_score_column])
        return estimate

    def construct_symbolic_estimator(self, estimand):
        expr = "b: " + ",".join(estimand.outcome_variable) + "~"
        # TODO -- fix: we are actually conditioning on positive treatment (d=1)
        var_list = estimand.treatment_variable + estimand.get_backdoor_variables()
        expr += "+".join(var_list)
        return expr


text:
package com.orionplatform.reflection.enumeration;

import java.lang.reflect.InvocationTargetException;
import com.orionplatform.core.abstraction.OrionService;
import com.orionplatform.reflection.enumeration.tasks.GetEnumerationDefinitionsTask;
import com.orionplatform.reflection.enumeration.tasks.GetEnumerationNameTask;
import com.orionplatform.reflection.enumeration.tasks.GetEnumerationValueTask;
import com.orionplatform.reflection.enumeration.tasks.InstantiateEnumerationTask;

public class ReflectionEnumerationService extends OrionService
{
    @SuppressWarnings({"rawtypes"})
    public static synchronized Class<Enum> instantiateEnumeration(String enumerationPath) throws ClassNotFoundException
    {
        return InstantiateEnumerationTask.run(enumerationPath);
    }

    @SuppressWarnings("rawtypes")
    public static synchronized Enum[] getEnumerationDefinitions(Class<Enum> enumerationClass)
    {
        return GetEnumerationDefinitionsTask.run(enumerationClass);
    }

    @SuppressWarnings("rawtypes")
    public static synchronized String getEnumerationName(Enum enumerationDefinition)
    {
        return GetEnumerationNameTask.run(enumerationDefinition);
    }

    @SuppressWarnings({"rawtypes"})
    public static synchronized String getEnumerationValue(Class<Enum> enumerationClass, String enumerationName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        return GetEnumerationValueTask.run(enumerationClass, enumerationName);
    }
}


text:
<?php

namespace Elcodi\Component\Comment\Event;

use Elcodi\Component\Comment\Event\Abstracts\AbstractCommentEvent;

/**
 * Class CommentPreRemoveEvent.
 */
final class CommentPreRemoveEvent extends AbstractCommentEvent
{
}


text:
@interface DMDummyJob : NSObject <DMJob>

@end


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

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

class BlobOutputStream extends OutputStream {
    private ClientBlob blob_;
    private long offset_;

    BlobOutputStream(ClientBlob blob, long offset) {
        blob_ = blob;
        offset_ = offset;

        /*
            offset_=1 while blob_.binaryString_.length - blob_.dataOffset_ = 0
            for a empty Blob hence check for offset_-1
         */
        if ((offset_-1) > (blob_.binaryString_.length - blob_.dataOffset_)) {
            throw new IndexOutOfBoundsException();
        }
    }

    public void write(int b) throws IOException
    {
        byte ba[] = {(byte )b};
        writeX(ba, 0, 1);
    }

    public void write(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
                ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        writeX(b, off, len);
    }

    private void writeX(byte b[], int off, int len)
    {
        byte[] newbuf = new byte[(int) offset_ - 1 + len + blob_.dataOffset_];
        System.arraycopy(blob_.binaryString_, 0,
                         newbuf, 0, (int )offset_ - 1 + blob_.dataOffset_);
        blob_.binaryString_ = newbuf;
        for (int i = 0; i < len; i++, offset_++) {
            blob_.binaryString_[(int )offset_ + blob_.dataOffset_ - 1]
                = b[off + i];
        }
        blob_.binaryStream_
            = new ByteArrayInputStream(blob_.binaryString_);
        blob_.setSqlLength(blob_.binaryString_.length - blob_.dataOffset_);
    }
}


text:
(function(undefined){
    // (0, eval)('this') is a robust way of getting a reference to the global object
    // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
    var window = this || (0, eval)('this'),
        document = window['document'],
        navigator = window['navigator'],
        jQuery = window["jQuery"],
        JSON = window["JSON"];


text:
var express = require('express');
var moment = require('moment');
var rest = require('./rest');
var token = require('./token');
var tagsIndexer = require('./tagsIndexer');
var redis = require("./redis");

module.exports = (function () {
    'use strict';
    var app = express.Router();

    app.get('/user/:id', getUser);

    function unpackUser(obj) {
        obj.password_hash = "";
        delete obj.lastloggedin;
        delete obj.created;
        obj.contact = "";
        return obj;
    }

    function unpackUserPrivileged(obj) { // only called when user = self
        obj.password_hash = "";
        obj.lastloggedin = moment(obj.lastloggedin);
        obj.created = moment(obj.created);
        return obj;
    }

    function getUser(req, res, next) {
        var id = req.params.id;
        rest.getDetail("user", id, res, next, unpackUser);
    }

    // ===== LOGIN

    app.post('/login', login);
    app.post('/signup', signup);

    function login(req, res, next) {
        var name = req.body.name;
        var hash = req.body.hash;
        var p = redis.client.zscoreAsync(["userids", name]).then(function (id) {
            if (id == null) {
                console.log("INFO: user " + name + " bad login - doesn't exist");
                res.json({status: "fail", msg: "wrong pass"});
                return p.cancel();
            } else {
                return redis.client.hgetallAsync("user:" + id);
            }
        }).then(function (userData) {
            if (userData.password_hash == hash) {
                console.log("INFO: user " + name + " successfully logged in");
                token.createToken(userData.id, function(token) {
                    var userObj = unpackUserPrivileged(userData);
                    userObj.token = token;
                    res.json({status: "success", obj: userObj});
                });
            } else {
                console.log("INFO: user " + name + " bad login");
                res.json({status: "fail", msg: "wrong pass"});
                //return p.cancel();
            }
        }).error(function (err) {
            console.log("ERROR: while trying to login user:" + name);
            console.log(err);
            res.json({status: "fail", msg: "There was a server problem, please try again in an hour or so."});
        }).cancellable();
    }

    function makeUser(name, hash) {
        var d = new Date();
        return {
            name: name,
            password_hash: hash,
            avatar: "",
            created: d.toISOString(),
            lastloggedin: d.toISOString(),
            contact: ""
        };
    }

    function signup(req, res, next) {
        var name = req.body.name;
        var pwhash = req.body.hash;
        var p = redis.client.sismemberAsync(["usernames", name]).then(function (userExists) {
            if (userExists) {
                console.log("INFO: user " + name + " attempted to sign up, but exists");
                res.json({status: "fail", msg: "name is already taken"});
                return p.cancel();
            } else {
                return redis.client.incrAsync("userID");
            }
        }).then(function (nextID) {
            var obj = makeUser(name, pwhash);
            obj.id = nextID;
            var hash = "user:" + nextID;
            redis.client.multi([
                ["hmset", hash, obj],
                ["zadd", "userids", nextID, name],
                ["sadd", "usernames", name],
                ["sadd", "users", nextID],
                ["set", hash + ":rep:events", 0],
                ["set", hash + ":rep:hushtags", 0],
                ["set", hash + ":rep:locations", 0]
            ]).execAsync().then(function () {
                console.log("INFO: user " + name + " signed up");
                token.createToken(nextID, function(token) {
                    var userObj = unpackUserPrivileged(obj);
                    userObj.token = token;
                    res.json({status: "success", obj: userObj});
                    tagsIndexer.updateObjectTags();
                });
            }).error(function (err) {
                console.log("error while inserting data for " + hash);
                console.dir(obj);
                console.log(err);
            });
        }).error(function (err) {
            console.log("ERROR: while user " + name + " attempt to sign up");
            res.json({status: "fail", msg: "There was a server problem, please try again in an hour or so."});
        }).cancellable();

    }

    return app;
})();


text:
using System;
using System.Collections.Generic;
using Augustus.Domain.Objects;
using Augustus.Web.Portal.Interfaces;

namespace Augustus.Web.Portal.ViewModels
{
    public class AccountWriteViewModel : ISharedLayoutViewModel, IWriteModelView<Account>, IAccountDropDown
    {
        public Breadcrumb Breadcrumb { get; set; }
        public string Title { get; set; }
        public FormButtons FormButtons { get; set; }
        public Account Account { get; set; }
        public DropDownViewModel<Account> AccountDropDown { get; set; }
        public Account DomainModel
        {
            get { return Account; }
            set { Account = value; }
        }
    }
}


text:
CBrowserWebView::
CBrowserWebView(QWidget *parent) :
 QFrame(parent)
{
  QVBoxLayout *layout = new QVBoxLayout(this);

  view_ = new QWebView;

  layout->addWidget(view_);
}

void
CBrowserWebView::
setFilename(const std::string &filename)
{
  setWindowTitle(filename.c_str());

  //QUrl url = QUrl::fromLocalFile(filename.c_str());

  //url.setScheme("file");
  //url.setPath(filename.c_str());

  //QUrl url(QString("file://%1").arg(filename.c_str()));

//std::cerr << url.toString().toStdString() << std::endl;
  //view_->setUrl(url);

  //view_->load(url);

  CFile file(filename);

  QString str;

  std::string line;

  while (file.readLine(line)) {
    str += line.c_str();
    str += "\n";
  }

  view_->setHtml(str);
}


text:
Index

News List

	<button type="button" id="truncateNews" class="btn btn-danger btn-flat btn-sm fadeDisplay">すべての記事と画像を削除</button>

	<button type="button" class="btn btn-fab btn-raised btn-material-red"></button>


text:
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".header-collapse">
				{{ trans('partials.toggle_navigation') }}

			</button>

category

				Product

 new product

 list product

				Image

 list image

				@if(Auth::guest())

{{ trans('partials.register') }}

{{ trans('partials.login') }}

				@else

{{ trans('partials.my_profile') }}

{{ trans('partials.logout') }}

				@endif


text:
class ObjModel
{
private:
    GLuint program;
    GLuint u_MvpMatrixHandle;
    GLuint u_MvMatrixHandle;
    GLuint u_LightPosHandle;
    GLuint u_EyePosHandle;

    GLuint a_PositionHandle;
    GLuint a_NormalHandle;
    GLuint a_ColorHandle;

    GLuint vbo;
    GLuint stride;
    GLuint numOfVertices;

public:
    ObjModel (const string &pathToObj, const string &pathToMtl);
    ~ObjModel ();
    void draw (mat4 mvp, mat4 mv, vec3 lighPos, vec3 eyePos);
    void drawDepth();
};

#endif // OBJMODEL_H


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Wetter. Gesellsch. Ges. Naturk. 2: 102 (1810)

#### Original name
Uredo gentianae F. Strauss, 1810

### Remarks
null


text:
package org.globus.mds.gsi.jndi;

import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;

import javax.security.auth.callback.CallbackHandler;  // from JAAS

import java.util.Map;

import org.globus.mds.gsi.common.GSIMechanism;

import org.ietf.jgss.GSSException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SaslClientWrapper implements SaslClient {

    private com.sun.security.sasl.preview.SaslClient client;

    public SaslClientWrapper(com.sun.security.sasl.preview.SaslClient client) {
        this.client = client;
    }

    public boolean hasInitialResponse() {
        return this.client.hasInitialResponse();
    }

    public byte[] evaluateChallenge(byte[] challengeData) throws SaslException {
        try {
            return this.client.evaluateChallenge(challengeData);
        } catch (com.sun.security.sasl.preview.SaslException e) {
            throw new SaslException("", e);
        }
    }

    public byte[] wrap(byte[] outgoing,
                       int offset,
                       int len)
        throws SaslException {
        try {
            return this.client.wrap(outgoing, offset, len);
        } catch (com.sun.security.sasl.preview.SaslException e) {
            throw new SaslException("", e);
        }
    }

    public byte[] unwrap(byte[] incoming,
                         int offset,
                         int len)
        throws SaslException {
        try {
            return this.client.unwrap(incoming, offset, len);
        } catch (com.sun.security.sasl.preview.SaslException e) {
            throw new SaslException("", e);
        }
    }

    public void dispose()
        throws SaslException {
        try {
            this.client.dispose();
        } catch (com.sun.security.sasl.preview.SaslException e) {
            throw new SaslException("", e);
        }
    }

    public Object getNegotiatedProperty(String propName) {
        try {
            return client.getNegotiatedProperty(propName);
        } catch (com.sun.security.sasl.preview.SaslException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public boolean isComplete() {
        return this.client.isComplete();
    }

    public String getMechanismName() {
        return this.client.getMechanismName();
    }

}


text:
{% extends "base.html" %}{% load i18n %}

{% block title %}
{% trans "Add a scheduled post" %}
{% endblock %}

{% block extra_css %}

{% endblock %}

{% block content %}

    {% trans "View scheduled posts" %}

    <form method="post" action="." class="pure-form pure-form-stacked" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="{% trans "Schedule" %}" class="pure-button pure-button-primary" >
    </form>

{% endblock %}

{% block extra_js %}

{% endblock %}


text:
<?php
define("IN_STORYBOT", 1);
require_once("config/config.php");
if(!is_admin(mod_id())) {
	die("Administrator rights required!");
}
	$content = file_get_contents("config/defaultsettings.php");
	$content = str_replace("DBUSER", $config['dbuser'], $content);
	$content = str_replace("DBHOST", $config['dbhost'], $content);
	$content = str_replace("DBPASS", $config['dbpass'], $content);
	$content = str_replace("DBNAME", $config['dbname'], $content);
	$content = str_replace("USERNAME", $_POST['snuser'], $content);
	$content = str_replace("PASSWORD", $_POST['snpass'], $content);
	if($_POST['mod'] == "true") {
		$content = str_replace("MODERATION", "true", $content);
	} else {
		$content = str_replace("MODERATION", "false", $content);
	}
	if($_POST['enable'] == "true") {
		$content = str_replace("ENABLED", "true", $content);
	} else {
		$content = str_replace("ENABLED", "false", $content);
	}
	if($_POST['pic'] == "true") {
		$content = str_replace("PICTURES", "true", $content);
	} else {
		$content = str_replace("PICTURES", "false", $content);
	}
	if($_POST['vid'] == "true") {
		$content = str_replace("VIDEOS", "true", $content);
	} else {
		$content = str_replace("VIDEOS", "false", $content);
	}
	if($_POST['time'] > 10) {
		$time = 10;
	} elseif($_POST['time'] < 1) {
		$time = 1;
	} else {
		$time = $_POST['time'];
	}
	$content = str_replace("TIME", $time, $content);
	file_put_contents("config/settings.php", $content);
	header("Location: admin.php");
?>


text:
var _ = require("lodash");
var tokenize = require("../tokenize");
var levels = require("../levels");
var passive = require("./data/passive");

var re = new RegExp('\\b(am|are|were|being|is|been|was|be)\\b\\s*([\\w]+ed|' + _.pluck(passive.list, "value").join('|') + ')\\b', 'gi');

module.exports = tokenize.check(
    tokenize.re(re),
    tokenize.define(function (text, token, prev) {
        var replacement = _.find(passive.list, { value: token.match[2] });
        if (replacement) replacement = [{ value: replacement.replace }];

        return {
            message: '"<%= value %>" may be passive voice',
            replacements: replacement
        };
    })
);
module.exports.level = levels.WARNING;


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

    <groupId>io.github.twktheainur</groupId>
    <artifactId>llodumls</artifactId>
    <version>0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>llodumls</name>
    <url>http://maven.apache.org</url>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>io.github.twktheainur.LlodUmls</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

    </build>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.6</version>
        </dependency>
         <dependency>
           <groupId>org.apache.logging.log4j</groupId>
           <artifactId>log4j-core</artifactId>
           <version>[2.16.0,)</version>
         </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.jena</groupId>
            <artifactId>jena-arq</artifactId>
            <version>3.1.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>jcl-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.jena</groupId>
            <artifactId>jena-tdb</artifactId>
            <version>3.1.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>jcl-over-slf4j</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
         <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>[8.0.16,)</version>
         </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.getalp</groupId>
            <artifactId>org.getalp.lexsema-similarity-core</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.getalp.lexsema-similarity-core-1.0-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.getalp</groupId>
            <artifactId>org.getalp.lexsema-similarity-api</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.getalp.lexsema-similarity-api-1.0-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.getalp</groupId>
            <artifactId>org.getalp.lexsema-util</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.getalp.lexsema-util-1.0-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.getalp</groupId>
            <artifactId>org.getalp.lexsema-ontolex-api</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.getalp.lexsema-ontolex-api-1.0-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.getalp</groupId>
            <artifactId>org.getalp.lexsema-ontolex-core</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.getalp.lexsema-ontolex-core-1.0-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.getalp</groupId>
            <artifactId>org.getalp.lexsema-translation-core</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.getalp.lexsema-translation-core-1.0-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.getalp</groupId>
            <artifactId>org.getalp.lexsema-ml</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/org.getalp.lexsema-ml-1.0-SNAPSHOT.jar</systemPath>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>
         <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-compress</artifactId>
           <version>[1.21,)</version>
         </dependency>
    </dependencies>
</project>


text:
__Note: this package is out of date and not usable with newer versions of Julia.__

[![Build Status](https://travis-ci.org/JuliaML/MLPlots.jl.svg?branch=master)](https://travis-ci.org/JuliaML/MLPlots.jl)

Common plotting recipes for statistics and machine learning.

This package uses [RecipesBase](https://github.com/JuliaPlots/RecipesBase.jl) to provide mappings from types defined in
statistics and machine learning packages to generic descriptions of visualization attributes and data.  These recipes can then be used in
conjunction with [Plots.jl](https://github.com/tbreloff/Plots.jl) to provide flexible statistical and machine learning
visualizations which are independent of both the platform and graphical library.

Many recipes are conditionally included and are loaded on the relevant `using` call of the library.
For example `using ROCAnalysis, MLPlots` will load plotting recipes for roc curves defined in ROCAnalysis.  Recipes include:

- [OnlineAI](#onlineai): Neural nets and spike trains
- [ROCAnalysis](#rocanalysis): ROC/AUC curves

#### Status: This package is currently on hiatus until further notice.  Collaboration is welcomed and encouraged!

## OnlineAI

Neural nets with [OnlineAI.jl](https://github.com/tbreloff/OnlineAI.jl).  Show the current state of a neural net:

```julia
using OnlineAI, MLPlots
net = buildClassificationNet(3, 1, [15,10,5])
plot(net)
```

![onlineai1](test/refimg/onlineai1.png)

For spiking neuron models, a spike (or raster) plot is useful to see firing times among neurons:

```julia
n = 20
spikes = SpikeTrains(n, title = "Spike Trains", color = :darkblue)
for t=1:100, i=1:n
    if rand() < 0.1
        push!(spikes, i, t)
    end
end
spikes.plt
```
![onlineai](test/refimg/onlineai2.png)

## ROCAnalysis

[ROCAnalysis.jl](https://github.com/davidavdav/ROCAnalysis.jl)

```julia
using ROCAnalysis, MLPlots
curve = ROCAnalysis.roc(2+2randn(1000), -2+2randn(100000))
plot(curve)
```

![rocanalysis](test/refimg/rocanalysis.png)


text:
[![Build Status](https://travis-ci.org/raiseandfall/slugify-files.svg)](https://travis-ci.org/raiseandfall/slugify-files) [![Downloads](https://img.shields.io/npm/dt/slugify-files.svg)](https://www.npmjs.com/package/slugify-files)

> A simple CL tool to slugify files (kebab-case)

> ```"this Filename NEEDS cleaning.png" -> "this-filename-needs-cleaning.png"```

## [CHANGELOG](./CHANGELOG.md)

## INSTALL

```shell
$ npm install slugify-files
```

## USAGE

```javascript
var slugify = require('slugify-files');

slugify(['*.png'], function (err, sluggedFiles) {
  sluggedFiles.forEach(function(file, idx)) {
    console.log(file.old, 'renamed to', file.new);
  }
});
```

## CLI

```shell
$ npm install --global slugify-files
```

```
$ slugify --help

  Usage
    $ slugify <source>

  Example
    $ slugify '*.tmp'

  <source> can contain globs if quoted
```

## API

```javascript
slugify(source, function(err, sluggedFiles){});
```
- ```source```: glob
- ```err```: error
- ```sluggedFiles```: Array of slugged files objects. Each has two keys: ```old``` and ```new```

## CONTRIBUTE

```shell
$ git clone git@github.com:raiseandfall/slugify-files.git && cd slugify-files
```

```shell
$ npm i
```

Run
```shell
$ npm run dev
```

Run tests
```shell
$ npm run test
```

## LICENSE
MIT


text:
// source:

package nl.uva.vlet.metadata;

/**
 * A Meta Resource is a File stored inside a File.
 * For example a File stored inside a Zip Archive.
 * This means a translation has to be done to either
 * read or write the file to the Storage Location.
 * Or a Meta Resource provides an extra layer on top of an
 * existing resource.
 * For example a media type or an encryption layer.
 * Multiple (meta) resource can be stacked ontop (or inside) of each other.
 *
 * @author Piter T. de Boer
 *
 */
public interface VMetaResource
{
    /** Whether this file is a composite meta file */
    boolean isComposite();

    /**
     * Return the Composite Meta File type of this file.
     * Use isComposite() to check wether this (Meta) file is composite.
     */
    VCompositeMetaResource getComposite();

}


text:
extern crate error_lib as lib;
use lib::Error;

trait From<T> {}

impl From<&str> for Box<dyn Error> {}
impl<E> From<E> for Box<dyn Error> where E: Error {}

fn main() {}


text:
NewAgentDialog::NewAgentDialog(const QStringList &importAgents, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewAgentDialog)
{
    ui->setupUi(this);

    existingAgents = importAgents;

    QStringList agentTypes;
    agentTypes << "Person" << "Group" << "Organization";
    ui->agentTypeBox->addItems(agentTypes);
    ui->agentTypeBox->setCurrentText("Person");
}

QString NewAgentDialog::getAgentCode()
{
    return agentCode;
}

QString NewAgentDialog::getFullName()
{
    return fullName;
}

QString NewAgentDialog::getAgentURI()
{
    return agentURI;
}

QString NewAgentDialog::getContactURL()
{
    return contactURL;
}

QString NewAgentDialog::getMorphbankID()
{
    return morphbankID;
}

QString NewAgentDialog::getAgentType()
{
    return agentType;
}

NewAgentDialog::~NewAgentDialog()
{
    delete ui;
}

void NewAgentDialog::on_addButton_clicked()
{
    ui->agentCode->setStyleSheet("border: 2px solid white");
    ui->fullName->setStyleSheet("border: 2px solid white");
    ui->agentURI->setStyleSheet("border: 2px solid white");
    ui->contactURL->setStyleSheet("border: 2px solid white");

    ui->agentCode->setText(ui->agentCode->text().trimmed());
    ui->fullName->setText(ui->fullName->text().trimmed());
    ui->agentURI->setText(ui->agentURI->text().trimmed());
    ui->contactURL->setText(ui->contactURL->text().trimmed());
    ui->morphbankID->setText(ui->morphbankID->text().trimmed());

    agentCode = ui->agentCode->text();
    fullName = ui->fullName->text();
    agentURI = ui->agentURI->text();
    contactURL = ui->contactURL->text();
    morphbankID = ui->morphbankID->text();
    agentType = ui->agentTypeBox->currentText();

    // highlight empty boxes red if they're required information
    bool redo = false;
    if (agentCode.isEmpty())
    {
        ui->agentCode->setStyleSheet("border: 2px solid red");
        redo = true;
    }
    else if (agentCode.contains(" "))
    {
        ui->agentCode->setStyleSheet("border: 2px solid red");
        redo = true;
        ui->agentCode->setText(agentCode.remove(" "));
        QMessageBox msgBox;
        msgBox.setText("The agent code cannot contain spaces. The spaces\n"
                       "have been automatically removed. Please review the\n"
                       "altered agent code before proceeding.");
        msgBox.exec();
        return;
    }
    if (fullName.isEmpty())
    {
        ui->fullName->setStyleSheet("border: 2px solid red");
        redo = true;
    }
    if (agentURI.isEmpty())
    {
        ui->agentURI->setStyleSheet("border: 2px solid red");
        redo = true;
    }
    else if (!agentURI.contains("http://"))
    {
        if (agentURI.contains("orcid.org/"))
            agentURI.prepend("http://");
        else
            agentURI.prepend("http://orcid.org/");
    }
    if (contactURL.isEmpty())
    {
        ui->contactURL->setStyleSheet("border: 2px solid red");
        redo = true;
    }

    if (existingAgents.contains(agentCode, Qt::CaseInsensitive))
    {
        ui->agentCode->setStyleSheet("border: 2px solid red");
        QMessageBox msgBox;
        msgBox.setText("That unique agent code already exists.\n"
                       "Please create a different one.");
        msgBox.exec();
        return;
    }
    if (redo)
        return;

    accept();
}

void NewAgentDialog::on_cancelButton_clicked()
{
    reject();
}

void NewAgentDialog::on_fullName_textEdited(const QString &arg1)
{
    // Assign agent code based on their full name, i.e. last name + first name initial
    QStringList splitName = arg1.split(" ");
    if (splitName.length() <= 1)
        return;
    else if (splitName.last().isEmpty())
        return;
    else
    {
        if (splitName.first().length() < 1)
            return;
        QString suggestedAgentCode = splitName.last() + splitName.first().at(0);
        if (existingAgents.contains(suggestedAgentCode, Qt::CaseInsensitive))
        {
            if (splitName.first().length() < 2)
                return;
            suggestedAgentCode += splitName.first().at(1);
            if (existingAgents.contains(suggestedAgentCode, Qt::CaseInsensitive))
            {
                return;
            }
        }

        ui->agentCode->setText(suggestedAgentCode.toLower());
    }
}


text:
package org.dice.solrenhancements.tokenfilters;

/**
 * Created by simon.hughes on 4/7/16.
 */

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.shingle.ShingleFilter;
import org.apache.lucene.analysis.tokenattributes.*;
import org.apache.lucene.util.AttributeSource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Based on http://sujitpal.blogspot.com/2011/07/lucene-token-concatenating-tokenfilter_30.html
 *
 * Concatenate all tokens, separated by a provided character,
 * defaulting to a single space. It always produces exactly one token, and it's designed to be the
 * last token filter in an analysis chain.
 */
public class ConcatenateTokenFilter extends TokenFilter {

  /*
  For a very different approach that could accept synonyms or anything except position gaps (e.g.
  not stopwords),
  consider using o.a.l.analysis.TokenStreamToAutomaton
  with o.a.l.util.automaton.SpecialOperations.getFiniteStrings().
  For gaps (stopwords), we could perhaps index a special token at those gaps and then have the
  tagger deal with them -- also doable.
   */

    private final String separator;
    private LinkedList<List<String>> words;
    private LinkedList<String> phrases;

    private boolean concat = false;
    private AttributeSource.State current;

    private final CharTermAttribute termAttr = addAttribute(CharTermAttribute.class);
    private final OffsetAttribute offsetAttr = addAttribute(OffsetAttribute.class);
    private final PositionIncrementAttribute posIncrAttr = addAttribute(PositionIncrementAttribute.class);
    private final PositionLengthAttribute posLenAttr = addAttribute(PositionLengthAttribute.class);
    private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);

    private StringBuilder buf = new StringBuilder(128);

    public ConcatenateTokenFilter(TokenStream input, String separator) {
        super(input);
        this.separator = separator;
        this.words = new LinkedList<List<String>>();
        this.phrases = new LinkedList<String>();
    }

    @Override
    public void reset() throws IOException {
        super.reset();
        this.words = new LinkedList<List<String>>();
        this.phrases = new LinkedList<String>();
    }

    @Override
    public final boolean incrementToken() throws IOException {
        //TODO make sure this works with synonyms and stop words

        int i = 0;
        while (input.incrementToken()) {
            String term = new String(termAttr.buffer(), 0, termAttr.length());
            List<String> word = posIncrAttr.getPositionIncrement() > 0 ? new ArrayList<String>() : words.removeLast();
            word.add(term);
            words.add(word);
            i++;
        }
        // now write out as a single token
        if (! concat) {
            makePhrases(words, phrases, 0);
            concat = true;
        }
        while (phrases.size() > 0) {

            String phrase = phrases.removeFirst();
            restoreState(current);
            clearAttributes();

            termAttr.setEmpty();
            termAttr.append(phrase);
            termAttr.setLength(phrase.length());

            //posIncrAttr.setPositionIncrement(0);
            typeAtt.setType(ShingleFilter.DEFAULT_TOKEN_TYPE);//"shingle"

            current = captureState();
            return true;
        }

        concat = false;
        return false;
    }

    private void makePhrases(List<List<String>> words, List<String> phrases, int currPos) {
        if (currPos == words.size()) {
            return;
        }
        if (phrases.size() == 0) {
            phrases.addAll(words.get(currPos));
        } else {
            List<String> newPhrases = new ArrayList<String>();
            for (String phrase : phrases) {
                for (String word : words.get(currPos)) {
                    newPhrases.add(StringUtils.join(new String[] {phrase, word}, " "));
                }
            }
            phrases.clear();
            phrases.addAll(newPhrases);
        }
        makePhrases(words, phrases, currPos + 1);
    }

    @Override
    public void end() throws IOException {
        //we already called input.end() in incrementToken
    }
}


text:
using namespace idaas;

class InstructionsHandler
{
private:
	char buffer[256];
	size_t registerMappingSize;
	IdaRegister::type *registerMapping;
	void prepareMapping();
	void setRegisterMapping(const char *registerName, IdaRegister::type idaRegister);
	void fetchOperand(IdaOperand &_return, const op_t &input);
	IdaRegister::type mapRegister(int reg);
	int calculateOperandSize(const op_t &input);
	void setIndexRegister(IdaOperand &_return, const op_t &input);
public:
	InstructionsHandler(void);
	~InstructionsHandler(void);

	void fetch(IdaInstruction &_return, int32_t address);
};


text:
import React, { Component } from 'react';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

import logo from '../logo.svg';
import './style.css';
import ApolloClient from 'apollo-client';
import { ApolloProvider } from 'react-apollo';

import ProjectsPage from '../pages/ProjectsPage';
import FlowsPage from '../pages/FlowsPage';
import CombinationsList from '../pages/CombinationsList'
import CombinationReport from '../pages/CombinationReport'
import NotFound from '../pages/NotFound'

import {
  BrowserRouter,
  Link,
  Route,
  Switch,
} from 'react-router-dom';

const uri = process.env.REACT_APP_REFLOW_DEVELOPMENT?
  'http://localhost:3000/graphql': 'https://automation.yamsafer.com:5555/graphql';

const client = new ApolloClient({
  link: createHttpLink({
    uri,
  }),
  cache: new InMemoryCache(),
});

class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <BrowserRouter>

              <Link to="/" className="navbar-brand">

              </Link>

              <Switch>
                <Route exact path="/" component={ProjectsPage}/>
                <Route exact path="/project/:projectID" component={ProjectsPage}/>
                <Route exact path="/job/:jobID" component={FlowsPage}/>
                <Route path="/flow/:flowID" component={CombinationsList}/>
                <Route path="/combination/:combinationID" component={CombinationReport}/>
                <Route component={ NotFound }/>
              </Switch>

        </BrowserRouter>
      </ApolloProvider>
    );
  }
};

export default App


text:
<?php

namespace tourze\Base\Exception;

/**
 * 未知属性
 *
 * @package tourze\Base\Exception
 */
class UnknownPropertyException extends BaseException
{
}


text:
import os
import inspect

class Environment(object):
    """
    A class representing which environment the client library is using.
    Pass in one of the following values as the first argument to
    :class:`braintree.Configuration.configure() <braintree.configuration.Configuration>` ::

        braintree.Environment.Sandbox
        braintree.Environment.Production
    """

    def __init__(self, server, port, is_ssl, ssl_certificate):
        self.__server = server
        self.__port = port
        self.is_ssl = is_ssl
        self.ssl_certificate = ssl_certificate

    @property
    def port(self):
        return int(self.__port)

    @property
    def protocol(self):
        return self.__port == "443" and "https://" or "http://"

    @property
    def server(self):
        return self.__server

    @property
    def server_and_port(self):
        return self.__server + ":" + self.__port

    @staticmethod
    def braintree_root():
        return os.path.dirname(inspect.getfile(Environment))

Environment.Development = Environment("localhost", os.getenv("GATEWAY_PORT") or "3000", False, None)
Environment.Sandbox = Environment("sandbox.braintreegateway.com", "443", True, Environment.braintree_root() + "/ssl/sandbox_braintreegateway_com.ca.crt")
Environment.Production = Environment("www.braintreegateway.com", "443", True, Environment.braintree_root() + "/ssl/www_braintreegateway_com.ca.crt")


text:
define([
	"./BaseView"
], function (BaseView) {
	return Ember.ObjectController.extend({
		mainViewClass: BaseView,
		mainView: null,
		init: function () {
			this._super();

			// stuff here
			this.restartView();
		},
		restartView: function() {
			this.set("mainView", this.get("mainViewClass").create({
				controller: this.get("viewModel") || this
			}));
			return this.get("mainView");
		}
	});
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<TestPlan>
   <Test>12004/submit</Test>
    <TestStep id="submit">
        <ExpectedStatus>Success</ExpectedStatus>
        <RegisterTransaction>
            <XDSb/>
            <MetadataFile>single_doc.xml</MetadataFile>
        </RegisterTransaction>
    </TestStep>
    <TestStep id="resubmit_doc">
        <ExpectedStatus>Success</ExpectedStatus>
        <RegisterTransaction>
            <XDSb/>
            <NoAssignUids id="Document01"/>
            <MetadataFile>single_doc2.xml</MetadataFile>
            <UseId id="Document01" step="submit"
                section="AssignedUids" symbol="$doc_uid$"/>
        </RegisterTransaction>
    </TestStep>
    <TestStep id="resubmit_doc_diff_hash">
        <ExpectedStatus>Failure</ExpectedStatus>
        <ExpectedErrorMessage>XDSNonIdenticalHash</ExpectedErrorMessage>
        <RegisterTransaction>
            <XDSb/>
            <NoAssignUids id="Document01"/>
            <MetadataFile>single_doc3.xml</MetadataFile>
            <UseId id="Document01" step="submit"
                section="AssignedUids" symbol="$doc_uid$"/>
        </RegisterTransaction>
    </TestStep>
</TestPlan>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Orleans.Tests.SqlUtils;

namespace UnitTests.General
{
    internal class MySqlStorageForTesting : RelationalStorageForTesting
    {
        public MySqlStorageForTesting(string connectionString) : base(AdoNetInvariants.InvariantNameMySql, connectionString)
        {
        }

        public override string CancellationTestQuery { get { return "DO SLEEP(10); SELECT 1;"; } }

        public override string CreateStreamTestTable { get { return "CREATE TABLE StreamingTest(Id INT NOT NULL, StreamData LONGBLOB NOT NULL);"; } }

        public IEnumerable<string> SplitScript(string setupScript)
        {
            return setupScript.Replace("END$$", "END;")
                .Split(new[] {"DELIMITER $$", "DELIMITER ;"}, StringSplitOptions.RemoveEmptyEntries);
        }

        protected override string CreateDatabaseTemplate
        {
            get { return @"CREATE DATABASE `{0}`"; }
        }

        protected override string DropDatabaseTemplate
        {
            get { return @"DROP DATABASE `{0}`"; }
        }

        public override string DefaultConnectionString
        {
            get { return "Server=127.0.0.1;Database=sys; Uid=root;Pwd=root;"; }
        }

        protected override string[] SetupSqlScriptFileNames
        {
            get
            {
                return new[] {
                    "MySQL-Main.sql",
                    "MySQL-Clustering.sql",
                    "MySQL-Persistence.sql",
                    "MySQL-Reminders.sql"
                };
            }
        }

        protected override string ExistsDatabaseTemplate
        {
            get { return "SELECT COUNT(1) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{0}'"; }
        }

        protected override IEnumerable<string> ConvertToExecutableBatches(string setupScript, string databaseName)
        {
            var batches = setupScript.Replace("END$$", "END;").Split(new[] { "DELIMITER $$", "DELIMITER ;" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            batches.Add(CreateStreamTestTable);

            return batches;
        }
    }
}


text:
package org.perfcake.reporting.reporters.accumulators;

/**
 * Accumulates a maximal value over a set of the number of recently reported values.
 *
 * @author Martin Večeřa
 * @author Pavel Macík
 */
public class SlidingWindowMaxAccumulator extends AbstractSlidingWindowAccumulator {

   /**
    * Creates a new maximum accumulator with the sliding window of a given size.
    *
    * @param windowSize
    *       Size of the sliding window.
    */
   public SlidingWindowMaxAccumulator(final int windowSize) {
      super(windowSize);
   }

   @Override
   public synchronized Double getResult() {
      double max = Double.MIN_VALUE;
      synchronized (fifo) {
         for (final Object o : fifo) {
            max = Math.max(max, (Double) o);
         }
      }

      return fifo.size() == 0 ? Double.NaN : max;
   }
}


text:
// ======================================================================== //
// Copyright 2009-2013 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#ifndef __EMBREE_BACKEND_SCENE_FLAT_H__
#define __EMBREE_BACKEND_SCENE_FLAT_H__

#include "scene.h"
#include <embree2/rtcore.h>

namespace embree
{
  /*! Flat scene, no support for instancing, best render performance. */
  class BackendSceneFlat : public BackendScene
  {
  public:

    struct Primitive : public RefCount
    {
    public:
      Primitive (const Ref<Shape>& shape,
                 const Ref<Light>& light,
                 const Ref<Material>& material,
                 const light_mask_t illumMask,
                 const light_mask_t shadowMask)
        : shape(shape), light(light), material(material),
          illumMask(illumMask), shadowMask(shadowMask) {}

      __forceinline void postIntersect(const Ray& ray, DifferentialGeometry& dg) const
      {
        dg.material   = material.ptr;
        dg.light      = (AreaLight*) light.ptr;
        dg.illumMask  = illumMask;
        dg.shadowMask = shadowMask;
        shape->postIntersect(ray,dg);
      }

    public:
      Ref<Shape> shape;
      Ref<Light> light;
      Ref<Material> material;
      light_mask_t illumMask;  /*! which light masks we receive illum from */
      light_mask_t shadowMask; /*! which light masks we cast shadows to */
    };

    /*! API handle that manages user actions. */
    class Handle : public BackendScene::Handle {
      ALIGNED_CLASS;
    public:

      void setPrimitive(size_t slot, Ref<PrimitiveHandle> prim)
      {
        if (slot >= prims.size()) prims.resize(slot+1);
        Ref<Shape> shape = prim->getShapeInstance();
        Ref<Light> light = prim->getLightInstance();
        if (light) shape = light->shape();
        if (shape) shape = shape->transform(prim->transform);
        if (light) light = light->transform(prim->transform,prim->illumMask,prim->shadowMask);
        prims[slot] = new Primitive(shape,light,prim->getMaterialInstance(),prim->illumMask,prim->shadowMask);
      }

      void create()
      {
        RTCScene scene = rtcNewScene(RTC_SCENE_STATIC,RTC_INTERSECT1);
        for (size_t i=0; i<prims.size(); i++) {
          if (prims[i] && prims[i]->shape)
            prims[i]->shape->extract(scene,i);
        }
        rtcCommit(scene);

        /* create new scene */
        instance = new BackendSceneFlat(prims,scene);
      }

    public:
      std::vector<Ref<Primitive> > prims;
    };

    /*! Construction of scene. */
    BackendSceneFlat (const std::vector<Ref<Primitive> >& geometry, RTCScene scene)
      : BackendScene(scene), geometry(geometry)
    {
      for (size_t i=0; i<geometry.size(); i++) {
        const Ref<Primitive>& prim = geometry[i];
        if (prim && prim->light) add(prim->light);
      }
    }

    /*! Helper to call the post intersector of the shape instance,
     *  which will call the post intersector of the shape. */
    void postIntersect(const Ray& ray, DifferentialGeometry& dg) const {
      if (ray) geometry[ray.id0]->postIntersect(ray,dg);
    }

  private:
    std::vector<Ref<Primitive> > geometry;  //!< Geometry of the scene
  };
}

#endif


text:
using System.Collections.Generic;
using System.Reflection;
using AdaskoTheBeAsT.AutoMapper.SimpleInjector;

namespace AngularWebApiSample;

public partial class Startup
{
    public void ConfigureServicesMapping(IEnumerable<Assembly> assemblies)
    {
        _container.AddAutoMapper(assemblies);
    }
}


text:
class Shop::AddShopWizard < WizardModel

  def self.structure_wizard_handler_info
    { :name => "Add an E-commerce shop to your Site",
      :description => 'This wizard will add an e-commerce shop to your site complete with cart and checkout',
      :permit => "shop_config",
      :url => self.wizard_url
    }
  end

  attributes :shop_id => nil,
  :add_to_id=>nil,
  :add_to_subpage => 'shop',
  :add_to_existing => nil,
  :opts => ['cart','categories','dummy_products'],
  :add_processor => nil,
  :add_region => nil,
  :add_country => nil,
  :add_delivery => nil,
  :shipping_cost => 5.00,
  :add_dummy_products => true

  boolean_options :add_processor, :add_region, :add_delivery
  float_options :shipping_cost

  page_options :add_to_id

  validates_format_of :add_to_subpage, :with => /^[a-zA-Z0-9\-_]+$/, :message => 'is an invalid url', :allow_blank => true
  validates_presence_of :add_to_id

  validates_presence_of :shop_id

  def wizard_partial; '/shop/wizard/form'; end

  def validate
    if (self.add_to_existing.blank? && self.add_to_subpage.blank?) ||
       (!self.add_to_existing.blank? && self.add_to_node.node_type == 'R')
      self.errors.add(:add_to, "must have a subpage selected or add\n to existing must be checked")
    end
  end

  def shop
    @shop ||= Shop::ShopShop.find(self.shop_id) if self.shop_id
  end

  def set_defaults(params)
    self.shop_id = Shop::ShopShop.default_shop.id
  end

  def run_wizard
    base_node = SiteNode.find(self.add_to_id)

    if self.add_to_existing.blank?
      base_node = base_node.add_subpage(self.add_to_subpage)
    end

    base_node.push_subpage('cart') do |cart_page, cart_revision|
      base_node.push_subpage('checkout') do |checkout_page, checkout_revision|
        base_node.new_revision do |shop_revision|
          self.destroy_basic_paragraph(shop_revision)
          self.destroy_basic_paragraph(cart_revision)
          self.destroy_basic_paragraph(checkout_revision)

          shop_revision.push_paragraph('/shop/page','product_listing',
                                       { :detail_page_id => base_node.id,
                                         :cart_page_id => cart_page.id,
                                         :shop_shop_id => self.shop_id,
                                         :base_category_id => Shop::ShopCategory.get_root_category.id
                                       }) do |para|
            para.add_page_input(:input,:page_arg_0,:product_category_1)
            para.add_page_input(:detail,:page_arg_1,:product_url)
          end

          shop_revision.push_paragraph('/shop/page','product_detail',
                                       { :cart_page_id => cart_page.id,
                                         :list_page_id => base_node.id,
                                         :shop_shop_id => self.shop_id
                                       }) do |para|
            para.add_page_input(:category,:page_arg_0,:product_category_1)
            para.add_page_input(:input,:page_arg_1,:product_id)
          end

          cart_revision.push_paragraph('/shop/processor','full_cart',
                                       { :checkout_page_id => checkout_page.id
                                       })

          checkout_revision.push_paragraph('/shop/processor','checkout',
                                           { :cart_page_id => cart_page.id,
                                             :add_tags => 'ShopOrder'
                                           }) do |para|
            para.add_page_input(:input,:page_arg_0,:checkout_page)
          end

          if self.opts.include?('cart')
            shop_revision.push_paragraph('/shop/page','display_cart',
                                         { :full_cart_page_id => cart_page.id
                                         }, :zone => 3)
          end

          if self.opts.include?('categories')
            shop_revision.push_paragraph('/shop/page','category_listing',
                                         { :list_page_id => base_node.id,
                                           :base_category_id => Shop::ShopCategory.get_root_category.id
                                         }, :zone => 3) do |para|
              para.add_page_input(:input,:page_arg_0,:product_category_1)
            end
          end
        end
      end
    end

    mod_opts = Shop::AdminController.module_options
    if self.add_processor
      processor = Shop::ShopPaymentProcessor.new(
        :name => 'Test Processor',
        :currency => mod_opts.currency,
        :payment_type => 'Credit Card',
        :options => { :force_failure => "no" },
        :active => true)
      processor.processor_handler = 'shop/test_payment_processor'
      processor.save
    end

    if self.add_region
      # Add automatic subregions for US
      region = Shop::ShopRegion.new(:name => self.add_country,:tax => 0.0,
                                    :has_subregions => self.add_country == 'United States',
                                   :subregion_type => 'state')
      region.countries.build(:country => self.add_country)
      region.save
    end

    if self.add_delivery
      region ||= Shop::ShopRegion.find(:first)
      if region
        carrier = Shop::ShopCarrier.new(:name => "Standard Carrier")
        carrier.carrier_processor = "shop/standard_carrier_processor"
        carrier.save

        category = Shop::ShopShippingCategory.create(
                                  :name => "Standard Shipping",
                                  :shop_carrier_id => carrier.id,
                                  :shop_region_id => region.id,
                                  :active => 1,
                                  :options => { :classes_shipping_cost => "item",
                                                :items => [ "" ],
                                                :item_prices => [ self.shipping_cost.to_s ],
                                                :items_shipping_cost => "item",
                                                :shipping_calculation => "items" })
      end
    end

    if self.opts.include?('dummy_products') && self.shop.shop_products.count == 0
      (0..2).each do |idx|
        self.create_dummy_product
      end
    end
  end

  def shop_folder
    @shop_folder ||= DomainFile.find(:first,:conditions => "name = 'Shop' and parent_id = #{DomainFile.root_folder.id}") || DomainFile.create(:name => 'Shop', :parent_id => DomainFile.root_folder.id, :file_type => 'fld')
  end

  def create_dummy_products
    return if @products
    @products = []
    (1..3).each do |idx|
      product = DomainFile.find(:first, :conditions => {:parent_id => self.shop_folder.id, :file_type => 'img', :name => "no#{idx}_product.png"})
      if product
        @products << product
      else
        File.open("#{RAILS_ROOT}/vendor/modules/shop/public/images/no#{idx}_product.png", "r") do |fd|
          @products << DomainFile.create(:filename => fd, :parent_id => self.shop_folder.id, :process_immediately => true)
        end
      end
    end
  end

  def dummy_product_image
    @shop_product_idx ||= -1
    @shop_product_idx+=1
    @shop_product_idx = @shop_product_idx % 3
    @products[@shop_product_idx]
  end

  def create_dummy_product
    create_dummy_products
    self.shop.shop_products.create :name => DummyText.words(1).split(' ')[0..2].join(' '), :price_values => {'USD' => 10.00}, :description => DummyText.paragraph, :image_file_id => self.dummy_product_image.id
  end
end


text:
"""Virtual Servers."""
# :license: MIT, see LICENSE for more details.

import re

import click

MEMORY_RE = re.compile(r"^(?P<amount>[0-9]+)(?P<unit>g|gb|m|mb)?$")

class MemoryType(click.ParamType):
    """Memory type."""
    name = 'integer'

    def convert(self, value, param, ctx):
        """Validate memory argument. Returns the memory value in megabytes."""
        matches = MEMORY_RE.match(value.lower())
        if matches is None:
            self.fail('%s is not a valid value for memory amount'
                      % value, param, ctx)
        amount_str, unit = matches.groups()
        amount = int(amount_str)
        if unit in [None, 'm', 'mb']:
            # Assume the user intends gigabytes if they specify a number < 1024
            if amount < 1024:
                return amount * 1024
            else:
                if amount % 1024 != 0:
                    self.fail('%s is not an integer that is divisable by 1024'
                              % value, param, ctx)
                return amount
        elif unit in ['g', 'gb']:
            return amount * 1024

MEM_TYPE = MemoryType()


text:
import unittest
import mock

from nsq.client import Client
from nsq import response

class MockConnection(mock.Mock):
    def __init__(self, host=None, port=None, *args, **kwargs):
        mock.Mock.__init__(self)
        self.host = host
        self.port = port
        self._responses = []
        self._alive = True

    def read(self):
        '''Return all of our responses'''
        found = list(self._responses)
        self._responses = []
        return found

    def response(self, message):
        self._responses.append(
            response.Response(self, response.Response.FRAME_TYPE, message))

    def error(self, exception):
        '''Send an error'''
        self._responses.append(
            response.Error(self, response.Error.FRAME_TYPE, exception.name))

    def alive(self):
        return self._alive

    def close(self):
        self._alive = False

class MockedConnectionTest(unittest.TestCase):
    '''Create a client with mocked connection objects'''
    nsqd_ports = (12345, 12346)

    def setUp(self):
        with mock.patch('nsq.client.connection.Connection', MockConnection):
            hosts = ['localhost:%s' % port for port in self.nsqd_ports]
            self.client = Client(nsqd_tcp_addresses=hosts)
            self.connections = self.client.connections()


text:
Opinionated Rails Forum
=======================

This is a rails-based forum engine with some strong opinions:

 - Authentication is OpenID, makes new profile if not exists
 - There are no forums/subforums
 - Topics are tagged
 - Tags are lowercase. By definition
 - Everyone can edit tags for a topic
 - A user is either normal or admin, no moderators
 - Avatars are gravatars
 - No smilies or sigs

## Topics

There are two kinds of topics:

 - **Normal**: These topics always show their entire contents.

 - **Continuous**: These topics are more like a chat room than like a forum topic. They show only the latest 30 or so messages, and provide you with a paginated archive when you really need the history.

# TODO

 - Mark some tags as usable only by admins
 - Remove UsersController#destroy
 - Admin: option to split topics
 - Only admins and users themselves should be able to edit a user's profile
 - Only admins should have the Admin checkbox on profile editing
 - Reserve tag editing for original poster and admins
 - Replace Markdown with whitelisted HTML
 - Replace Prototype with unobtrusive JavaScript
 - Create Search page using Google Site Search
 - Give users a text box to add their own profile info
 - When switching message modes, preserve message
 - In large message mode, post/cancel buttons overlap right column


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>My title</title>
        <link rel="stylesheet" type="text/css" href="css/fonts.css" />
        <link rel="stylesheet" type="text/css" href="css/base.css" />

My page

                        Unicode strings and bytestrings in Python 2

Published: <time pubdate="pubdate">2015-04-21</time>

Character sets, encodings, Unicode and...

                Creative Commons Attribution-ShareAlike License


text:
このリポジトリでは、GameCanvas for Unity 向けのエディタ拡張DLLのソースコードを管理しています。

お問い合わせ等は [GameCanvas for Unity 本体のリポジトリ](https://github.com/sfc-sdp/GameCanvas-Unity) までお願いします。

## ライセンス
Copyright (c) 2015-2017 Smart Device Programming.

This software is released under the MIT License, see [LICENSE](LICENSE).


text:
from utils.schema_validator import *
import shelve

from mock_rest import *
# from flask.ext.cache import Cache
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

from flask import Flask, request, render_template
from mock_rest import *
from flask import jsonify

import multiprocessing as mp
# TODO: make configurable files

class AppContainer(object):
    pass

apps = shelve.open("allapps.txt", writeback=True)

def add_app(app_name, mock_rest):
    global apps
    apps.update({app_name: mock_rest})

def remove_app(app_name):
    global apps
    del apps[app_name]

def get_app(app_name):
    global apps
    return apps.get(app_name)

def launch_app_server_from_file(port, file_path, file_type):

    # validate and get the file content
    is_valid, content = validate_file_content(file_path, file_type)

    if is_valid:
        if(file_type == "JSON"):
            mock_rest = MockREST.from_json(content)

        # launch server
        print type(mock_rest.name)
        apps[str(mock_rest.name)] = file_path
        launch_flask_server(port, mock_rest)

        #launch_flask_server(port, mock_rest)

        # TODO Add these details to app container

    else:
        print "Invalid Content"
        raise ValueError("Invalid Content")

def launch_app_server_from_ui(port, app_data):
    # launch server
    if app_data:
        launch_flask_server(port, app_data)
    else:
        print "Invalid Content"
        raise ValueError("Invalid Content")

def launch_flask_server(port, mock_rest, shut_down=False):
    """
    Launches a new mock rest server with the passed configuration.
    :type port: integer
    """
    app_name = mock_rest.name

    # cache = Cache(config={'CACHE_TYPE': 'simple'})

    app = Flask(str(mock_rest.name).replace(" ", ''), static_folder='static')
    # cache.init_app(app)
    # print app
    # print port,"his is prot"
    #@app

    @app.route('/Apibox')
    def index():
        """ Displays the index page accessible at '/Apibox'
        """

        return render_template('index.html')

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>', methods=["GET", "POST", "DELETE", "PUT"])
    def catch_all(path):

        path = "/" + path

        endpoint_obj = mock_rest.get_endpoint(path, request.method)

        return jsonify(endpoint_obj)

        # print path, " this is path"
        #print (mock_rest.endpoints),"is it mock rest object"
        #  endpoint_obj = mock_rest.get_endpoint(path)
        #  if isinstance(endpoint_obj, str):
        #      return endpoint_obj.__json__()
        #  else:
        #      method = endpoint_obj.get_method(request.method)
        #      if isinstance(method, str):
        #          return method

        #  return str(method.result)

    if not shut_down:
        app.run(debug=True, host='0.0.0.0', port=port)


text:
using OpenTK;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK.Graphics.OpenGL;

namespace OpenTKPlatformerExample
{
    class Slime
    {
        public static Texture2D[] walkAnimation = new Texture2D[2];
        int index = 0;
        private Vector2 gravity;
        public Vector2 position;
        private Vector2 velocity;
        private Vector2 size;
        int deathtime = 0;
        private Texture2D sprite;
        public static Texture2D dead;
        public bool grounded,isdead;
        public int hash;

        public RectangleF ColRec
        {
            get
            {
                return new RectangleF(position.X - size.X / 2f, position.Y - size.Y / 2f, size.X - 2, size.Y);
            }
        }
        public RectangleF DrawRec
        {
            get
            {
                return new RectangleF(ColRec.X, ColRec.Y, ColRec.Width, ColRec.Height);
            }
        }
        public static void Load()
        {
            walkAnimation = new Texture2D[2];
            walkAnimation[0] = ContentPipe.LoadTexture("slimeGreen.png");
            walkAnimation[1] = ContentPipe.LoadTexture("slimeGreen_walk.png");
            dead = ContentPipe.LoadTexture("slimeGreen_squashed.png");
        }
        public Slime(Vector2 startPos, Vector2 gravity)
        {
            this.gravity = gravity;
            this.hash = Game.rand.Next(int.MinValue, int.MaxValue);
            this.position = startPos;
            this.velocity = Vector2.Zero;
            this.velocity.X = -3;
            this.size = new Vector2(49, 33);
            sprite = walkAnimation[index];

        }
        public void Update(ref Level level,Player player)
        {
            if (position.Y > 850)
            {
                foreach (Enemy e in Game.enemies.ToArray())
                {
                    if (e.hash == hash)
                    {
                        Game.enemies.Remove(e);
                        return;
                    }
                }
            }
            if (isdead)
            {
                if (Environment.TickCount > deathtime + 1500)
                {
                    foreach (Enemy e in Game.enemies.ToArray())
                    {
                        if (e.hash == hash)
                            Game.enemies.Remove(e);
                    }
                }
                if (sprite.ID != dead.ID)
                {
                    position.Y += velocity.Y;
                    velocity += gravity *2;
                }
                return;
            }
            if (sprite.ID != dead.ID)
            {
                index += 1;
                if (index == 6)
                {
                    index = 0;
                }
                if (index < 3)
                {
                    sprite = walkAnimation[0];
                    this.size = new Vector2(49, 33);
                }
                else
                {
                    sprite = walkAnimation[1];
                    this.size = new Vector2(57, 30);
                    position.Y += 3;
                }
            }

            if (grounded)
            {
                if (velocity.X < -10f)
                    velocity.X = -10f;
                if (velocity.X > 10f)
                    velocity.X = 10f;
            }
            else
            {
                if (velocity.X < -7f)
                    velocity.X = -7f;
                if (velocity.X > 7f)
                    velocity.X = 7f;
            }

            this.velocity += gravity;
            this.position += velocity;
            ResolveCollisions(ref level);
            if (CollisionPlayer(new RectangleF(player.position.X, player.position.Y, 24, 38)))
            {
                if (player.position.Y + 35<= position.Y && !player.dying )
                {
                    player.velocity.Y = -7;
                    if (Input.KeyDown(OpenTK.Input.Key.Z) || Input.A)
                    {
                        player.velocity.Y *= 2;
                    }
                    sprite = dead;
                    SoundManager.sounds[5].Play();
                    size = new Vector2(57, 32);
                    velocity = Vector2.Zero;
                    deathtime = Environment.TickCount;
                    isdead = true;
                }else
                {
                    if (!player.isInvincible )
                    {
                        if (Player.fireflower)
                        {
                            player.isInvincible = true;
                            player.invincibletime = Environment.TickCount;
                            Player.fireflower = false;
                        }else
                        {
                            player.Death();
                        }
                    }
                }
            }
            if (ObjectHandler.fireballsonscreen != 0)
            foreach (GameObject o in ObjectHandler.objects.ToArray())
                if (o.type == ObjectHandler.ObjectType.Fireball)
            if (Math.Sqrt(Math.Pow(position.X - o.position.X,2) + Math.Pow(position.Y - o.position.Y,2)) < 32)
                {
                        ObjectHandler.objects.Remove(o);
                        ObjectHandler.fireballsonscreen -= 1;
                        isdead = true;
                        //Burn sound
                        deathtime = Environment.TickCount;
                        velocity = new Vector2(velocity.X, -10);
                }
        }
        private void ResolveCollisions(ref Level level)
        {
            int minX = (int)Math.Floor((this.position.X - this.size.X / 2f) / Game.GRIDSIZE);
            int minY = (int)Math.Floor((this.position.Y - this.size.Y / 2f) / Game.GRIDSIZE);
            int maxX = (int)Math.Ceiling((this.position.X + this.size.X / 2f) / Game.GRIDSIZE);
            int maxY = (int)Math.Ceiling((this.position.Y + this.size.Y / 2f) / Game.GRIDSIZE);

            for (int x = minX; x <= maxX; x++)
            {
                for (int y = minY; y <= maxY; y++)
                {
                    RectangleF blockRec = new RectangleF(x * Game.GRIDSIZE, y * Game.GRIDSIZE, Game.GRIDSIZE, Game.GRIDSIZE);

                    if (level[x, y].IsSolid && this.ColRec.IntersectsWith(blockRec))
                    {

                        #region Resolve
                        if (y *Game.GRIDSIZE<= position.Y )
                        if (x * Game.GRIDSIZE > position.X)
                        {
                            velocity.X = -3;
                        }
                        else
                        {
                            velocity.X = 3;
                        }
                        float[] depths = new float[4]
                        {
                            blockRec.Right - ColRec.Left, //PosX
							blockRec.Bottom - ColRec.Top, //PosY
							ColRec.Right - blockRec.Left, //NegX
							ColRec.Bottom - blockRec.Top  //NegY
						};

                        if (level[x + 1, y].IsSolid)
                            depths[0] = -1;
                        if (level[x, y + 1].IsSolid || level[x, y].IsPlatform)
                            depths[1] = -1;
                        if (level[x - 1, y].IsSolid)
                            depths[2] = -1;
                        if (level[x, y - 1].IsSolid)
                            depths[3] = -1;

                        float min = float.MaxValue;
                        Vector2 minDirection = Vector2.Zero;
                        for (int i = 0; i < 4; i++)
                        {
                            if (depths[i] >= 0 && depths[i] < min)
                            {
                                min = depths[i];
                                switch (i)
                                {
                                    case 0:
                                        minDirection = new Vector2(1, 0);
                                        break;
                                    case 1:
                                        minDirection = new Vector2(0, 1);
                                        break;
                                    case 2:
                                        minDirection = new Vector2(-1, 0);
                                        break;
                                    default:
                                        minDirection = new Vector2(0, -1);
                                        break;
                                }
                            }
                        }

                        if (minDirection == Vector2.Zero)
                        {
                            //Console.WriteLine("This shouldn't really happen...");
                        }
                        else
                        {
                            this.position += minDirection * min;
                            if (this.velocity.X * minDirection.X < 0)
                                this.velocity.X = 0;
                            if (this.velocity.Y * minDirection.Y < 0)
                                this.velocity.Y = 0;

                            if (minDirection == new Vector2(0, -1))
                                grounded = true;
                        }

                        #endregion
                    }
                    if (this.velocity.Y > 0 && this.ColRec.IntersectsWith(blockRec))
                    {
                        if (this.position.Y - this.velocity.Y + this.size.Y / 2f <= blockRec.Top) //if we were above last frame
                        {
                            this.velocity.Y = 0;
                            this.position.Y = blockRec.Top - this.size.Y / 2f;
                            grounded = true;
                        }
                    }
                }
            }
        }
        public bool CollisionPlayer(RectangleF player)
        {
            if (ColRec.IntersectsWith(player))
            {
                return true;
            }
            return false;
        }
        public void Draw()
        {
            RectangleF rec = DrawRec;
            if (velocity.X > 0)
            {
                rec.X += rec.Width;
                rec.Width = -rec.Width;

            }
            if (isdead && sprite.ID != dead.ID)
            {
                rec.Y += rec.Height;
                rec.Height = -rec.Height;
            }

            if (Game.Level != 5)
            Spritebatch.DrawSprite(sprite, rec,Color.White);
            else
                Spritebatch.DrawSprite(sprite, rec, Color.Purple);
        }
    }
}