text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ui.activity.DebugActivity">

    <data>
        <variable
                name="presenter"
                type="org.yframework.android.view.Presenter"/>
    </data>
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:gravity="center">

            <ImageView
                android:id="@+id/ad_image_view"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:contentDescription="@null"/>

        </LinearLayout>
        <Button
                android:id="@+id/ad_action_add_personnel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="25dp"
                android:text="@string/action_add_personnel"
                android:onClick="@{(v)->presenter.onClick(v)}"
        />

        <Button
                android:id="@+id/ad_action_get_personnel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="25dp"
                android:text="@string/action_get_personnel"
                android:onClick="@{(v)->presenter.onClick(v)}"
        />

        <Button
                android:id="@+id/ad_action_remove_personnel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="25dp"
                android:text="@string/action_remove_personnel"
                android:onClick="@{(v)->presenter.onClick(v)}"
        />

        <Button
            android:id="@+id/ad_action_to_main_activity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="25dp"
            android:text="@string/action_to_main_activity"
            android:onClick="@{(v)->presenter.onClick(v)}"
            />
    </LinearLayout>
</layout>


text:
using System;
using FakeItEasy;
using SolutionInspector.Api.Rules;
using SolutionInspector.TestInfrastructure;

namespace SolutionInspector.Api.Tests.Reporting
{
  internal static class RuleViolationObjectMother
  {
    public static IRuleViolation Create (IRule rule = null, string target = null, string targetPath = null, string message = null)
    {
      var ruleViolation = A.Fake<IRuleViolation>();

      A.CallTo(() => ruleViolation.Rule).Returns(rule ?? new SomeRule());
      A.CallTo(() => ruleViolation.Target.Identifier).Returns(target ?? Some.String());
      A.CallTo(() => ruleViolation.Target.FullPath).Returns(targetPath ?? Some.String());
      A.CallTo(() => ruleViolation.Message).Returns(message ?? Some.String());

      return ruleViolation;
    }

    class SomeRule : IRule
    {
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace FOS\UserBundle\Util;

/**
 * @internal
 *
 * @author Gabor Egyed <gabor.egyed@gmail.com>
 */
final class LegacyFormHelper
{
    private static $map = array(
        'FOS\UserBundle\Form\Type\ChangePasswordFormType' => 'fos_user_change_password',
        'FOS\UserBundle\Form\Type\GroupFormType' => 'fos_user_group',
        'FOS\UserBundle\Form\Type\ProfileFormType' => 'fos_user_profile',
        'FOS\UserBundle\Form\Type\RegistrationFormType' => 'fos_user_registration',
        'FOS\UserBundle\Form\Type\ResettingFormType' => 'fos_user_resetting',
        'Symfony\Component\Form\Extension\Core\Type\EmailType' => 'email',
        'Symfony\Component\Form\Extension\Core\Type\PasswordType' => 'password',
        'Symfony\Component\Form\Extension\Core\Type\RepeatedType' => 'repeated',
        'Symfony\Component\Form\Extension\Core\Type\TextType' => 'text',
    );

    public static function getType($class)
    {
        if (!self::isLegacy()) {
            return $class;
        }

        if (!isset(self::$map[$class])) {
            throw new \InvalidArgumentException(sprintf('Form type with class "%s" can not be found. Please check for typos or add it to the map in LegacyFormHelper', $class));
        }

        return self::$map[$class];
    }

    public static function isLegacy()
    {
        return !method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix');
    }

    private function __construct()
    {
    }

    private function __clone()
    {
    }
}


text:
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, DetailView, ListView

# from toolhub.mixins import MPTTUrlMixin
from tools.models import Tool, ToolClassification, UserTool
from .forms import CreateUserToolForm, SuggestToolForm
from toolhub.mixins import LoginRequiredMixin, FormValidMessageMixin

class CreateUserTool(
        LoginRequiredMixin,
        FormValidMessageMixin,
        CreateView):
    """
    Allows user to create a new user tool
    """
    template_name = 'tools/usertool_create.jinja'
    model = UserTool
    form_class = CreateUserToolForm
    form_valid_message = _("Succefully added tool to your library.")

    def get_success_url(self):
        return reverse('account:tool:manager')

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.owner = self.request.user
        self.object.save()
        return super(CreateUserTool, self).form_valid(form)

class SuggestTool(
        LoginRequiredMixin,
        FormValidMessageMixin,
        CreateView):
    """
    Allows users to suggest new tool types
    """
    template_name = 'tools/tool_suggest.jinja'
    model = Tool
    form_class = SuggestToolForm
    form_valid_message = _("""
        Thanks for suggesting a new tool type! We'll take it from here!""")

    def get_success_url(self):
        return reverse('account:tool:manager')

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.creator = self.request.user
        assert self.object.published is False
        return super(SuggestTool, self).form_valid(form)

class BaseToolList(ListView):
    template_name = 'tools/tool_list.jinja'
    queryset = Tool.objects.published()
    context_object_name = 'tool_list'
    paginate_by = 6

class ToolList(BaseToolList):
    """
    A filterable list of tools by classification
    """
    tool_class = None

    def dispatch(self, request, *args, **kwargs):
        tool_class_slug = kwargs.pop('tool_class_slug', None)
        if tool_class_slug:
            self.tool_class = get_object_or_404(
                ToolClassification, slug=tool_class_slug)

        return super(ToolList, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, object=None):
        context = super(ToolList, self).get_context_data()
        context['tool_class'] = self.tool_class
        return context

    def get_queryset(self):
        qs = super(ToolList, self).get_queryset()
        if self.tool_class:
            #TODO: show all tools that are inside a category and it's decendants
            return qs.children_tools(self.tool_class)
        else:
            return qs

class ToolDetailView(DetailView):
    template_name = 'tools/tool_detail.jinja'
    model = Tool
    slug_url_kwarg = 'tool_slug'
    context_object_name = 'tool'


text:
import * as modelsProxy from '../proxy/'

const userProxy  = modelsProxy.userProxy;
import crypto from 'crypto'
import uuid from 'node-uuid'

const secretKey = 'fd*^$#ygwefugb!#TYTf%&lasgdfiu&*%^';

const reg = function(req,res,next){
	userProxy.getUserByName(req.body.username,(err,user)=>{
		if(err){
			return next(err)
		}
		if(user){
			return res.json({key:0,err:'用户已存在'})
		}
		let date = (new Date()).toLocaleString()
		let newUser = {
			username:req.body.username,
			password:req.body.password,
			nickName:req.body.nickName,
			imgUrl:req.body.imgUrl,
			uid:uuid.v4(),
			regTime:date,
			lastLogin:date
		}
		let hmac = crypto.createHmac('sha256', secretKey)
		newUser.password = hmac.update(newUser.password).digest('hex')
		userProxy.createUser(newUser,(err,newuser)=>{
			if(err){
				return next(err);
			}
			return res.json({key:1,user:newuser})
		})
	})
}

const login = function(req,res,next){
	userProxy.getUserByName(req.body.username,(err,user)=>{
		if(err){
			return next(err);
		}
		if(!user){
			return res.json({key:0,err:'用户不存在'})
		}
		let hmac = crypto.createHmac('sha256', secretKey)
		let password = hmac.update(req.body.password).digest('hex')
		if(password !== user.password){
			return res.json({key:0,err:'密码错误'})
		}
		let date = (new Date()).toLocaleString()
		req.session.userInfo = {
			username:user.username,
			regTime:user.regTime,
			nickName:user.nickName,
			imgUrl:user.imgUrl,
			uid:user.uid,
			lastLogin:user.lastLogin
		}
		userProxy.updateUserLastLogin(req.body.username,(err,newuser)=>{
			if(err){
				return next(err)
			}
			return res.json({key:1,user:newuser})
		})
	})
}

const getUserInfoFromSession = function(req,res,next){
	res.json({key:1,userInfo:req.session.userInfo})
}

const delUserInfoFromSession = function(req,res,next){
	req.session.userInfo = null
	res.json({key:1})
}

export {reg,login,getUserInfoFromSession,delUserInfoFromSession}


text:
module.exports = {
    // db collection
    collection: 'auths',
    // projection of db collection
    publicCollection: 'users',
    user: {
        id: true,
        email: true
    },
    confirmRegistration: false,
    // passportjs options
    passport: {
        successRedirect: '/',
        failureRedirect: '/'
    },
    strategies: {
        github: {
            strategy: require("passport-github").Strategy,
            conf: {
                clientID: "eeb00e8fa12f5119e5e9",
                clientSecret: "61631bdef37fce808334c83f1336320846647115"
            }
        },
        google: {
            strategy: require('passport-google-oauth').OAuth2Strategy,
            conf: {
                clientID: '1060568558513-164eli9jaaf8nbjgv4asv3gutn72usl6.apps.googleusercontent.com',
                clientSecret: 'lqYJ1NF1AEeAA07MUGrIynXD',
                callbackURL: 'http://localhost:3000/auth/google/callback',
                scope: 'https://www.googleapis.com/auth/plus.login'
            }
        },
        linkedin: {
            strategy: require('passport-linkedin').Strategy,
            conf: {
                consumerKey: '4s7d4s2c1d7s',
                consumerSecret: '4Df1dW8s547qQ95',
                profileFields: ["id", "first-name", "last-name", "headline", "email-address"],
                params: {
                    scope: ["r_fullprofile", "r_emailaddress"]
                }
            }
        },
        facebook: {
            strategy: require('passport-facebook').Strategy,
            conf: {
                clientID: '58362219983',
                clientSecret: 'da0fb6cbcb6cac1a0aca9f78200935d2',
                callbackURL: 'http://localhost:3000/auth/facebook/callback'
            }
        },
        vkontakte: {
            strategy: require('passport-vkontakte').Strategy,
            conf: {
                clientID: '4373291',
                clientSecret: 'fOZiLyGhSH1DHWLFFfZo',
                callbackURL: 'http://localhost:3000/auth/vkontakte/callback'
            }
        }
    },
    hooks: {
        request: function (req, res, userId, isAuthenticated, done) {
            done();
        }
    }
};


text:
set -x
echo "Creating user Oracle"

#
# Create the user and group oracle
#
/usr/sbin/groupadd oracle
useradd oracle -g oracle -G wheel
echo "oracle"|passwd --stdin oracle
echo "oracle          ALL=(ALL)     NOPASSWD: ALL" >> /etc/sudoers.d/oracle
chmod 0440 /etc/sudoers.d/oracle

#
# set the tmp directory up for the oracle user
#
echo "export TMP=/tmp" >> /home/oracle/.bash_profile
echo "export TMPDIR=/tmp" >> /home/oracle/.bash_profile
echo "export ORACLE_HOSTNAME='$HOSTNAME'" >> /home/oracle/.bash_profile


text:
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>D3: Creating an empty SVG</title>
		<script type="text/javascript" src="../d3.js"></script>
		<style type="text/css">
			/* No style rules here yet */
		</style>
	</head>
	<body>
		<script type="text/javascript">

			//Create SVG element
			var svg = d3.select("body")
						.append("svg")
						.attr("width", 500)
						.attr("height", 50);

		</script>
	</body>
</html>


text:
class Condition {
public:
	virtual bool Check() const = 0;
};

#endif//!_CONDITION_H


text:
package server

import (
	"fmt"
	"io"
	"net"
	"time"

	proto1 "github.com/golang/protobuf/proto"
	"github.com/nicholaskh/golib/server"
	log "github.com/nicholaskh/log4go"
	. "github.com/nicholaskh/mysql-cluster/config"
	"github.com/nicholaskh/mysql-cluster/core"
	proto "github.com/nicholaskh/mysql-cluster/proto/go"
)

func LaunchServer(config *ServerConfig) {
	s := server.NewTcpServer("myc")

	s.LaunchTcpServer(config.ListenAddr, newClientHandler(config), time.Minute*2, 200)
}

type ClientHandler struct {
	serverConfig *ServerConfig
}

func newClientHandler(serverConfig *ServerConfig) *ClientHandler {
	return &ClientHandler{serverConfig}
}

func (this *ClientHandler) OnAccept(c *server.Client) {
	proto := server.NewProtocol()
	proto.SetConn(c.Conn)
	client := newClient(c, proto)
	for {
		if this.serverConfig.SessTimeout.Nanoseconds() > int64(0) {
			client.Proto.SetReadDeadline(time.Now().Add(this.serverConfig.SessTimeout))
		}

		data, err := client.proto.Read()

		if err != nil {
			err_, ok := err.(net.Error)
			if ok {
				if err_.Temporary() {
					log.Info("Temporary failure: %s", err_.Error())
					break
				}
			}
			if err == io.EOF {
				log.Info("Client %s closed the connection", client.Proto.RemoteAddr().String())
				break
			} else {
				log.Error(err.Error())
				break
			}
		}

		go this.OnRead(data, client)
	}
	client.Close()
}

func (this *ClientHandler) OnRead(input []byte, client *Client) {
	q := &proto.QueryStruct{}
	err := proto1.Unmarshal([]byte(input), q)
	if err != nil {
		log.Error("parse query error")
	}
	log.Info("sql: %s\npool: %s", q.GetSql(), q.GetPool())
	cols, rows, err := core.MysqlClusterInstance.Query(q)
	if err != nil {
		log.Error(err.Error())
	} else {
		log.Info(cols)
		log.Info(rows)
		client.WriteMsg(fmt.Sprintf("%s\n", rows))
	}
}

func handleClient(client *server.Client) {
	client.Conn.Write([]byte("connected"))
}

type Client struct {
	*server.Client
	proto *server.Protocol
}

func newClient(c *server.Client, proto *server.Protocol) *Client {
	this := new(Client)
	this.Client = c
	this.proto = proto

	return this
}


text:
///<reference path="../../typings/grunt.d.ts" />
///<reference path="./task.ts" />
var util = require("./util");
var ts = require("typescript");
var _path = require("path"), _fs = require("fs");
function prepareWatch(opt, files) {
    var after = [], before = [], val = opt.watch, getDirNames = function (files) {
        return files.map(function (file) {
            if (_fs.existsSync(file)) {
                if (_fs.statSync(file).isDirectory()) {
                    return file;
                }
            }
            else {
                if (!_path.extname(file)) {
                    return file;
                }
            }
            return util.normalizePath(_path.resolve(_path.dirname(file)));
        });
    }, extractPath = function (files) {
        var dirNames = getDirNames(files), result = dirNames.reduce(function (prev, curr) {
            if (!prev) {
                return curr;
            }
            var left = util.normalizePath(_path.relative(prev, curr)), right = util.normalizePath(_path.relative(curr, prev)), match = left.match(/^(\.\.(\/)?)+/);
            if (match) {
                return util.normalizePath(_path.resolve(prev, match[0]));
            }
            match = right.match(/^(\.\.(\/)?)+/);
            if (match) {
                return util.normalizePath(_path.resolve(curr, match[0]));
            }
            return prev;
        }, undefined);
        if (result) {
            return [result];
        }
    };
    if (!val) {
        return undefined;
    }
    if (util.isStr(val) || util.isArray(val)) {
        return {
            path: util.isStr(val) ? [val] : val,
            after: [],
            before: [],
            atBegin: false
        };
    }
    if (util.isBool(val) && !!val) {
        return {
            path: extractPath(files),
            after: [],
            before: [],
            atBegin: false
        };
    }
    if (!val.path) {
        val.path = extractPath(files);
        if (!val.path) {
            //util.writeWarn("Can't auto detect watch directory. Please place one or more files or set the path option.");
            return undefined;
        }
    }
    if (val.after && !util.isArray(val.after)) {
        after.push(val.after);
    }
    else if (util.isArray(val.after)) {
        after = val.after;
    }
    if (val.before && !util.isArray(val.before)) {
        before.push(val.before);
    }
    else if (util.isArray(val.before)) {
        before = val.before;
    }
    return {
        path: val.path,
        after: after,
        before: before,
        atBegin: !!val.atBegin
    };
}
function checkBasePath(opt) {
    if (util.isUndef(opt.basePath)) {
        return;
    }
    var result = "";
    if (util.isStr(opt.basePath)) {
        result = opt.basePath;
    }
    if (!result) {
        return undefined;
    }
    result = util.normalizePath(result);
    if (result.lastIndexOf("/") !== result.length - 1) {
        result = result + "/";
    }
    util.writeWarn("BasePath option has been deprecated. Method for determining an output directory has been changed in the same way as the TSC. " +
        "Please re-set output directory with the new rootDir option or use keepDirectoryHierachy option. " +
        "However, keepDirectoryHierachy option would not be available long.");
    return result;
}
function prepareTarget(opt) {
    var result = 0 /* ES3 */;
    if (opt.target) {
        var temp = (opt.target + "").toLowerCase();
        if (temp === 'es3') {
            result = 0 /* ES3 */;
        }
        else if (temp == 'es5') {
            result = 1 /* ES5 */;
        }
        else if (temp == "es6") {
            result = 2 /* ES6 */;
        }
    }
    return result;
}
function prepareModule(opt) {
    var result = 0 /* None */;
    if (opt.module) {
        var temp = (opt.module + "").toLowerCase();
        if (temp === "commonjs" || temp === "node") {
            result = 1 /* CommonJS */;
        }
        else if (temp === "amd") {
            result = 2 /* AMD */;
        }
        else if (temp === "system") {
            result = 4 /* System */;
        }
        else if (temp === "umd") {
            result = 3 /* UMD */;
        }
    }
    return result;
}
function prepareNewLine(opt) {
    var result = undefined;
    if (opt.newLine) {
        var temp = (opt.newLine + "").toLowerCase();
        if (temp === "crlf") {
            result = 0 /* CarriageReturnLineFeed */;
        }
        else if (temp === "lf") {
            result = 1 /* LineFeed */;
        }
    }
    return result;
}
function boolOrUndef(source, key, def) {
    var result = util.isUndef(source[key]) ? undefined : !!source[key];
    if (util.isUndef(result) && !util.isUndef(def)) {
        result = def;
    }
    return result;
}
function prepareGenerateTsConfig(opt) {
    var result = false;
    if (!opt.generateTsConfig) {
        return false;
    }
    if (util.isBool(opt.generateTsConfig)) {
        return !!opt.generateTsConfig;
    }
    if (util.isStr(opt.generateTsConfig)) {
        return opt.generateTsConfig + "";
    }
    return result;
}
function createGruntOption(source, grunt, gruntFile, logger) {
    var dest = util.normalizePath(gruntFile.dest || ""), singleFile = !!dest && _path.extname(dest) === ".js", targetVersion = prepareTarget(source), basePath = checkBasePath(source), rootDir = util.isStr(source.rootDir) ? source.rootDir : undefined, keepDirectoryHierarchy = boolOrUndef(source, "keepDirectoryHierarchy");
    function getTargetFiles() {
        return grunt.file.expand(gruntFile.orig.src);
    }
    function getReferences() {
        var target, binPath = util.getBinDir();
        if (!source.references) {
            return [];
        }
        if (util.isStr(source.references)) {
            target = [source.references];
        }
        if (util.isArray(source.references)) {
            target = source.references.concat();
        }
        if (!target) {
            return [];
        }
        target = target.map(function (item) {
            if (item === "lib.core.d.ts" || item === "core") {
                return util.combinePaths(binPath, targetVersion === 2 /* ES6 */ ? "lib.core.es6.d.ts" : "lib.core.d.ts");
            }
            if (item === "lib.dom.d.ts" || item === "dom") {
                return util.combinePaths(binPath, "lib.dom.d.ts");
            }
            if (item === "lib.scriptHost.d.ts" || item === "scriptHost") {
                return util.combinePaths(binPath, "lib.scriptHost.d.ts");
            }
            if (item === "lib.webworker.d.ts" || item === "webworker") {
                return util.combinePaths(binPath, "lib.webworker.d.ts");
            }
            return item;
        });
        return grunt.file.expand(target);
    }
    if (keepDirectoryHierarchy) {
        rootDir = undefined;
    }
    else {
        basePath = undefined;
    }
    var result = {
        targetFiles: getTargetFiles,
        dest: dest,
        singleFile: singleFile,
        basePath: basePath,
        //ignoreError: boolOrUndef(source, "ignoreError"),
        keepDirectoryHierarchy: keepDirectoryHierarchy,
        watch: prepareWatch(source, getTargetFiles()),
        references: getReferences,
        generateTsConfig: prepareGenerateTsConfig(source),
        //_showNearlyTscCommand: !!grunt.option("showtsc"),
        tsOptions: {
            //removeComments: prepareRemoveComments(source),
            removeComments: boolOrUndef(source, "removeComments"),
            sourceMap: boolOrUndef(source, "sourceMap"),
            declaration: boolOrUndef(source, "declaration"),
            out: singleFile ? dest : undefined,
            outDir: singleFile ? undefined :
                keepDirectoryHierarchy ? undefined : dest,
            noLib: boolOrUndef(source, "noLib"),
            noImplicitAny: boolOrUndef(source, "noImplicitAny"),
            noResolve: boolOrUndef(source, "noResolve"),
            target: targetVersion,
            rootDir: rootDir,
            module: prepareModule(source),
            preserveConstEnums: boolOrUndef(source, "preserveConstEnums"),
            noEmitOnError: boolOrUndef(source, "noEmitOnError", true),
            suppressImplicitAnyIndexErrors: boolOrUndef(source, "suppressImplicitAnyIndexErrors"),
            experimentalDecorators: boolOrUndef(source, "experimentalDecorators"),
            emitDecoratorMetadata: boolOrUndef(source, "emitDecoratorMetadata"),
            newLine: prepareNewLine(source),
        }
    };
    logger.verbose("--option");
    logger.verbose(JSON.stringify(result, null, "  "));
    return result;
}
exports.createGruntOption = createGruntOption;


text:
<?php
namespace Ibrows\RestBundle\Listener;

use Ibrows\RestBundle\Annotation\View;
use Ibrows\RestBundle\Expression\ExpressionEvaluator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\Routing\RouterInterface;

class LocationResponseListener
{
    /**
     * @var RouterInterface
     */
    protected $router;

    /**
     * @var ExpressionEvaluator
     */
    protected $evaluator;

    /**
     * CreateViewResponseListener constructor.
     * @param RouterInterface $router
     * @param $evaluator
     */
    public function __construct(RouterInterface $router, ExpressionEvaluator $evaluator)
    {
        $this->router = $router;
        $this->evaluator = $evaluator;
    }

    /**
     * {@inheritdoc}
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $response = $event->getResponse();
        $request = $event->getRequest();

        /** @var View $configuration */
        $view = $request->attributes->get('_template');

        if (!$view instanceof View || !$view->getLocation()) {
            return;
        }

        $objects = $request->attributes->all();

        $params = $this->prepareRouteParameters($view->getLocation()->getParams(), $objects);
        $url = $this->router->generate($view->getLocation()->getRoute(), $params);

        $response->headers->add(array('Location' => $url));
        $event->setResponse($response);
    }

    /**
     * @param $params
     * @param $context
     * @return mixed
     */
    protected function prepareRouteParameters(array $params, array $context)
    {
        $newParams = $params;
        foreach ($params as $key => $val) {
            $newParams[$key] = $this->evaluator->evaluate($val, $context);
        }

        return $newParams;
    }
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

001
017
018package org.apache.commons.net.io;
019
020import java.io.BufferedReader;
021import java.io.IOException;
022import java.io.Reader;
023
024/**
025 * CRLFLineReader implements a readLine() method that requires
026 * exactly CRLF to terminate an input line.
027 * This is required for IMAP, which allows bare CR and LF.
028 *
029 * @since 3.0
030 */
031public final class CRLFLineReader extends BufferedReader
032{
033    private static final char LF = '\n';
034    private static final char CR = '\r';
035
036    /**
037     * Creates a CRLFLineReader that wraps an existing Reader
038     * input source.
039     * @param reader  The Reader input source.
040     */
041    public CRLFLineReader(Reader reader)
042    {
043        super(reader);
044    }
045
046    /**
047     * Read a line of text.
048     * A line is considered to be terminated by carriage return followed immediately by a linefeed.
049     * This contrasts with BufferedReader which also allows other combinations.
050     * @since 3.0
051     */
052    @Override
053    public String readLine() throws IOException {
054        StringBuilder sb = new StringBuilder();
055        int intch;
056        boolean prevWasCR = false;
057        synchronized(lock) { // make thread-safe (hopefully!)
058            while((intch = read()) != -1)
059            {
060                if (prevWasCR && intch == LF) {
061                    return sb.substring(0, sb.length()-1);
062                }
063                if (intch == CR) {
064                    prevWasCR = true;
065                } else {
066                    prevWasCR = false;
067                }
068                sb.append((char) intch);
069            }
070        }
071        String string = sb.toString();
072        if (string.length() == 0) { // immediate EOF
073            return null;
074        }
075        return string;
076    }
077}


text:
package org.apache.ws.security.message;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.message.token.Timestamp;
import org.apache.ws.security.util.WSSecurityUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Builds a WS Timestamp and inserts it into the SOAP Envelope. Refer to the WS
 * specification 1.0. chapter 10 / appendix A.2
 *
 * @author Christof Soehngen (Christof.Soehngen@syracom.de).
 * @author Werner Dittmann (werner@apache.org).
 */

public class WSSecTimestamp extends WSSecBase {
    private static Log log = LogFactory.getLog(WSSecTimestamp.class.getName());

    private Timestamp ts = null;

    private int timeToLive = 300; // time between Created and Expires

    /**
     * Constructor.
     */
    public WSSecTimestamp() {
    }

    /**
     * Set the time to live. This is the time difference in seconds between the
     * Created and the Expires in
     * Timestamp.

     *
     * @param ttl The time to live in second
     */
    public void setTimeToLive(int ttl) {
        timeToLive = ttl;
    }

    /**
     * Creates a Timestamp element.
     *
     * The method prepares and initializes a WSSec Timestamp structure after the
     * relevant information was set. Before calling prepare() the
     * parameter such as timeToLive can be set if the default
     * value is not suitable.
     *
     * @param doc The SOAP envelope as W3C document
     */
    public void prepare(Document doc) {
        ts = new Timestamp(wssConfig.isPrecisionInMilliSeconds(), doc, timeToLive);
        String tsId = wssConfig.getIdAllocator().createId("Timestamp-", ts);
        ts.setID(tsId);
    }

    /**
     * Prepends the Timestamp element to the elements already in the Security
     * header.
     *
     * The method can be called any time after prepare(). This
     * allows to insert the Timestamp element at any position in the Security
     * header.
     *
     * @param secHeader The security header that holds the Signature element.
     */
    public void prependToHeader(WSSecHeader secHeader) {
        WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), ts.getElement());
    }

    /**
     * Adds a new Timestamp to a soap envelope.
     *
     * A complete Timestamp is constructed and added to the
     * wsse:Security header.
     *
     * @param doc The SOAP envelope as W3C document
     * @param secHeader The security header that hold this Timestamp
     * @return Document with Timestamp added
     * @throws Exception
     */
    public Document build(Document doc, WSSecHeader secHeader) {
        log.debug("Begin add timestamp...");

        prepare(doc);
        prependToHeader(secHeader);

        return doc;
    }

    /**
     * Get the id generated during prepare().
     *
     * Returns the the value of wsu:Id attribute of this Timestamp.
     *
     * @return Return the wsu:Id of this token or null if
     *         prepareToken() was not called before.
     */
    public String getId() {
        if (ts == null) {
            return null;
        }
        return ts.getID();
    }

    /**
     * Get the timestamp element generated during prepare().
     */
    public Element getElement() {
        if (ts == null) {
            return null;
        }
        return ts.getElement();
    }
}


text:
package com.navercorp.pinpoint.hbase.manager;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.DefaultApplicationArguments;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author HyunGil Jeong
 */
public class ProgramCommand {

    public static final ProgramCommand EMPTY = new ProgramCommand("", Collections.emptyList());

    private final String command;
    private final List<String> commandArgs;

    private ProgramCommand(String command) {
        this(command, Collections.emptyList());
    }

    private ProgramCommand(String command, List<String> commandArgs) {
        this.command = Objects.requireNonNull(command, "command must not be null");
        this.commandArgs = Objects.requireNonNull(commandArgs, "commandArgs must not be null");
    }

    public static ProgramCommand parseArgs(String[] args) {
        if (args == null) {
            throw new NullPointerException("args must not be null");
        }
        return parseArgs(new DefaultApplicationArguments(args));
    }

    public static ProgramCommand parseArgs(ApplicationArguments applicationArguments) {
        if (applicationArguments == null) {
            throw new NullPointerException("applicationArguments must not be null");
        }
        List<String> nonOptionArgs = applicationArguments.getNonOptionArgs();
        if (CollectionUtils.isEmpty(nonOptionArgs)) {
            return EMPTY;
        }
        String commandString = nonOptionArgs.get(0);
        if (nonOptionArgs.size() > 1) {
            List<String> commandArgs = new ArrayList<>(nonOptionArgs.subList(1, nonOptionArgs.size()));
            return new ProgramCommand(commandString, commandArgs);
        }
        return new ProgramCommand(commandString);
    }

    public String getCommand() {
        return command;
    }

    public List<String> getCommandArgs() {
        return commandArgs;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder().append('[').append(command).append(']');
        if (!commandArgs.isEmpty()) {
            sb.append(", args : ").append(commandArgs);
        }
        return sb.toString();
    }
}


text:
'use strict';

var util = require('util');
var Logmatic = require('node-logmatic');
var Transport = require('winston').Transport;

function WinstonLogmatic(options) {
  Transport.call(this, options);
  options = options || {};

  this.logmatic = new Logmatic(options.logmatic);
};

util.inherits(WinstonLogmatic, Transport);

// Expose the name of this WinstonLogmatic on the prototype
WinstonLogmatic.prototype.name = 'logmatic';

WinstonLogmatic.prototype.log = function (level, message, meta, callback) {
  var logMessage = {
    level: level,
    meta: meta
  };

  if (message) {
    logMessage.message = message;
  }

  this.logmatic.log(logMessage);
  callback();
};

module.exports = WinstonLogmatic;


text:
/**
 * @namespace dom
 */

ECMAScript.Extend('dom', function (ecma) {

  /**
   * @function getXPath
   */

  this.getXPath = function (elem) {
    elem = ecma.dom.getElement(elem);
    var result = [''];
    while (elem && ecma.dom.node.isElement(elem)) {
      var i = ecma.dom.getChildIndex(elem);
      var name = elem.tagName.toLowerCase();
      if (i > 0) name += '[' + (i + 1) + ']';
      result.unshift(name);
      elem = elem.parentNode;
    }
    return result.join('/');
  }

  /**
   * @function getChildIndex
   */

  this.getChildIndex = function (elem) {
    var result = 0;
    for (var node = elem.previousSibling; node; node = node.previousSibling) {
      if (ecma.dom.node.isElement(node) && (node.tagName == elem.tagName)) {
        result++;
      }
    }
    return result;
  }

});


text:
@interface BMWeakReferenceContext : NSObject

@property (nonatomic, weak) id owner;
@property (nonatomic, copy) BMWeakReferenceCleanupBlock cleanupBlock;

@end

@implementation BMWeakReferenceContext

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

- (NSUInteger)hash {
    NSUInteger hash = ((NSUInteger)self.owner);
    return hash;
}

- (BOOL)isEqual:(id)object {
    BOOL ret = NO;
    if ([object isKindOfClass:[BMWeakReferenceContext class]]) {
        BMWeakReferenceContext *other = object;
        ret = other.owner == self.owner;
    }
    return ret;
}

- (void)dealloc {
    //Object was deallocated: Do cleanup
    BMWeakReferenceCleanupBlock cleanupBlock = self.cleanupBlock;
    if (cleanupBlock) {
        cleanupBlock();
    }
}

@end

@interface NSObject(BMWeakReferenceRegistry)

- (void)bmAddWeakReferenceContext:(BMWeakReferenceContext *)context;
- (void)bmRemoveWeakReferenceContext:(BMWeakReferenceContext *)context;
- (void)bmRemoveWeakReferenceContexts;
- (void)bmRemoveWeakReferenceContextsWithPredicate:(BOOL (^)(BMWeakReferenceContext *))predicate;
- (BOOL)bmHasWeakReferenceContextWithPredicate:(BOOL (^)(BMWeakReferenceContext *))predicate;

@end

@implementation NSObject(BMWeakReferenceRegistry)

static char * const kBMWeakReferenceContextsKey = "com.behindmedia.bmcommons.NSObject.weakReferenceContexts";

- (NSMutableArray<BMWeakReferenceContext *> *)_bmWeakReferenceContexts {
    return objc_getAssociatedObject(self, kBMWeakReferenceContextsKey);
}

- (void)bmAddWeakReferenceContext:(BMWeakReferenceContext *)context {
    if (context != nil) {
        @synchronized (self) {
            NSMutableArray<BMWeakReferenceContext *> *contexts = [self _bmWeakReferenceContexts];
            if (contexts == nil) {
                contexts = [NSMutableArray new];
                objc_setAssociatedObject(self, kBMWeakReferenceContextsKey, contexts, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            }
            [contexts addObject:context];
        }
    }
}

- (void)bmRemoveWeakReferenceContexts {
    @synchronized (self) {
        [self._bmWeakReferenceContexts removeAllObjects];
    }
}

- (void)bmRemoveWeakReferenceContext:(BMWeakReferenceContext *)context {
    @synchronized (self) {
        [self._bmWeakReferenceContexts removeObjectIdenticalTo:context];
    }
}

- (void)bmRemoveWeakReferenceContextsWithPredicate:(BOOL (^)(BMWeakReferenceContext *))predicate {
    @synchronized (self) {
        [self._bmWeakReferenceContexts bmRemoveObjectsWithPredicate:predicate];
    }
}

- (BOOL)bmHasWeakReferenceContextWithPredicate:(BOOL (^)(BMWeakReferenceContext *))predicate {
    @synchronized (self) {
        return [self._bmWeakReferenceContexts bmFirstObjectWithPredicate:predicate] != nil;
    }
}

@end

@implementation BMWeakReferenceRegistry {
}

BM_SYNTHESIZE_DEFAULT_SINGLETON

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

- (void)registerReference:(id)reference forOwner:(id)owner withCleanupBlock:(BMWeakReferenceCleanupBlock)cleanup {
    if (reference && cleanup) {
        if (owner == nil) {
            owner = self;
        }
        BMWeakReferenceContext *context = [BMWeakReferenceContext new];
        context.owner = owner;
        context.cleanupBlock = cleanup;
        [reference bmAddWeakReferenceContext:context];
    }
}

- (void)deregisterReference:(id)reference forOwner:(id)owner {
    if (reference) {
        [reference bmRemoveWeakReferenceContextsWithPredicate:^BOOL(BMWeakReferenceContext *context) {
            return (owner == nil || context.owner == owner);
        }];
    }
}

- (BOOL)hasRegisteredReference:(id)reference forOwner:(id)owner {
    BOOL ret = NO;
    if (reference) {
        ret = [reference bmHasWeakReferenceContextWithPredicate:^BOOL(BMWeakReferenceContext *context) {
            return (owner == nil || context.owner == owner);
        }];
    }
    return ret;
}

@end


text:
/*
* jQuery has some limitations to run on Node.js. Therefore, was extracted only
* some core functions to use on this example.
*/
exports.jQuery = {
	each: function( object, callback, args ) {
		var name, i = 0,
			length = object.length,
			isObj = length === undefined || this.isFunction(object);

		if ( args ) {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.apply( object[ name ], args ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.apply( object[ i++ ], args ) === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
						break;
					}
				}
			} else {
				for ( var value = object[0];
					i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
			}
		}

		return object;
	},

	extend: function() {
		var target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false,
			options;

		if (typeof target === 'boolean') {
			deep = target;
			target = arguments[1] || {};
			i = 2;
		}

		if (typeof target !== 'object' && !isFunction(target)) {
			target = {};
		}

		if (length == i) {
			target = this;
			--i;
		}

		for (; i < length; i++) {
			if ((options = arguments[i]) != null) {
				for (var name in options) {
					var src = target[name],
						copy = options[name];

					if (target === copy) {
						continue;
					}

					if (deep && copy && typeof copy === 'object' && !copy.nodeType) {
						target[name] = apply(
							deep,
							src || (copy.length != null ? [] : {}),
							copy
						);
					}

					else if (copy !== undefined) {
						target[name] = copy;
					}

				}
			}
		}

		return target;
	},

	isFunction: function( obj ) {
		return Object.prototype.toString.call(obj) === "[object Function]";
	},

	substitute: function(template, hashMap) {
		var EMPTY_STRING = '';

	    this.each(hashMap, function(key, val) {
			var regex = new RegExp('\{' + key + '\}', 'g');

			template = (template || EMPTY_STRING).replace(regex, val);
		});

		return template;
	}
};


text:
yum -y install fuse-libs net-tools
mkdir -p /mnt/vmware
mount -o loop /home/vagrant/linux.iso /mnt/vmware

cd /tmp
tar xzf /mnt/vmware/VMwareTools-*.tar.gz

umount /mnt/vmware
rm -fr /home/vagrant/linux.iso

/tmp/vmware-tools-distrib/vmware-install.pl -d
rm -fr /tmp/vmware-tools-distrib


text:
/**
 * @module ol/format/TextFeature
 */
import {inherits} from '../index.js';
import FeatureFormat from '../format/Feature.js';
import FormatType from '../format/FormatType.js';

/**
 * @classdesc
 * Abstract base class; normally only used for creating subclasses and not
 * instantiated in apps.
 * Base class for text feature formats.
 *
 * @constructor
 * @abstract
 * @extends {ol.format.Feature}
 */
const TextFeature = function() {
  FeatureFormat.call(this);
};

inherits(TextFeature, FeatureFormat);

/**
 * @param {Document|Node|Object|string} source Source.
 * @return {string} Text.
 */
function getText(source) {
  if (typeof source === 'string') {
    return source;
  } else {
    return '';
  }
}

/**
 * @inheritDoc
 */
TextFeature.prototype.getType = function() {
  return FormatType.TEXT;
};

/**
 * @inheritDoc
 */
TextFeature.prototype.readFeature = function(source, opt_options) {
  return this.readFeatureFromText(getText(source), this.adaptOptions(opt_options));
};

/**
 * @abstract
 * @param {string} text Text.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {ol.Feature} Feature.
 */
TextFeature.prototype.readFeatureFromText = function(text, opt_options) {};

/**
 * @inheritDoc
 */
TextFeature.prototype.readFeatures = function(source, opt_options) {
  return this.readFeaturesFromText(getText(source), this.adaptOptions(opt_options));
};

/**
 * @abstract
 * @param {string} text Text.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {Array.<ol.Feature>} Features.
 */
TextFeature.prototype.readFeaturesFromText = function(text, opt_options) {};

/**
 * @inheritDoc
 */
TextFeature.prototype.readGeometry = function(source, opt_options) {
  return this.readGeometryFromText(getText(source), this.adaptOptions(opt_options));
};

/**
 * @abstract
 * @param {string} text Text.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {ol.geom.Geometry} Geometry.
 */
TextFeature.prototype.readGeometryFromText = function(text, opt_options) {};

/**
 * @inheritDoc
 */
TextFeature.prototype.readProjection = function(source) {
  return this.readProjectionFromText(getText(source));
};

/**
 * @param {string} text Text.
 * @protected
 * @return {ol.proj.Projection} Projection.
 */
TextFeature.prototype.readProjectionFromText = function(text) {
  return this.defaultDataProjection;
};

/**
 * @inheritDoc
 */
TextFeature.prototype.writeFeature = function(feature, opt_options) {
  return this.writeFeatureText(feature, this.adaptOptions(opt_options));
};

/**
 * @abstract
 * @param {ol.Feature} feature Features.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {string} Text.
 */
TextFeature.prototype.writeFeatureText = function(feature, opt_options) {};

/**
 * @inheritDoc
 */
TextFeature.prototype.writeFeatures = function(features, opt_options) {
  return this.writeFeaturesText(features, this.adaptOptions(opt_options));
};

/**
 * @abstract
 * @param {Array.<ol.Feature>} features Features.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {string} Text.
 */
TextFeature.prototype.writeFeaturesText = function(features, opt_options) {};

/**
 * @inheritDoc
 */
TextFeature.prototype.writeGeometry = function(geometry, opt_options) {
  return this.writeGeometryText(geometry, this.adaptOptions(opt_options));
};

/**
 * @abstract
 * @param {ol.geom.Geometry} geometry Geometry.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {string} Text.
 */
TextFeature.prototype.writeGeometryText = function(geometry, opt_options) {};
export default TextFeature;


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
AssetTrackerTutorial::Application.initialize!

# Set Haml Options:
Haml::Template.options[:format] = :xhtml


text:
project: waveletf.cpp Makefile
	g++ waveletf.cpp NMath.cpp -I. -o waveletf
clean:
	rm waveletf


text:
"""Common settings and globals."""

from os.path import abspath, basename, dirname, join, normpath
from sys import path

### Conceptum configuration. ###
CI_COURSE = 'CS 2'
###

########## PATH CONFIGURATION
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))

# Absolute filesystem path to the top-level project folder:
SITE_ROOT = dirname(DJANGO_ROOT)

# Site name:
SITE_NAME = basename(DJANGO_ROOT)

# Add our project to our pythonpath, this way we don't need to type our project
# name in our dotted import paths:
path.append(DJANGO_ROOT)
########## END PATH CONFIGURATION

########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = False

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION

########## MANAGER CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = (
    ('Conceptum Admin', 'conceptum@cs.swarthmore.edu'),
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
########## END MANAGER CONFIGURATION

########## DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
########## END DATABASE CONFIGURATION

########## GENERAL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
TIME_ZONE = 'America/New_York'

# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'

# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
########## END GENERAL CONFIGURATION

########## MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
########## END MEDIA CONFIGURATION

########## STATIC FILE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
    normpath(join(SITE_ROOT, 'static')),
)

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
########## END STATIC FILE CONFIGURATION

########## SECRET CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Note: This key should only be used for development and testing.
SECRET_KEY = r"o)qtx54-c1obzwm3qt!f5yo*_*d*+f*mg+061v!ftcb%*d39d%"
########## END SECRET CONFIGURATION

########## SITE CONFIGURATION
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
########## END SITE CONFIGURATION

########## FIXTURE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
    normpath(join(SITE_ROOT, 'fixtures')),
)
########## END FIXTURE CONFIGURATION

########## TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',

    #allauth
    'allauth.account.context_processors.account',
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
TEMPLATE_DIRS = (
    normpath(join(SITE_ROOT, 'templates')),
)
########## END TEMPLATE CONFIGURATION

########## MIDDLEWARE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes
MIDDLEWARE_CLASSES = (
    # Default Django middleware.
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    #'reversion.middleware.RevisionMiddleware',
)
########## END MIDDLEWARE CONFIGURATION

########## URL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = '%s.urls' % SITE_NAME
########## END URL CONFIGURATION

########## APP CONFIGURATION
DJANGO_APPS = (
    # Default Django apps:
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.formtools',

    # Useful template tags:
    # 'django.contrib.humanize',

    # Admin panel and documentation:
    'django.contrib.admin',
    # 'django.contrib.admindocs',

    'reversion',

    # order necessary to force django_comments to inherit threaded templates
    'threadedcomments',
    'django_comments',

    'authtools',
    'allauth',
    'allauth.account',

    # Used as a tree structure for CI Stage 1
    'mptt',

    'django_enumfield',

)

# Apps specific for this project go here.
LOCAL_APPS = (
    'cidev',
    'custom_auth',
    'exam',
    'interviews',
    'profiles',
    'custom_auth',
    'cistage1',
    'nodemanager',
    'ranking',
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS
########## END APP CONFIGURATION

########## LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
########## END LOGGING CONFIGURATION

########## WSGI CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME
########## END WSGI CONFIGURATION

########## SOUTH CONFIGURATION
# See: http://south.readthedocs.org/en/latest/installation.html#configuring-your-django-installation
INSTALLED_APPS += (
    # Database migration helpers:
    'south',
)
# Don't need to use South when setting up a test database.
SOUTH_TESTS_MIGRATE = False
########## END SOUTH CONFIGURATION

########## USER CONFIGURATION
AUTH_USER_MODEL = 'authtools.User'

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)
########## END USER CONFIGURATION

########## ALLAUTH CONFIGURATION
#LOGIN_REDIRECT_URL = '/'
ACCOUNT_ADAPTER = "custom_auth.adapter.AccountAdapter"
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_SESSION_REMEMBER = False
ACCOUNT_SIGNUP_FORM_CLASS = 'custom_auth.forms.SignupForm'
ACCOUNT_USER_DISPLAY = lambda user: user.get_full_name()
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "mandatory"

SOCIALACCOUNT_PROVIDERS = None
########## END ALLAUTH CONFIGURATION

########## COMMENT CONFIGURATION
COMMENTS_APP = 'threadedcomments'
########## END COMMENT CONFIGURATION


text:
package com.neovisionaries.animation.interpolator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static com.neovisionaries.animation.interpolator.LinearInterpolator.LINEAR_INTERPOLATOR;

/**
 * A composite interpolator.
 *
 *

 * This class combines multiple interpolators.
 *

 *
 *

 * When {@link #doInterpolate(float[], int, float[], int, int, float, float[], int) doInterpolator}
 * method is called, {@link Interpolator#interpolate(float[], int, float[], int, int, float, float[], int)
 * interpolator} method of each registered interpolator is executed one by one and
 * the calculated values are accumulated. The logic of the accumulation is implemented
 * in {@link #accumulate(float[], float, float[], int) accumulate} method and the method
 * can be overridden if necessary.
 *

 *
 *

 * If no interpolator is registered when {@link
 * #doInterpolate(float[], int, float[], int, int, float, float[], int) doInterpolator} is called,
 * {@code CompositeInterpolator} behaves in the same way as {@link LinearInterpolator}.
 *

 *
 *

 *
 * {@link Interpolator} interpolatorA = ......;
 * {@link Interpolator} interpolatorB = ......;
 *
 * {@link CompositeInterpolator} ci = new {@link #CompositeInterpolator()};
 * {@link CompositeInterpolator.Entry Entry} entryA = ci.{@link #add(Interpolator, float) add}(interpolatorA, 1.0F);
 * {@link CompositeInterpolator.Entry Entry} entryB = ci.{@link #add(Interpolator, float) add}(interpolatorB, 0.0F);
 *
 * for (int i = 0; i <= 10; ++i)
 * {
 *     // Change weights.
 *     entryA.{@link CompositeInterpolator.Entry#setWeight(float) setWeight}((10 - i) * 0.1F);
 *     entryB.{@link CompositeInterpolator.Entry#setWeight(float) setWeight}(      i  * 0.1F);
 *
 *     // Use the composite interpolator.
 *     ......
 * }
 *

 *
 * @author Takahiko Kawasaki
 */
public class CompositeInterpolator extends InterpolatorBase
{
    /**
     * The default interpolator used when no interpolator is registered.
     */
    private static final Interpolator DEFAULT_INTERPOLATOR = LINEAR_INTERPOLATOR;

    /**
     * Interpolators registered into this {@code CompositeInterpolator}.
     */
    private List<Entry> entryList;

    /**
     * A pair of {@link Interpolator} and weight.
     *
     * @author Takahiko Kawasaki
     */
    public static class Entry
    {
        private final Interpolator interpolator;
        private float weight;

        /**
         * A constructor with {@link Interpolator} and weight.
         *
         * @param interpolator
         * @param weight
         *
         * @throws IllegalArgumentException
         *         {@code interpolator} is null.
         */
        public Entry(Interpolator interpolator, float weight)
        {
            if (interpolator == null)
            {
                throw new IllegalArgumentException("interpolator is null");
            }

            this.interpolator = interpolator;
            this.weight = weight;
        }

        /**
         * Get the interpolator.
         *
         * @return
         *         The interpolator given to the {@link
         *         CompositeInterpolator.Entry#CompositeInterpolator.Entry(Interpolator, float)
         *         constructor}.
         */
        public Interpolator getInterpolator()
        {
            return interpolator;
        }

        /**
         * Get the weight.
         *
         * @return
         *         Weight.
         */
        public float getWeight()
        {
            return weight;
        }

        /**
         * Set the weight.
         *
         * @param weight
         */
        public void setWeight(float weight)
        {
            this.weight = weight;
        }
    }

    @Override
    protected final void doInterpolate(
            float[] from, int fromIndex, float[] to, int toIndex,
            int count, float ratio, float[] output, int outputIndex)
    {
        if (entryList == null)
        {
            // No interpolator is registered, so use the default interpolator.
            DEFAULT_INTERPOLATOR.interpolate(
                    from, fromIndex, to, toIndex, count, ratio, output, outputIndex);

            // Interpolation was done.
            return;
        }

        // Clear the output array before starting to accumulate interpolated values.
        Arrays.fill(output, 0, count, 0.0F);

        // A work buffer to hold one interpolated value.
        float[] work = new float[count];

        // For each interpolator.
        for (Entry entry : entryList)
        {
            // Interpolator.
            Interpolator interpolator = entry.getInterpolator();

            // Weight.
            float weight = entry.getWeight();

            // Clear the work buffer.
            Arrays.fill(work, 0.0F);

            // Let the interpolator interpolate and store the output to 'work'.
            interpolator.interpolate(
                    from, fromIndex, to, toIndex, count, ratio, work, 0);

            // Accumulate the interpolated value and update the output array.
            accumulate(work, weight, output, outputIndex);
        }
    }

    /**
     * Accumulate values calculated by registered interpolators.
     *
     *

     * The default implementation of this method does the following.
     *

     *
     *

     *
     * for (int i = 0; i < value.length; ++i)
     * {
     *     output[outputIndex + i] += value[i] * weight;
     * }
     *

     *
     *

     * The above implementation assumes that the possible range of each weight
     * is in between 0.0F (no influence rate) and 1.0F (100%) and that the sum
     * of all weights is 1.0F.
     *

     *
     * @param value
     *         An interpolated value by an interpolator.
     *
     * @param weight
     *         A weight value specified when the interpolator was registered
     *         by {@link #add(Interpolator, float) add} method.
     *
     * @param output
     *         The {@code output} argument passed to {@link #doInterpolate(float[],
     *         int, float[], int, int, float, float[], int) doInterpolate} method.
     *
     * @param outputIndex
     *         The {@code outputIndex} argument passed to {@link #doInterpolate(float[],
     *         int, float[], int, int, float, float[], int) doInterpolate} method.
     */
    protected void accumulate(float[] value, float weight, float[] output, int outputIndex)
    {
        // The default accumulation behavior.
        for (int i = 0; i < value.length; ++i)
        {
            output[outputIndex + i] += value[i] * weight;
        }
    }

    /**
     * Add a pair of interpolator and weight.
     *
     *

     * The way that the weight is used depends on the implementation of
     * {@link #accumulate(float[], float, float[], int) accumulate} method.
     *

     *
     * @param interpolator
     *         An interpolator.
     *
     * @param weight
     *         Weight given to the interpolator.
     *
     * @return
     *         An {@link CompositeInterpolator.Entry Entry} instance that
     *         represents the pair of the interpolator and the weight.
     *         By using the instance, the weight can be changed after the
     *         interpolator was added to this {@code CompositeInterpolator}.
     *
     * @throws IllegalArgumentException
     *         {@code interpolator} is null.
     */
    public Entry add(Interpolator interpolator, float weight)
    {
        if (interpolator == null)
        {
            throw new IllegalArgumentException("interpolator is null");
        }

        Entry entry = new Entry(interpolator, weight);

        return add(entry);
    }

    /**
     * Add a pair of interpolator and weight.
     *
     * @param entry
     *
     * @return
     *         The given entry.
     *
     * @throws IllegalArgumentException
     *         The given argument is null.
     */
    public Entry add(Entry entry)
    {
        if (entry == null)
        {
            throw new IllegalArgumentException("entry is null");
        }

        if (entryList == null)
        {
            entryList = new ArrayList<Entry>();
        }

        entryList.add(entry);

        return entry;
    }

    /**
     * Remove a pair of interpolator and weight.
     *
     * @param entry
     *         A pair to remove.
     */
    public void remove(Entry entry)
    {
        if (entry == null)
        {
            return;
        }

        if (entryList == null)
        {
            return;
        }

        entryList.remove(entry);

        if (entryList.size() == 0)
        {
            entryList = null;
        }
    }

    /**
     * Remove all pairs of interpolator and weight.
     */
    public void removeAll()
    {
        entryList = null;
    }

    /**
     * Get a pair of interpolator and weight at the specified index.
     *
     * @param index
     *         The position of the pair.
     *
     * @return
     *         A pair of interpolator and weight at the specified index.
     *
     * @throws IndexOutOfBoundsException
     */
    public Entry get(int index)
    {
        if (entryList == null || index < 0 || entryList.size() <= index)
        {
            throw new IndexOutOfBoundsException();
        }

        return entryList.get(index);
    }

    /**
     * Get an immutable list of all pairs of interpolator and weight.
     *
     * @return
     *         A list of all pairs of interpolator and weight. If no
     *         pair is registered, an empty list is returned.
     */
    public List<Entry> getAll()
    {
        if (entryList == null)
        {
            // Immutable empty list.
            return Collections.emptyList();
        }

        return Collections.unmodifiableList(entryList);
    }
}


text:
using Ripoff_Of_Kenov.Infrastructure;
using System.ComponentModel.DataAnnotations;

namespace Ripoff_Of_Kenov.Data
{
    public class Post
    {
        public int Id { get; set; }
        [Required]
        [MaxLength(25)]
        public string Title { get; set; }
        [Required]
        [Url]
        [ImageUrl]
        public string ImageUrl { get; set; }
        [MaxLength(50)]
        public string Description { get; set; }
        [Required]
        public string OwnerId { get; set; }

        public virtual User Owner { get; set; }

    }
}


text:
The unit test of this project is the same as `examples` of this project and this
is just a Matlab unit tests wrapper. Please read

```
$CBIG_CODE_DIR/stable_projects/disorder_subtypes/Sun2019_ADJointFactors/examples/README.md
```


text:
package com.ctrip.framework.cs.util;

/**
 * Created by jiang.j on 2016/4/7.
 */

/**
 * Internal convenience methods that help a method or constructor check whether it was invoked
 * correctly. Please notice that this should be considered an internal implementation detail, and
 * it is subject to change without notice.
 */
public final class Preconditions {
  private Preconditions() {
  }

  /**
   * Ensures the object reference is not null.
   */
  public static <T> T checkNotNull(T obj, String name) {
    if (obj == null) {
      String msg = String.format("parameter '%s' cannot be null", name);
      throw new NullPointerException(msg);
    }
    return obj;
  }

  /**
   * Ensures the truth of an expression involving one or more parameters to the
   * calling method.
   *
   * @param expression a boolean expression
   * @throws IllegalArgumentException if {@code expression} is false
   */
  public static void checkArgument(
      boolean expression, String errorMessage) {
    if (!expression) {
      throw new IllegalArgumentException(errorMessage);
    }
  }
}


text:
package org.elasticsearch.indices.recovery;

import org.apache.lucene.store.RateLimiter;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionListenerResponseHandler;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.index.seqno.ReplicationTracker;
import org.elasticsearch.index.seqno.RetentionLeases;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetaData;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.EmptyTransportResponseHandler;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportService;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;

public class RemoteRecoveryTargetHandler implements RecoveryTargetHandler {

    private final TransportService transportService;
    private final long recoveryId;
    private final ShardId shardId;
    private final DiscoveryNode targetNode;
    private final RecoverySettings recoverySettings;

    private final TransportRequestOptions translogOpsRequestOptions;
    private final TransportRequestOptions fileChunkRequestOptions;

    private final AtomicLong bytesSinceLastPause = new AtomicLong();

    private final Consumer<Long> onSourceThrottle;

    public RemoteRecoveryTargetHandler(long recoveryId, ShardId shardId, TransportService transportService,
                                       DiscoveryNode targetNode, RecoverySettings recoverySettings, Consumer<Long> onSourceThrottle) {
        this.transportService = transportService;
        this.recoveryId = recoveryId;
        this.shardId = shardId;
        this.targetNode = targetNode;
        this.recoverySettings = recoverySettings;
        this.onSourceThrottle = onSourceThrottle;
        this.translogOpsRequestOptions = TransportRequestOptions.builder()
                .withType(TransportRequestOptions.Type.RECOVERY)
                .withTimeout(recoverySettings.internalActionLongTimeout())
                .build();
        this.fileChunkRequestOptions = TransportRequestOptions.builder()
                // we are saving the cpu for other things
                .withType(TransportRequestOptions.Type.RECOVERY)
                .withTimeout(recoverySettings.internalActionTimeout())
                .build();

    }

    @Override
    public void prepareForTranslogOperations(boolean fileBasedRecovery, int totalTranslogOps, ActionListener<Void> listener) {
        transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.PREPARE_TRANSLOG,
            new RecoveryPrepareForTranslogOperationsRequest(recoveryId, shardId, totalTranslogOps, fileBasedRecovery),
            TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionTimeout()).build(),
            new ActionListenerResponseHandler<>(ActionListener.wrap(r -> listener.onResponse(null), listener::onFailure),
                in -> TransportResponse.Empty.INSTANCE, ThreadPool.Names.GENERIC));
    }

    @Override
    public void finalizeRecovery(final long globalCheckpoint, final ActionListener<Void> listener) {
        transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.FINALIZE,
            new RecoveryFinalizeRecoveryRequest(recoveryId, shardId, globalCheckpoint),
            TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionLongTimeout()).build(),
            new ActionListenerResponseHandler<>(ActionListener.wrap(r -> listener.onResponse(null), listener::onFailure),
                in -> TransportResponse.Empty.INSTANCE, ThreadPool.Names.GENERIC));
    }

    @Override
    public void ensureClusterStateVersion(long clusterStateVersion) {
        transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.WAIT_CLUSTERSTATE,
            new RecoveryWaitForClusterStateRequest(recoveryId, shardId, clusterStateVersion),
            TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionLongTimeout()).build(),
                EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
    }

    @Override
    public void handoffPrimaryContext(final ReplicationTracker.PrimaryContext primaryContext) {
        transportService.submitRequest(
                targetNode,
                PeerRecoveryTargetService.Actions.HANDOFF_PRIMARY_CONTEXT,
                new RecoveryHandoffPrimaryContextRequest(recoveryId, shardId, primaryContext),
                TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionTimeout()).build(),
                EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
    }

    @Override
    public void indexTranslogOperations(
            final List<Translog.Operation> operations,
            final int totalTranslogOps,
            final long maxSeenAutoIdTimestampOnPrimary,
            final long maxSeqNoOfDeletesOrUpdatesOnPrimary,
            final RetentionLeases retentionLeases,
            final ActionListener<Long> listener) {
        final RecoveryTranslogOperationsRequest request = new RecoveryTranslogOperationsRequest(
                recoveryId,
                shardId,
                operations,
                totalTranslogOps,
                maxSeenAutoIdTimestampOnPrimary,
                maxSeqNoOfDeletesOrUpdatesOnPrimary,
                retentionLeases);
        transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.TRANSLOG_OPS, request, translogOpsRequestOptions,
            new ActionListenerResponseHandler<>(ActionListener.wrap(r -> listener.onResponse(r.localCheckpoint), listener::onFailure),
                RecoveryTranslogOperationsResponse::new, ThreadPool.Names.GENERIC));
    }

    @Override
    public void receiveFileInfo(List<String> phase1FileNames, List<Long> phase1FileSizes, List<String> phase1ExistingFileNames,
                                List<Long> phase1ExistingFileSizes, int totalTranslogOps) {

        RecoveryFilesInfoRequest recoveryInfoFilesRequest = new RecoveryFilesInfoRequest(recoveryId, shardId,
                phase1FileNames, phase1FileSizes, phase1ExistingFileNames, phase1ExistingFileSizes, totalTranslogOps);
        transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.FILES_INFO, recoveryInfoFilesRequest,
                TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionTimeout()).build(),
                EmptyTransportResponseHandler.INSTANCE_SAME).txGet();

    }

    @Override
    public void cleanFiles(int totalTranslogOps, Store.MetadataSnapshot sourceMetaData) throws IOException {
        transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.CLEAN_FILES,
                new RecoveryCleanFilesRequest(recoveryId, shardId, sourceMetaData, totalTranslogOps),
                TransportRequestOptions.builder().withTimeout(recoverySettings.internalActionTimeout()).build(),
                EmptyTransportResponseHandler.INSTANCE_SAME).txGet();
    }

    @Override
    public void writeFileChunk(StoreFileMetaData fileMetaData, long position, BytesReference content,
                               boolean lastChunk, int totalTranslogOps, ActionListener<Void> listener) {
        // Pause using the rate limiter, if desired, to throttle the recovery
        final long throttleTimeInNanos;
        // always fetch the ratelimiter - it might be updated in real-time on the recovery settings
        final RateLimiter rl = recoverySettings.rateLimiter();
        if (rl != null) {
            long bytes = bytesSinceLastPause.addAndGet(content.length());
            if (bytes > rl.getMinPauseCheckBytes()) {
                // Time to pause
                bytesSinceLastPause.addAndGet(-bytes);
                try {
                    throttleTimeInNanos = rl.pause(bytes);
                    onSourceThrottle.accept(throttleTimeInNanos);
                } catch (IOException e) {
                    throw new ElasticsearchException("failed to pause recovery", e);
                }
            } else {
                throttleTimeInNanos = 0;
            }
        } else {
            throttleTimeInNanos = 0;
        }

        transportService.submitRequest(targetNode, PeerRecoveryTargetService.Actions.FILE_CHUNK,
            new RecoveryFileChunkRequest(recoveryId, shardId, fileMetaData, position, content, lastChunk,
                totalTranslogOps,
                /* we send estimateTotalOperations with every request since we collect stats on the target and that way we can
                 * see how many translog ops we accumulate while copying files across the network. A future optimization
                 * would be in to restart file copy again (new deltas) if we have too many translog ops are piling up.
                 */
                throttleTimeInNanos), fileChunkRequestOptions, new ActionListenerResponseHandler<>(
                    ActionListener.wrap(r -> listener.onResponse(null), listener::onFailure), in -> TransportResponse.Empty.INSTANCE));
    }

}


text:
<?php
namespace CrudGenerator\Tests\General\View\Helpers\TextFactory;

use CrudGenerator\View\Helpers\TextFactory;

class GetInstanceTest extends \PHPUnit_Framework_TestCase
{
    public function testInstance()
    {
        $this->assertInstanceOf(
            'CrudGenerator\View\Helpers\Text',
            TextFactory::getInstance()
        );
    }
}


text:
'use strict';

const smoochBot = require('smooch-bot');
const MemoryLock = smoochBot.MemoryLock;
const SmoochApiStore = smoochBot.SmoochApiStore;
const SmoochApiBot = smoochBot.SmoochApiBot;
const StateMachine = smoochBot.StateMachine;
const app = require('../app');
const script = require('../script');
const SmoochCore = require('smooch-core');
const jwt = require('../jwt');

const name = 'SmoochBot';
const avatarUrl = 'https://s.gravatar.com/avatar/f91b04087e0125153623a3778e819c0a?s=80';
const store = new SmoochApiStore({
    jwt
});
const lock = new MemoryLock();
const webhookTriggers = ['message:appUser', 'postback'];

function createWebhook(smoochCore, target) {
    return smoochCore.webhooks.create({
        target,
        triggers: webhookTriggers
    })
        .then((res) => {
            console.log('Smooch webhook created with target', res.webhook.target);
        })
        .catch((err) => {
            console.error('Error creating Smooch webhook:', err);
            console.error(err.stack);
        });
}

function updateWebhook(smoochCore, existingWebhook) {
    return smoochCore.webhooks.update(existingWebhook._id, {
        triggers: webhookTriggers
    })
        .then((res) => {
            console.log('Smooch webhook updated with missing triggers', res.webhook.target);
        })
        .catch((err) => {
            console.error('Error updating Smooch webhook:', err);
            console.error(err.stack);
        });
}

// Create a webhook if one doesn't already exist
if (process.env.SERVICE_URL) {
    const target = process.env.SERVICE_URL.replace(/\/$/, '') + '/webhook';
    const smoochCore = new SmoochCore({
        jwt
    });
    smoochCore.webhooks.list()
        .then((res) => {
            const existingWebhook = res.webhooks.find((w) => w.target === target);

            if (!existingWebhook) {
                return createWebhook(smoochCore, target);
            }

            const missingTriggers = webhookTriggers.every((t) => {
                return existingWebhook.triggers.indexOf(t) !== -1;
            });

            if (!missingTriggers) {
                updateWebhook(smoochCore, existingWebhook);
            }
        });
}

function createBot(appUser) {
    const userId = appUser.userId || appUser._id;
    return new SmoochApiBot({
        name,
        avatarUrl,
        lock,
        store,
        userId
    });
}

function handleMessages(req, res) {
    const messages = req.body.messages.reduce((prev, current) => {
        if (current.role === 'appUser') {
            prev.push(current);
        }
        return prev;
    }, []);

    if (messages.length === 0) {
        return res.end();
    }

    const stateMachine = new StateMachine({
        script,
        bot: createBot(req.body.appUser)
    });

    stateMachine.receiveMessage(messages[0])
        .then(() => res.end())
        .catch((err) => {
            console.error('SmoochBot error:', err);
            console.error(err.stack);
            res.end();
        });
}

function handlePostback(req, res) {
    const postback = req.body.postbacks[0];
    if (!postback || !postback.action) {
        res.end();
    }

    createBot(req.body.appUser).say(`You said: ${postback.action.text} (payload was: ${postback.action.payload})`)
        .then(() => res.end());
}

app.post('/webhook', function(req, res, next) {
    const trigger = req.body.trigger;

    switch (trigger) {
        case 'message:appUser':
            handleMessages(req, res);
            break;

        case 'postback':
            handlePostback(req, res);
            break;

        default:
            console.log('Ignoring unknown webhook trigger:', trigger);
    }
});

var server = app.listen(process.env.PORT || 8000, function() {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Smooch Bot listening at http://%s:%s', host, port);
});


text:
package edu.wustl.common.query.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.cab2b.client.ui.query.IPathFinder;
import edu.wustl.cab2b.common.cache.AbstractEntityCache;
import edu.wustl.cab2b.server.path.PathFinder;
import edu.wustl.common.querysuite.metadata.associations.IInterModelAssociation;
import edu.wustl.common.querysuite.metadata.associations.IIntraModelAssociation;
import edu.wustl.common.querysuite.metadata.path.ICuratedPath;
import edu.wustl.common.querysuite.metadata.path.IPath;
import edu.wustl.common.util.logger.Logger;

// TODO: Auto-generated Javadoc
/**
 * This class is used to find all the possible paths between two entities.
 *
 * @author deepti_shelar
 * @author lalit_chand
 */
public class CommonPathFinder implements IPathFinder
{

	/** instance of PathFinder. */
	private static PathFinder pathFinder = null;

	/**
	 * Instantiates a new common path finder.
	 */
	public CommonPathFinder()
	{
		if (AbstractEntityCache.isCacheReady)
		{
			Connection connection = null;
			try
			{
				InitialContext initialContext = new InitialContext();
				Context env = (Context) initialContext.lookup("java:comp/env");
                String dsName = (String) env.lookup("DataSource");
                Logger.out.info("Data source name found: " + dsName);

                DataSource dataSource = (DataSource)initialContext.lookup(dsName);
                Logger.out.info("Data source found: " + dataSource);

				connection = dataSource.getConnection();
				Logger.out.info("Connection established: " + connection);

				pathFinder = PathFinder.getInstance(connection);
			}
			catch (NamingException e)
			{
				Logger.out.error("CommonPathFinder:", e);
				//TODO need to see how to handle exception
			}
			catch (SQLException e)
			{
				Logger.out.error("CommonPathFinder:", e);
				//TODO need to see how to handle exception
			}
			finally
			{
				try
				{
					if (connection != null)
					{
						connection.close();
					}
				}
				catch (SQLException e)
				{
					Logger.out.error("CommonPathFinder:", e);
				}
			}
		}
	}

	/**
	 * This method gets all the possible paths between two entities.
	 *
	 * @param srcEntity Source Entity.
	 * @param destEntity Destination Entity.
	 *
	 * @return List of all possible paths between source and destination entity.
	 */
	public List<IPath> getAllPossiblePaths(EntityInterface srcEntity, EntityInterface destEntity)
	{
		//PathFinder pathFinder= getPathFinderInstance();
		return pathFinder.getAllPossiblePaths(srcEntity, destEntity);
	}

	/**
	 * This method gets all the paths for query.
	 *
	 * @param srcEntity Source Entity.
	 * @param destEntity Destination Entity.
	 *
	 * @return All the paths
	 */
	public List<IPath> getAllPathsForQuery(EntityInterface srcEntity, EntityInterface destEntity)
	{
		//PathFinder pathFinder= getPathFinderInstance();
		return pathFinder.getAllPathsForQuery(srcEntity, destEntity);
	}

	/**
	 * Gets the path for associations.
	 *
	 * @param intraModelAssociationList List of intramodel association
	 *
	 * @return IPath object
	 */
	public IPath getPathForAssociations(List<IIntraModelAssociation> intraModelAssociationList)
	{
		//PathFinder pathFinder = getPathFinderInstance();
		return pathFinder.getPathForAssociations(intraModelAssociationList);
	}

	/**
	 * Auto connect.
	 *
	 * @param entitySet Set of entities.
	 *
	 * @return Set of curated paths.
	 */
	public Set<ICuratedPath> autoConnect(Set<EntityInterface> entitySet)
	{
		return pathFinder.autoConnect(entitySet);
	}

	/**
	 * Gets the curated paths.
	 *
	 * @param srcEntity Source Entity.
	 * @param destEntity Destination Entity.
	 *
	 * @return Curated paths between srcEntity and destEntity.
	 */
	public Set<ICuratedPath> getCuratedPaths(EntityInterface srcEntity, EntityInterface destEntity)
	{
		return pathFinder.getCuratedPaths(srcEntity, destEntity);
	}

	/**
	 * Gets the inter model associations.
	 *
	 * @param arg0 arg0
	 *
	 * @return List of inter model associations.
	 */
	public List<IInterModelAssociation> getInterModelAssociations(Long arg0)
	{
		return pathFinder.getInterModelAssociations(arg0);
	}
}


text:
package org.yeastrc.xlink.www.lorikeet_dto;

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

/**
 *
 *
 */
public class LorikeetRootData {

	private int charge;
	private double precursorMz;

	/**
	 * Filename for display
	 */
	private String fileName;

	/**
	 * Scan Number
	 */
	private int scanNum;

	/**
     * Peptide Sequence
     */
	private String sequence;

	/**
	 * Each sublist is one peak with [<mz>,intensity]
	 */
	private List<List<Object>> peaks;

	/**
	 * Each sublist is one peak with [<mz>,intensity]
	 */
	private List<List<Object>> ms1peaks;

	/**
	 * Static Mods
	 */
	private List<LorikeetStaticMod> staticMods;

	/**
	 * Variable Mods / Dynamic Mods
	 */
	private List<LorikeetVariableMod> variableMods;

	private double ntermMod = 0; // additional mass to be added to the n-term
	private double ctermMod = 0; // additional mass to be added to the c-term

	/**
	 * Data for a Loop Link - Cross Links Project
	 */
	private LorikeetLoopLinkData loopLinkDataInputFormat;  //  Lorikeet internal object property name: loopLinkData

	/**
	 * Data for a Cross Link - Cross Links Project
	 */
	private LorikeetCrossLinkData crossLinkDataInputFormat;  //  Lorikeet internal object property name: crossLinkData

	/**
	 * Data for a Dimer - Cross Links Project
	 */
	private LorikeetDimerData dimerDataInputFormat;  //  Lorikeet will ignore this property, the setup JS code will handle this

	private String label;		// stable isotope label name

	/**
	 *
	 */
	private int height;

	private int width;

//	jpeak.add( peak.getMz() );
//	jpeak.add( peak.getIntensity() );
//
//	    private float mz;
//    private float intensity;

    /**
     * Add to "peaks" list
     * @param mz
     * @param intensity
     */
    public void addPeak( double mz, float intensity ) {

    	if ( peaks == null ) {

    		peaks = new ArrayList<List<Object>>();
    	}

    	List<Object> peakItem = new ArrayList<>();

    	peakItem.add( mz );
    	peakItem.add( intensity );

    	peaks.add( peakItem );
    }

    /**
     * Add to "ms1peaks" list
     * @param mz
     * @param intensity
     */
    public void addMs1Peak( double mz, float intensity ) {

    	if ( ms1peaks == null ) {

    		ms1peaks = new ArrayList<List<Object>>();
    	}

    	List<Object> peakItem = new ArrayList<>();

    	peakItem.add( mz );
    	peakItem.add( intensity );

    	ms1peaks.add( peakItem );
    }

	/**
	 * Each sublist is one peak with [<mz>,intensity]
	 * @return
	 */
	public List<List<Object>> getMs1peaks() {
		return ms1peaks;
	}

	/**
	 * Each sublist is one peak with [<mz>,intensity]
	 * @param ms1peaks
	 */
	public void setMs1peaks(List<List<Object>> ms1peaks) {
		this.ms1peaks = ms1peaks;
	}

	/**
	 * Data for a Loop Link - Input to Lorikeet Format - Cross Links Project
	 * @return
	 */
	public LorikeetLoopLinkData getLoopLinkDataInputFormat() {
		return loopLinkDataInputFormat;
	}

	/**
	 * Data for a Loop Link - Input to Lorikeet Format - Cross Links Project
	 * @param loopLinkDataInputFormat
	 */
	public void setLoopLinkDataInputFormat(
			LorikeetLoopLinkData loopLinkDataInputFormat) {
		this.loopLinkDataInputFormat = loopLinkDataInputFormat;
	}

	/**
	 * Data for a Cross Link - Cross Links Project
	 * @return
	 */
	public LorikeetCrossLinkData getCrossLinkDataInputFormat() {
		return crossLinkDataInputFormat;
	}
	/**
	 * Data for a Cross Link - Cross Links Project
	 * @param crossLinkDataInputFormat
	 */
	public void setCrossLinkDataInputFormat(
			LorikeetCrossLinkData crossLinkDataInputFormat) {
		this.crossLinkDataInputFormat = crossLinkDataInputFormat;
	}

	/**
	 * Filename for display
	 * @return
	 */
	public String getFileName() {
		return fileName;
	}

	/**Filename for display
	 *
	 * @param fileName
	 */
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

    /**
     * Scan Number
     * @return
     */
    public int getScanNum() {
		return scanNum;
	}

	/**
	 * Scan Number
	 * @param scanNum
	 */
	public void setScanNum(int scanNum) {
		this.scanNum = scanNum;
	}

	public int getCharge() {
		return charge;
	}

	public void setCharge(int charge) {
		this.charge = charge;
	}

	public double getPrecursorMz() {
		return precursorMz;
	}

	public void setPrecursorMz(double precursorMz) {
		this.precursorMz = precursorMz;
	}

	public String getSequence() {
		return sequence;
	}

	public void setSequence(String sequence) {
		this.sequence = sequence;
	}

	public List<LorikeetVariableMod> getVariableMods() {
		return variableMods;
	}

	public void setVariableMods(List<LorikeetVariableMod> variableMods) {
		this.variableMods = variableMods;
	}

	public List<LorikeetStaticMod> getStaticMods() {
		return staticMods;
	}

	public void setStaticMods(List<LorikeetStaticMod> staticMods) {
		this.staticMods = staticMods;
	}

	public List<List<Object>> getPeaks() {
		return peaks;
	}

	public void setPeaks(List<List<Object>> peaks) {
		this.peaks = peaks;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public LorikeetDimerData getDimerDataInputFormat() {
		return dimerDataInputFormat;
	}

	public void setDimerDataInputFormat(LorikeetDimerData dimerDataInputFormat) {
		this.dimerDataInputFormat = dimerDataInputFormat;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public double getNtermMod() {
		return ntermMod;
	}

	public void setNtermMod(double ntermMod) {
		this.ntermMod = ntermMod;
	}

	public double getCtermMod() {
		return ctermMod;
	}

	public void setCtermMod(double ctermMod) {
		this.ctermMod = ctermMod;
	}

}

//lorikeetOptions: Object
//charge: 0
//height: 500
//peaks: Array[15026]
//precursorMz: "927.475524902"
//sequence: "KPAVAVSSQQMESCR"
//variableMods: Array[0]
//width: 500


text:
package org.zaproxy.zap.extension.alert;

import java.awt.Component;
import java.util.Set;

import javax.swing.tree.DefaultTreeModel;

import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;

/**
 * A {@link PopupMenuItemAlert} that allows to refresh the Alerts tree (the UI tree is rebuilt from the model already set).
 *
 * @since 1.4.0
 */
public class PopupMenuAlertsRefresh extends PopupMenuItemAlert {

	private static final long serialVersionUID = 1L;

    public PopupMenuAlertsRefresh() {
        super(Constant.messages.getString("alerts.refresh.popup"), true);
	}

    @Override
    protected void performActions(Set<Alert> alerts) {
        ((DefaultTreeModel) getExtensionAlert().getAlertPanel().getTreeAlert().getModel()).reload();
    }

    @Override
    public boolean isEnableForComponent(Component invoker) {
        if (super.isEnableForComponent(invoker)) {
            setEnabled(true);
            return true;
        }
        return false;
    }

    @Override
    protected void performAction(Alert alert) {
        // Nothing to do.
    }

    @Override
    public boolean isSafe() {
        return true;
    }
}


text:
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]

[![npm badge][11]][1]

Gets the description of a Symbol. Handles `Symbol()` vs `Symbol('')` properly when possible.

## Example

```js
var getSymbolDescription = require('get-symbol-description');
var assert = require('assert');

assert(getSymbolDescription(Symbol()) === undefined);
assert(getSymbolDescription(Symbol('')) === ''); // or `undefined`, if in an engine that lacks name inference from concise method
assert(getSymbolDescription(Symbol('foo')) === 'foo');
assert(getSymbolDescription(Symbol.iterator) === 'Symbol.iterator');
```

## Tests
Simply clone the repo, `npm install`, and run `npm test`

[1]: https://npmjs.org/package/get-symbol-description
[2]: https://versionbadg.es/inspect-js/get-symbol-description.svg
[5]: https://david-dm.org/inspect-js/get-symbol-description.svg
[6]: https://david-dm.org/inspect-js/get-symbol-description
[7]: https://david-dm.org/inspect-js/get-symbol-description/dev-status.svg
[8]: https://david-dm.org/inspect-js/get-symbol-description#info=devDependencies
[11]: https://nodei.co/npm/get-symbol-description.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/get-symbol-description.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/get-symbol-description.svg
[downloads-url]: https://npm-stat.com/charts.html?package=get-symbol-description
[codecov-image]: https://codecov.io/gh/inspect-js/get-symbol-description/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/inspect-js/get-symbol-description/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/get-symbol-description
[actions-url]: https://github.com/inspect-js/get-symbol-description/actions