text:
package org.sat4j.minisat;

import org.sat4j.core.ASolverFactory;
import org.sat4j.minisat.constraints.MixedDataStructureDanielHT;
import org.sat4j.minisat.constraints.MixedDataStructureDanielWL;
import org.sat4j.minisat.constraints.MixedDataStructureSingleWL;
import org.sat4j.minisat.core.DataStructureFactory;
import org.sat4j.minisat.core.ICDCL;
import org.sat4j.minisat.core.IOrder;
import org.sat4j.minisat.core.SearchParams;
import org.sat4j.minisat.core.Solver;
import org.sat4j.minisat.learning.LimitedLearning;
import org.sat4j.minisat.learning.MiniSATLearning;
import org.sat4j.minisat.learning.NoLearningButHeuristics;
import org.sat4j.minisat.learning.PercentLengthLearning;
import org.sat4j.minisat.orders.PhaseCachingAutoEraseStrategy;
import org.sat4j.minisat.orders.RSATLastLearnedClausesPhaseSelectionStrategy;
import org.sat4j.minisat.orders.RSATPhaseSelectionStrategy;
import org.sat4j.minisat.orders.RandomWalkDecorator;
import org.sat4j.minisat.orders.VarOrderHeap;
import org.sat4j.minisat.restarts.ArminRestarts;
import org.sat4j.minisat.restarts.Glucose21Restarts;
import org.sat4j.minisat.restarts.LubyRestarts;
import org.sat4j.minisat.restarts.MiniSATRestarts;
import org.sat4j.minisat.restarts.NoRestarts;
import org.sat4j.opt.MinOneDecorator;
import org.sat4j.specs.ISolver;
import org.sat4j.tools.DimacsOutputSolver;
import org.sat4j.tools.ManyCore;
import org.sat4j.tools.OptToSatAdapter;
import org.sat4j.tools.StatisticsSolver;

/**
 * User friendly access to pre-constructed solvers.
 *
 * @author leberre
 */
public final class SolverFactory extends ASolverFactory<ISolver> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    // thread safe implementation of the singleton design pattern
    private static SolverFactory instance;

    /**
     * Private constructor. Use singleton method instance() instead.
     *
     * @see #instance()
     */
    private SolverFactory() {
        super();
    }

    private static synchronized void createInstance() {
        if (instance == null) {
            instance = new SolverFactory();
        }
    }

    /**
     * Access to the single instance of the factory.
     *
     * @return the singleton of that class.
     */
    public static SolverFactory instance() {
        if (instance == null) {
            createInstance();
        }
        return instance;
    }

    /**
     * @return a "default" "minilearning" solver learning clauses of size
     *         smaller than 10 % of the total number of variables with a heap
     *         based var order.
     */
    public static Solver<DataStructureFactory> newMiniLearningHeap() {
        return newMiniLearningHeap(new MixedDataStructureDanielWL());
    }

    public static ICDCL<DataStructureFactory> newMiniLearningHeapEZSimp() {
        Solver<DataStructureFactory> solver = newMiniLearningHeap();
        solver.setSimplifier(solver.SIMPLE_SIMPLIFICATION);
        return solver;
    }

    public static Solver<DataStructureFactory> newMiniLearningHeapExpSimp() {
        Solver<DataStructureFactory> solver = newMiniLearningHeap();
        solver.setSimplifier(solver.EXPENSIVE_SIMPLIFICATION);
        return solver;
    }

    public static Solver<DataStructureFactory> newMiniLearningHeapRsatExpSimp() {
        Solver<DataStructureFactory> solver = newMiniLearningHeapExpSimp();
        solver.setOrder(new VarOrderHeap(new RSATPhaseSelectionStrategy()));
        return solver;
    }

    public static Solver<DataStructureFactory> newMiniLearningHeapRsatExpSimpBiere() {
        Solver<DataStructureFactory> solver = newMiniLearningHeapRsatExpSimp();
        solver.setRestartStrategy(new ArminRestarts());
        solver.setSearchParams(new SearchParams(1.1, 100));
        return solver;
    }

    public static ICDCL<DataStructureFactory> newMiniLearningHeapRsatExpSimpLuby() {
        ICDCL<DataStructureFactory> solver = newMiniLearningHeapRsatExpSimp();
        solver.setRestartStrategy(new LubyRestarts(512));
        return solver;
    }

    public static ICDCL<DataStructureFactory> newGlucose21() {
        Solver<DataStructureFactory> solver = newMiniLearningHeapRsatExpSimp();
        solver.setRestartStrategy(new Glucose21Restarts());
        solver.setLearnedConstraintsDeletionStrategy(solver.glucose);
        return solver;
    }

    private static Solver<DataStructureFactory> newBestCurrentSolverConfiguration(
            DataStructureFactory dsf) {
        MiniSATLearning<DataStructureFactory> learning = new MiniSATLearning<DataStructureFactory>();
        Solver<DataStructureFactory> solver = new Solver<DataStructureFactory>(
                learning, dsf, new VarOrderHeap(
                        new RSATPhaseSelectionStrategy()), new ArminRestarts());
        solver.setSearchParams(new SearchParams(1.1, 100));
        solver.setSimplifier(solver.EXPENSIVE_SIMPLIFICATION);
        return solver;
    }

    /**
     *
     * @since 2.2
     */
    public static ICDCL<DataStructureFactory> newGreedySolver() {
        MiniSATLearning<DataStructureFactory> learning = new MiniSATLearning<DataStructureFactory>();
        Solver<DataStructureFactory> solver = new Solver<DataStructureFactory>(
                learning, new MixedDataStructureDanielWL(),
                new RandomWalkDecorator(new VarOrderHeap(
                        new RSATPhaseSelectionStrategy())), new NoRestarts());
        // solver.setSearchParams(new SearchParams(1.1, 100));
        solver.setSimplifier(solver.EXPENSIVE_SIMPLIFICATION);
        return solver;
    }

    /**
     * @since 2.2
     */
    public static ICDCL<DataStructureFactory> newDefaultAutoErasePhaseSaving() {
        ICDCL<DataStructureFactory> solver = newBestWL();
        solver.setOrder(new VarOrderHeap(new PhaseCachingAutoEraseStrategy()));
        return solver;
    }

    /**
     * @since 2.2.3
     */
    public static ICDCL<DataStructureFactory> newDefaultMS21PhaseSaving() {
        ICDCL<DataStructureFactory> solver = newBestWL();
        solver.setOrder(new VarOrderHeap(
                new RSATLastLearnedClausesPhaseSelectionStrategy()));
        return solver;
    }

    /**
     * @since 2.1
     */
    public static Solver<DataStructureFactory> newBestWL() {
        return newBestCurrentSolverConfiguration(new MixedDataStructureDanielWL());
    }

    /**
     *
     * @since 2.1
     */
    public static ICDCL<DataStructureFactory> newBestHT() {
        return newBestCurrentSolverConfiguration(new MixedDataStructureDanielHT());
    }

    /**
     *
     * @since 2.2
     */
    public static ICDCL<DataStructureFactory> newBest17() {
        Solver<DataStructureFactory> solver = newBestCurrentSolverConfiguration(new MixedDataStructureSingleWL());
        solver.setSimplifier(solver.EXPENSIVE_SIMPLIFICATION_WLONLY);
        solver.setLearnedConstraintsDeletionStrategy(solver.memory_based);
        LimitedLearning<DataStructureFactory> learning = new PercentLengthLearning<DataStructureFactory>(
                10);
        solver.setLearningStrategy(learning);
        return solver;
    }

    /**
     * @since 2.1
     */
    public static Solver<DataStructureFactory> newGlucose() {
        Solver<DataStructureFactory> solver = newBestWL();
        solver.setLearnedConstraintsDeletionStrategy(solver.glucose);
        solver.setRestartStrategy(new LubyRestarts(512));
        return solver;
    }

    /**
     * @param dsf
     *            a specific data structure factory
     * @return a default "minilearning" solver using a specific data structure
     *         factory, learning clauses of length smaller or equals to 10 % of
     *         the number of variables and a heap based VSIDS heuristics
     */
    public static Solver<DataStructureFactory> newMiniLearningHeap(
            DataStructureFactory dsf) {
        return newMiniLearning(dsf, new VarOrderHeap());
    }

    /**
     * @param dsf
     *            the data structure factory used to represent literals and
     *            clauses
     * @param order
     *            the heuristics
     * @return a SAT solver with learning limited to clauses of length smaller
     *         or equal to 10 percent of the total number of variables, the dsf
     *         data structure, the FirstUIP clause generator and order as
     *         heuristics.
     */
    public static Solver<DataStructureFactory> newMiniLearning(
            DataStructureFactory dsf, IOrder order) {
        // LimitedLearning<DataStructureFactory> learning = new
        // PercentLengthLearning<DataStructureFactory>(10);
        MiniSATLearning<DataStructureFactory> learning = new MiniSATLearning<DataStructureFactory>();
        Solver<DataStructureFactory> solver = new Solver<DataStructureFactory>(
                learning, dsf, order, new MiniSATRestarts());
        return solver;
    }

    /**
     * @return a default MiniLearning without restarts.
     */
    public static ICDCL<DataStructureFactory> newMiniLearningHeapEZSimpNoRestarts() {
        LimitedLearning<DataStructureFactory> learning = new PercentLengthLearning<DataStructureFactory>(
                10);
        Solver<DataStructureFactory> solver = new Solver<DataStructureFactory>(
                learning, new MixedDataStructureDanielWL(), new SearchParams(
                        Integer.MAX_VALUE), new VarOrderHeap(),
                new MiniSATRestarts());
        learning.setSolver(solver);
        solver.setSimplifier(solver.SIMPLE_SIMPLIFICATION);
        return solver;
    }

    /**
     * @return a default MiniLearning with restarts beginning at 1000 conflicts.
     */
    public static ICDCL<DataStructureFactory> newMiniLearningHeapEZSimpLongRestarts() {
        LimitedLearning<DataStructureFactory> learning = new PercentLengthLearning<DataStructureFactory>(
                10);
        Solver<DataStructureFactory> solver = new Solver<DataStructureFactory>(
                learning, new MixedDataStructureDanielWL(), new SearchParams(
                        1000), new VarOrderHeap(), new MiniSATRestarts());
        learning.setSolver(solver);
        solver.setSimplifier(solver.SIMPLE_SIMPLIFICATION);
        return solver;
    }

    /**
     * @return a SAT solver very close to the original MiniSAT sat solver.
     */
    public static Solver<DataStructureFactory> newMiniSATHeap() {
        return newMiniSATHeap(new MixedDataStructureDanielWL());
    }

    /**
     * @return a SAT solver very close to the original MiniSAT sat solver
     *         including easy reason simplification.
     */
    public static ICDCL<DataStructureFactory> newMiniSATHeapEZSimp() {
        Solver<DataStructureFactory> solver = newMiniSATHeap();
        solver.setSimplifier(solver.SIMPLE_SIMPLIFICATION);
        return solver;
    }

    public static ICDCL<DataStructureFactory> newMiniSATHeapExpSimp() {
        Solver<DataStructureFactory> solver = newMiniSATHeap();
        solver.setSimplifier(solver.EXPENSIVE_SIMPLIFICATION);
        return solver;
    }

    public static Solver<DataStructureFactory> newMiniSATHeap(
            DataStructureFactory dsf) {
        MiniSATLearning<DataStructureFactory> learning = new MiniSATLearning<DataStructureFactory>();
        Solver<DataStructureFactory> solver = new Solver<DataStructureFactory>(
                learning, dsf, new VarOrderHeap(), new MiniSATRestarts());
        learning.setDataStructureFactory(solver.getDSFactory());
        learning.setVarActivityListener(solver);
        return solver;
    }

    /**
     * @return MiniSAT with VSIDS heuristics, FirstUIP clause generator for
     *         backjumping but no learning.
     */
    public static ICDCL<MixedDataStructureDanielWL> newBackjumping() {
        NoLearningButHeuristics<MixedDataStructureDanielWL> learning = new NoLearningButHeuristics<MixedDataStructureDanielWL>();
        Solver<MixedDataStructureDanielWL> solver = new Solver<MixedDataStructureDanielWL>(
                learning, new MixedDataStructureDanielWL(), new VarOrderHeap(),
                new MiniSATRestarts());
        learning.setVarActivityListener(solver);
        return solver;
    }

    /**
     * @return a solver computing models with a minimum number of satisfied
     *         literals.
     */
    public static ISolver newMinOneSolver() {
        return new OptToSatAdapter(new MinOneDecorator(newDefault()));
    }

    /**
     * Default solver of the SolverFactory. This solver is meant to be used on
     * challenging SAT benchmarks.
     *
     * @return the best "general purpose" SAT solver available in the factory.
     * @see #defaultSolver() the same method, polymorphic, to be called from an
     *      instance of ASolverFactory.
     */
    public static ISolver newDefault() {
        return newGlucose21(); // newMiniLearningHeapRsatExpSimpBiere();
    }

    @Override
    public ISolver defaultSolver() {
        return newDefault();
    }

    /**
     * Small footprint SAT solver.
     *
     * @return a SAT solver suitable for solving small/easy SAT benchmarks.
     * @see #lightSolver() the same method, polymorphic, to be called from an
     *      instance of ASolverFactory.
     */
    public static ISolver newLight() {
        return newMiniLearningHeap();
    }

    @Override
    public ISolver lightSolver() {
        return newLight();
    }

    public static ISolver newDimacsOutput() {
        return new DimacsOutputSolver();
    }

    public static ISolver newStatistics() {
        return new StatisticsSolver();
    }

    public static ISolver newParallel() {
        return new ManyCore(newSAT(), newUNSAT(),
                newMiniLearningHeapRsatExpSimpLuby(),
                newMiniLearningHeapRsatExpSimp(),
                newDefaultAutoErasePhaseSaving(), newMiniLearningHeap(),
                newMiniSATHeapExpSimp(), newMiniSATHeapEZSimp());
    }

    /**
     * Two solvers are running in //: one for solving SAT instances, the other
     * one for solving unsat instances.
     *
     * @return a parallel solver for both SAT and UNSAT problems.
     */
    public static ISolver newSATUNSAT() {
        return new ManyCore(newSAT(), newUNSAT());
    }

    /**
     * That solver is expected to perform better on satisfiable benchmarks.
     *
     * @return a solver for satisfiable benchmarks.
     */
    public static Solver newSAT() {
        Solver solver = (Solver) newGlucose21();
        solver.setRestartStrategy(new LubyRestarts(100));
        solver.setLearnedConstraintsDeletionStrategy(solver.memory_based);
        return solver;
    }

    /**
     * That solver is expected to perform better on unsatisfiable benchmarks.
     *
     * @return a solver for unsatisfiable benchmarks.
     */
    public static Solver newUNSAT() {
        Solver solver = (Solver) newGlucose21();
        solver.setRestartStrategy(new NoRestarts());
        solver.setSimplifier(solver.SIMPLE_SIMPLIFICATION);
        return solver;
    }
}


text:
module Language.Drasil.Printing.Import.Space where

import Language.Drasil (dbl, Space(..))

import qualified Language.Drasil.Printing.AST as P
import Language.Drasil.Printing.PrintingInformation (PrintingInformation)

import Language.Drasil.Printing.Import.Expr (expr)

import Data.List (intersperse)
import Data.List.NonEmpty (toList)

-- | Render a 'Space'.
space :: PrintingInformation -> Space -> P.Expr
space _  Integer        = P.MO P.Integer
space _  Rational       = P.MO P.Rational
space _  Real           = P.MO P.Real
space _  Natural        = P.MO P.Natural
space _  Boolean        = P.MO P.Boolean
space _  Char           = P.Ident "Char"
space _  String         = P.Ident "String"
space _  Radians        = error "Radians not translated"
space _  (Vect _)       = error "Vector space not translated"
space _  (Array _)      = error "Array space not translated"
space _  (Actor s)      = P.Ident s
space sm (DiscreteD l)  = P.Fenced P.Curly P.Curly $ P.Row $ intersperse (P.MO P.Comma) $ map (flip expr sm . dbl) l -- [Double]
space _  (DiscreteS l)  = P.Fenced P.Curly P.Curly $ P.Row $ intersperse (P.MO P.Comma) $ map P.Str l --ex. let Meal = {"breakfast", "lunch", "dinner"}
space _  Void           = error "Void not translated"
space sm (Function i t) = P.Row $
  intersperse (P.MO P.Cross) (map (space sm) $ toList i) ++  -- AxBxC...xY
  [P.MO P.RArrow, space sm t]                                -- -> Z

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web;

namespace SethWebster.OpenLogging.Models
{
    public class LogMessage
    {
        public LogMessage()
        {
            this.DateCreated = DateTimeOffset.Now;
            this.DateOfEvent = DateTimeOffset.Now;
            this.DateOfExpiration = DateTimeOffset.Now.AddDays(15);
        }
        public int LogMessageId { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Category { get; set; }
        [Required]
        public string Message { get; set; }
        public string Body { get; set; }
        public DateTimeOffset DateCreated { get; set; }
        public DateTimeOffset DateOfEvent { get; set; }
        /// <summary>
        /// The Date this LogMessage is eligible for purge
        /// </summary>
        public DateTimeOffset DateOfExpiration { get; set; }

        public string Context { get; set; }

        public async Task<T> GetContextAsync<T>()
        {
            return await JsonConvert.DeserializeObjectAsync<T>(Context);
        }

        public void SetContext<T>(T context)
        {
            this.Context = JsonConvert.SerializeObject(context);
        }

        [Required]
        public Client Client { get; set; }
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "attendance".
 *
 * @property string $student_no
 * @property string $date
 *
 * @property User $studentNo
 */
class Attendance extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'attendance';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['student_no', 'date'], 'required'],
            [['date'], 'safe'],
            [['student_no'], 'string', 'max' => 10]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'student_no' => 'Student Number',
            'date' => 'Date ',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getStudentNo()
    {
        return $this->hasOne(User::className(), ['student_no' => 'student_no']);
    }
}


text:
import os
import io
import sys
from shutil import rmtree

from setuptools import find_packages, setup, Command

# Package meta-data.
NAME = 'django-anexia-monitoring'
PACKAGE_PATH = 'anexia_monitoring'
DESCRIPTION = 'A Django app used to monitor updates for Django and all installed python packages in the running environment. It can be also used to check if the website is alive and working correctly.'
URL = 'https://github.com/anexia-it/anexia-monitoring-django'
AUTHOR = 'Anexia'
LICENSE = 'MIT'
REQUIRED = [
    'updatable>=0.4.1,<0.5',
]
CLASSIFIERS = [
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Natural Language :: English',
        'Topic :: Utilities',
]

# Setup configuration
current_path = os.path.abspath(os.path.dirname(__file__))

# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
with io.open(os.path.join(current_path, 'README.md'), encoding='utf-8') as f:
    long_description = '\n' + f.read()

class PublishCommand(Command):
    """Support setup.py publish."""

    description = 'Build and publish the package.'
    user_options = []

    @staticmethod
    def status(s):
        """Prints things in bold."""
        print('\033[1m{0}\033[0m'.format(s))

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        try:
            self.status('Removing previous builds…')
            rmtree(os.path.join(current_path, 'dist'))
        except OSError:
            pass

        self.status('Building Source and Wheel (universal) distribution…')
        os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))

        self.status('Uploading the package to PyPi via Twine…')
        os.system('twine upload dist/*')

        sys.exit()

setup(
    name=NAME,
    version=os.getenv('PACKAGE_VERSION', '0.0.0').replace('refs/tags/', ''),
    packages=find_packages(),
    include_package_data=True,
    license=LICENSE,
    description=DESCRIPTION,
    long_description=long_description,
    long_description_content_type='text/markdown',
    url=URL,
    author=AUTHOR,
    classifiers=CLASSIFIERS,
    install_requires=REQUIRED,
    # $ setup.py publish support.
    cmdclass={
        'publish': PublishCommand,
    },
)


text:
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkCamera.h"
#include "SkEmbossMaskFilter.h"
#include "SkGradientShader.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkRandom.h"
#include "SkImageDecoder.h"

class CameraView : public SampleView {
    SkTDArray<SkShader*> fShaders;
    int     fShaderIndex;
    bool    fFrontFace;
public:
    CameraView() {
        fRX = fRY = fRZ = 0;
        fShaderIndex = 0;
        fFrontFace = false;

        for (int i = 0;; i++) {
            SkString str;
            str.printf("/skimages/elephant%d.jpeg", i);
            SkBitmap bm;
            if (SkImageDecoder::DecodeFile(str.c_str(), &bm)) {
                SkShader* s = SkShader::CreateBitmapShader(bm,
                                                           SkShader::kClamp_TileMode,
                                                           SkShader::kClamp_TileMode);

                SkRect src = { 0, 0, SkIntToScalar(bm.width()), SkIntToScalar(bm.height()) };
                SkRect dst = { -150, -150, 150, 150 };
                SkMatrix matrix;
                matrix.setRectToRect(src, dst, SkMatrix::kFill_ScaleToFit);
                s->setLocalMatrix(matrix);
                *fShaders.append() = s;
            } else {
                break;
            }
        }
        this->setBGColor(0xFFDDDDDD);
    }

    virtual ~CameraView() {
        fShaders.unrefAll();
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt))
        {
            SampleCode::TitleR(evt, "Camera");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        canvas->translate(this->width()/2, this->height()/2);

        Sk3DView    view;
        view.rotateX(fRX);
        view.rotateY(fRY);
        view.applyToCanvas(canvas);

        SkPaint paint;
        if (fShaders.count() > 0) {
            bool frontFace = view.dotWithNormal(0, 0, SK_Scalar1) < 0;
            if (frontFace != fFrontFace) {
                fFrontFace = frontFace;
                fShaderIndex = (fShaderIndex + 1) % fShaders.count();
            }

            paint.setAntiAlias(true);
            paint.setShader(fShaders[fShaderIndex]);
            SkRect r = { -150, -150, 150, 150 };
            canvas->drawRoundRect(r, 30, 30, paint);
        }

        fRY += SampleCode::GetAnimSecondsDelta() * 90;
        if (fRY >= SkIntToScalar(360)) {
            fRY = 0;
        }
        this->inval(NULL);
    }

private:
    SkScalar fRX, fRY, fRZ;
    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new CameraView; }
static SkViewRegister reg(MyFactory);


text: Removes the region of interest from an ofxCvImage.


text:
package mockcalls

import (
	"fmt"

	"github.com/golang/protobuf/proto"
	l2 "go.ligato.io/vpp-agent/v3/examples/kvscheduler/mock_plugins/l2plugin/model"
)

// CreateL2FIB creates L2 FIB table entry in the mock SB.
func (h *MockFIBHandler) CreateL2FIB(fib *l2.FIBEntry) error {
	h.mockFIBs = append(h.mockFIBs, fib)
	h.log.Infof("Created L2 FIB entry: %v", fib)
	return nil
}

// DeleteL2FIB removes existing L2 FIB table entry from the mock SB.
func (h *MockFIBHandler) DeleteL2FIB(fib *l2.FIBEntry) error {
	var idx int
	for ; idx < len(h.mockFIBs); idx++ {
		if proto.Equal(h.mockFIBs[idx], fib) {
			break
		}
	}
	if idx == len(h.mockFIBs) {
		return fmt.Errorf("no such L2 FIB entry: %v", fib)
	}
	h.mockFIBs = append(h.mockFIBs[:idx], h.mockFIBs[idx+1:]...)
	h.log.Infof("Deleted L2 FIB entry: %v", fib)
	return nil
}

// DumpL2FIBs dumps L2 FIB table entries "configured" in the mock SB.
func (h *MockFIBHandler) DumpL2FIBs() ([]*l2.FIBEntry, error) {
	h.log.Infof("Dumped L2 FIB entries: %+v", h.mockFIBs)
	return h.mockFIBs, nil
}


text:
<?php

namespace spec\PSB\Core\Serialization\Json\ObjectNormalizerSpec;

class MagicClass
{
    public $show = true;

    public $hide = true;

    public $woke = false;

    public function __sleep()
    {
        return ['show'];
    }

    public function __wakeup()
    {
        $this->woke = true;
    }
}


text:
#import <XXUnknownSuperclass.h> // Unknown library

@interface PodsDummy_Pods_MKNetworkKit : XXUnknownSuperclass {
}
@end


text:
"""Functionality related with node paths in a PyTables file.

Variables
=========

`__docformat`__
    The format of documentation strings in this module.

"""

# Imports
# =======
import re
import warnings
import keyword

from tables.exceptions import NaturalNameWarning

# Public variables
# ================
__docformat__ = 'reStructuredText'
"""The format of documentation strings in this module."""

# Private variables
# =================
_python_id_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
"""Python identifier regular expression."""

_reserved_id_re = re.compile('^_[cfgv]_')
"""PyTables reserved identifier regular expression.

- c: class variables
- f: class public methods
- g: class private methods
- v: instance variables
"""

_hidden_name_re = re.compile('^_[pi]_')
"""Nodes with a name *matching* this expression are considered hidden.

For instance, ``name`` whould be visible while ``_i_name`` would not.
"""

_hidden_path_re = re.compile('/_[pi]_')
"""Nodes with a path *containing* this expression are considered hidden.

For instance, a node with a pathname like ``/a/b/c`` would be visible
while nodes with pathnames like ``/a/c/_i_x`` or ``/a/_p_x/y`` would
not.
"""

_warnInfo = (
        "you will not be able to use natural naming to access this object; "
        "using ``getattr()`` will still work, though")
"""Warning printed when a name will not be reachable through natural naming"""

# Public functions
# ================

def check_attribute_name(name):
    """Check the validity of the `name` of an attribute in AttributeSet.

    If the name is not valid, a ``ValueError`` is raised.  If it is
    valid but it can not be used with natural naming, a
    `NaturalNameWarning` is issued.

    >>> check_attribute_name('a')
    >>> check_attribute_name('a_b')
    >>> check_attribute_name('a:b')
    >>> check_attribute_name('/a/b')
    >>> check_attribute_name('/')
    >>> check_attribute_name('.')
    >>> check_attribute_name('__members__')
    Traceback (most recent call last):
     ...
    ValueError: ``__members__`` is not allowed as an object name
    >>> check_attribute_name(1)
    Traceback (most recent call last):
     ...
    TypeError: object name is not a string: 1
    >>> check_attribute_name('')
    Traceback (most recent call last):
     ...
    ValueError: the empty string is not allowed as an object name
    """
    if not isinstance(name, basestring):  # Python >= 2.3
        raise TypeError("object name is not a string: %r" % (name,))

    if name == '':
        raise ValueError("the empty string is not allowed as an object name")

    # Check whether `name` is a valid Python identifier.
    if not _python_id_re.match(name):
        warnings.warn("object name is not a valid Python identifier: %r; "
                      "it does not match the pattern ``%s``; %s"
                      % (name, _python_id_re.pattern, _warnInfo),
                      NaturalNameWarning)
        return

    # However, Python identifiers and keywords have the same form.
    if keyword.iskeyword(name):
        warnings.warn("object name is a Python keyword: %r; %s"
                      % (name, _warnInfo), NaturalNameWarning)
        return

    # Still, names starting with reserved prefixes are not allowed.
    if _reserved_id_re.match(name):
        raise ValueError("object name starts with a reserved prefix: %r; "
                         "it matches the pattern ``%s``"
                         % (name, _reserved_id_re.pattern))

    # ``__members__`` is the only exception to that rule.
    if name == '__members__':
        raise ValueError("``__members__`` is not allowed as an object name")

def check_name_validity(name):
    """Check the validity of the `name` of a Node object, which more limited
    than attribute names.

    If the name is not valid, a ``ValueError`` is raised.  If it is
    valid but it can not be used with natural naming, a
    `NaturalNameWarning` is issued.

    >>> check_name_validity('a')
    >>> check_name_validity('a_b')
    >>> check_name_validity('a:b')
    >>> check_name_validity('/a/b')
    Traceback (most recent call last):
     ...
    ValueError: the ``/`` character is not allowed in object names: '/a/b'
    >>> check_name_validity('.')
    Traceback (most recent call last):
     ...
    ValueError: ``.`` is not allowed as an object name
    >>> check_name_validity('')
    Traceback (most recent call last):
     ...
    ValueError: the empty string is not allowed as an object name

    """
    check_attribute_name(name)

    # Check whether `name` is a valid HDF5 name.
    # http://hdfgroup.org/HDF5/doc/UG/03_Model.html#Structure
    if name == '.':
        raise ValueError("``.`` is not allowed as an object name")
    elif '/' in name:
        raise ValueError("the ``/`` character is not allowed "
                         "in object names: %r" % name)

def join_path(parentpath, name):
    """Join a *canonical* `parentpath` with a *non-empty* `name`.

    .. versionchanged:: 3.0
       The *parentPath* parameter has been renamed into *parentpath*.

    >>> join_path('/', 'foo')
    '/foo'
    >>> join_path('/foo', 'bar')
    '/foo/bar'
    >>> join_path('/foo', '/foo2/bar')
    '/foo/foo2/bar'
    >>> join_path('/foo', '/')
    '/foo'

    """

    if name.startswith('./'):  # Support relative paths (mainly for links)
        name = name[2:]
    if parentpath == '/' and name.startswith('/'):
        pstr = '%s' % name
    elif parentpath == '/' or name.startswith('/'):
        pstr = '%s%s' % (parentpath, name)
    else:
        pstr = '%s/%s' % (parentpath, name)
    if pstr.endswith('/'):
        pstr = pstr[:-1]
    return pstr

def split_path(path):
    """Split a *canonical* `path` into a parent path and a node name.

    The result is returned as a tuple.  The parent path does not
    include a trailing slash.

    >>> split_path('/')
    ('/', '')
    >>> split_path('/foo/bar')
    ('/foo', 'bar')

    """

    lastslash = path.rfind('/')
    ppath = path[:lastslash]
    name = path[lastslash + 1:]

    if ppath == '':
        ppath = '/'

    return (ppath, name)

def isvisiblename(name):
    """Does this `name` make the named node a visible one?"""

    return _hidden_name_re.match(name) is None

def isvisiblepath(path):
    """Does this `path` make the named node a visible one?"""

    return _hidden_path_re.search(path) is None

# Main part
# =========
def _test():
    """Run ``doctest`` on this module."""

    import doctest
    doctest.testmod()

if __name__ == '__main__':
    _test()


text:
name: Konfiguration und Start
---

# Konfiguration und Start

## Konfiguration

### Standard-Konfiguration

Die Standard-Konfiguration ist in `conf/app.ini` gespeichert. Du brauchst diese Datei **NICHT** verändern, seit `v0.6.0` ist das im Programm eingebunden.

### Manuelle Konfiguration

Wie macht man nun eigene Änderungen, wenn man die `conf/app.ini` nicht verändern darf? Erstelle einfach eine `custom/conf/app.ini`! Die entsprechenden Schlüssel in den entsprechenden Sektionen werden die Werte aus `conf/app.ini` überschreiben.

Zum Beispiel kann man, um denn Wurzelpfad, in dem die Repository-Rohdaten gespeichert werden, zu verändern, eine Zeile wie die folgende hinzufügen:

```
[repository]
ROOT = /home/jiahuachen/gogs-repositories
```

Natürlich kann man auch die Datenbank-Einstellungen ändern

```
[database]
PASSWD = root
```

### Warum tun wir das?

Ja, warum nicht einfach `conf/app.ini` verändern? Der Grund ist, die eigene Konfiguration sicher zu speichern:

- Alle, die das Programm aus der Binärdateien installieren, können jedes mal, wenn eine neue Version rauskommt, die Dateien einfach in den Ordner kopieren, ohne etwas neu konfigurieren zu müssen.
- Für alle, die das Programm aus den Quelldateien installieren, haben wir die `custom/conf/app.ini` in der `.gitignore` aus der Versionskontrolle ausgenommen, sodass es keine neue Version erzeugt, wenn man Konfigurationsänderungen macht oder eine neue Version herunterlädt.

## Gogs Server starten

### Für Entwickler

- Setze den Schlüssel `security -> INSTALL_LOCK` auf `true` in der `custom/conf/app.ini` um Gogs aus den Quelldateien zu starten
- Du kannst Live-Compiling anschalten mit `bra run` im Gogs Quell-Ordner
	- Installation von [bra](https://github.com/Unknwon/bra): ` go get -u github.com/Unknwon/bra`

### Für normalen Einsatz

**Die Skripte liegen im `scripts`-Ordner, aber führe sie immer im Wurzelverzeichnis des Repositorys aus**

- Es gibt einige Wege, Gogs zu starten:
	- Einfach: Nutze einfach `./gogs web`
	- Daemons: siehe [scripts](https://github.com/gogs/gogs/tree/master/scripts) Ordner
- gucke in `/install` um die erste Konfiguration zu erstellen.


text:
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <parameters>
        <parameter key="guestbook.message.repository.class">Lebed\GuestbookBundle\Entity\MessageRepository</parameter>
        <parameter key="lebed_guestbook.searcher.class">Lebed\GuestbookBundle\Service\SearcherService\Searcher</parameter>
    </parameters>
    <services>
        <service id="lebed_guestbook.form.type.message"
                 class="Lebed\GuestbookBundle\Form\Type\MessageType">
            <tag name="form.type" alias="message" />
        </service>
        <service id="guestbook.message.repository"
                 class="%guestbook.message.repository.class%"
                 factory-service="doctrine.orm.entity_manager"
                 factory-method="getRepository">
            <argument>LebedGuestbookBundle:Message</argument>
        </service>
        <service id="searcher"
                 class="%lebed_guestbook.searcher.class%">
            <argument type="service" id="guestbook.message.repository" />
        </service>
    </services>
</container>


text:
import csv
import httplib;
import urllib;
import json;
import argparse;

class API:
    def __init__(self, api_key, secret_key, url, use_ssl=True):
        self.api_key = api_key
        self.secret_key = secret_key
        self.url = url
        self.use_ssl = use_ssl

    def auth_token(self, api_key, secret_key):
        return {'Authorization': 'Token token="' + api_key + secret_key + '"'}

    def append_auth_token_to_headers(self, headers):
        headers['Authorization'] = self.auth_token(self.api_key, self.secret_key)['Authorization'];
        return headers;

    def call(self, name, method, path, body='', headers={}):
        browser = None
        try:
            if self.use_ssl:
                browser = httplib.HTTPSConnection(self.url)
            else:
                browser = httplib.HTTPConnection(self.url)

            browser.request(method, path, body, self.append_auth_token_to_headers(headers))
            res = browser.getresponse()
            # read() must be called before close(), otherwise it will return an empty string
            data = res.read()

            if res.status >= 400:
                raise httplib.HTTPException(str(res.status) + ' ' + res.reason + (': ' + data.strip() if data.strip() else ''))

            # close() must be called after each request, or subsequent requests will be denied
            browser.close()
            #return data
            if data != '':
                return json.loads(data)
            else:
                # No Content is a legitimate response
                if str(res.status) == '204':
                    return {}
                raise Exception(str(res.status) + res.reason)
        except httplib.HTTPException as h:
            raise Exception('ScriptRock API request failed [' + name + ']: ' + str(h))
        finally:
            if browser is not None:
                browser.close()

def create_arg_parser():
    parser = argparse.ArgumentParser(description='Manipulate node groups')
    parser.add_argument('-api_key', help='The API key for the appliance')
    parser.add_argument('-secret_key', help='The secret key for the appliance')
    parser.add_argument('-url', help='The URL for the appliance, with no scheme specified')
    parser.add_argument('-node_group_id', help='The ndoe group that the CSV file defines membership for')
    parser.add_argument('-csv_path', help='The path to the CSV file to import from')
    parser.add_argument('-headers', help='The list of column headers (comma separated) for the CSV file. The order must match that of the CSV file')
    parser.add_argument('-filters', help='A list of columns to filter by, in the format "filter_column_name=option[|option]"')
    parser.add_argument('-dry_run', action='store_true', help='If specified, will display the results of executing the script, without commiting any changes')
    parser.add_argument('-name_column', default='name', help='The column that contains node names. Defaults to "name"')
    parser.add_argument('-no_ssl', action='store_true', help='During development, can be used to make requests of HTTP instead of HTTPS')
    return parser

def get_node_list(csv_path, name_column, raw_filters, dry_run, headers=None):
    final_node_list = []
    name_column_index = 0
    skipped_rows = 0

    with open(csv_path, 'rb') as f:
        reader = csv.reader(f)
        node = {}

        filters = {}
        for kvp in raw_filters.split(';'):
            if kvp == '':
                continue
            k, v = kvp.split('=')
            filters[k] = v.split('|') # results in an array, regardless as to whether or not a split actually occured

        for row in reader:
            node_acceptable = True
            reason_string = ''

            if headers == None:
                # if no headers are specified on the command line, use the first row as the headers
                headers = row

                if name_column not in headers:
                    print('Column "' + str(name_column) + '" was not found in the headers')
                    return []

                name_column_index = headers.index(name_column)
                continue

            # we can't do anything if there is no node name, but don't want to print out an entry for every blank line, so just keep a count
            if not str(row[name_column_index]):
                skipped_rows = skipped_rows + 1
                continue

            for index, header in enumerate(headers):
                if header in filters:
                    if node_acceptable == False:
                        break;

                    reason_string += header + ' = ' + row[index] + '; '
                    if row[index] not in filters[header]:
                        node_acceptable = False

            if node_acceptable:
                print('Adding node ' + row[name_column_index] + ' to group because it matched filters ' + reason_string)
                final_node_list.append(row[name_column_index])
            else:
                print('Not adding node ' + row[name_column_index] + ' to group because it did not match filters ' + reason_string)

    if skipped_rows > 0:
        print(str(skipped_rows) + ' rows were skipped because the name column was blank')

    return final_node_list

def change_group_membership(node_list, target_group, api, dry_run):
    existing_node_ids_in_group = [node['id'] for node in api.call('get_node_group_nodes', 'GET', '/api/v1/node_groups/' + str(target_group) + '/nodes.json')]
    new_member_ids = []

    for node in node_list:
            retrieved_node = None
            try:
                retrieved_node = api.call('get_node', 'GET', '/api/v1/nodes/lookup.json?name=' + str(node))
            except Exception as e:
                print('Could not retrieve node ' + node)
                print(e)
                continue

            # in case we get some wierd respone back
            # 'lookup' just returns the Id in an object like so: { "node_id": 1 }
            if 'node_id' not in retrieved_node:
                print('Could not retrieve node ' + node + ': Id was not found on the returned object')
                continue
            else:
                new_member_ids.append(retrieved_node['node_id'])

    remove_ids = [n for n in existing_node_ids_in_group if n not in new_member_ids]

    for r_id in remove_ids:
        if dry_run:
            print('Removing node with ID ' + str(r_id) + ' from node group with ID ' + str(target_group))
            continue

        api.call('remove_node_from_group', 'POST', '/api/v1/node_groups/' + str(target_group) + '/remove_node.json?node_id=' + str(r_id))

    add_ids = [n for n in new_member_ids if n not in existing_node_ids_in_group]

    for a_id in add_ids:
        if dry_run:
            print('Adding node with ID ' + str(a_id) + ' to node group with ID ' + str(target_group))
            continue

        api.call('add_node_to_group', 'POST', '/api/v1/node_groups/' + str(target_group) + '/add_node.json?node_id=' + str(a_id))

def main():
    args = create_arg_parser().parse_args()

    api = API(args.api_key, args.secret_key, args.url, not args.no_ssl)

    change_group_membership(get_node_list(args.csv_path, args.name_column, args.filters, args.dry_run, args.headers), args.node_group_id, api, args.dry_run)

main()


text:
import Controller from 'ember-controller';

export default Controller.extend({
  dataUri: null,
  didSnap(dataUri) {
    this.set('dataUri', dataUri);
  },
  actions: {
    takeSnapshot(snap) {
      snap();
    }
  }
});


text:
package com.redhat.plugin.checkrelease;

import java.util.ArrayList;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.ResolutionScope;

/**
 * Determines if the build artifact with its current version already
 * exists in the release repository. If the release artifact is
 * modified but the version number is kept the same, prints a warning.
 *
 * Configuration Items:
 *

 *
repoUrl: (required) URL of the deployment repository

 *
ignore: (optional) If set to true, check-release artifact
 * skips the current project.

 *

 *
 * Usage:
 *

 *    mvn clean install check-release:report
 *

 *
 * @author Burak Serdar (bserdar@redhat.com)
 */

@Mojo(name = "report",
      requiresDependencyResolution = ResolutionScope.COMPILE,
      defaultPhase = LifecyclePhase.PREPARE_PACKAGE,
      threadSafe = true
)
public class ReportReleaseMojo extends AbstractReleaseMojo {

    private static ArrayList<String> messages=new ArrayList<String>();

    protected void modifiedButSameVersion(ReleaseArtifact a,
                                          String diff)
        throws MojoExecutionException, MojoFailureException {
        messages.add(a+" is modified, but version number is not changed\n"+diff);
        getLog().warn(a+" is modified, but version number is not changed\n"+diff);
    }

    protected void end() {
    }

    protected void modifiedButSemanticallyEqual(ReleaseArtifact a)
        throws MojoExecutionException, MojoFailureException {}

    protected void identical(ReleaseArtifact a)
        throws MojoExecutionException, MojoFailureException {}

}


text:
This folder contains supportive source code.

For current versions or reporting issues etc. please check the main development pages.

- [bmp180](https://github.com/Angus71/esp-open-rtos-driver-bmp180)
- [i2c](https://github.com/kanflo/esp-open-rtos-driver-i2c)
- [rboot-ota](http://richard.burtons.org/)


text:
/**
 * Palvelu hoitaa yllapitajan toimiin liittyvat pyynnot palvelimelle.
 */
angular.module('chatProApp')
    .factory('adminService', ['$http', function ($http) {

        function getUsers(callback) {
            $http.get('/getusers').then(callback);
        }

        function createUser(user , callback) {
            $http.post('/newuser', user).then(callback);
        }

        function delUser(userID, callback) {
            $http.delete('/delete/' + userID, {}).then(callback);
        }

        function resetPassword(userID, newPassword, callback) {
            $http.post('/resetpassword/' + userID, newPassword).then(callback);
        }

        function resetDatabase(callback) {
            $http.delete('/tuhoaHistoria', {}).then(callback);
        }

        var admin = {
            getUsers: getUsers,
            createUser: createUser,
            delUser: delUser,
            resetPassword: resetPassword,
            resetDatabase: resetDatabase
        };

        return admin;
    }]);


text:
#ifndef UAVCAN_PROTOCOL_NODE_STATUS_MONITOR_HPP_INCLUDED
#define UAVCAN_PROTOCOL_NODE_STATUS_MONITOR_HPP_INCLUDED

#include <uavcan/debug.hpp>
#include <uavcan/util/method_binder.hpp>
#include <uavcan/node/subscriber.hpp>
#include <uavcan/node/timer.hpp>
#include <uavcan/protocol/NodeStatus.hpp>
#include <cassert>
#include <cstdlib>

namespace uavcan
{
/**
 * This class implements the core functionality of a network monitor.
 * It can be extended by inheritance to add more complex logic, or used directly as is.
 */
class UAVCAN_EXPORT NodeStatusMonitor
{
public:
    struct NodeStatus
    {
        uint8_t health   : 2;
        uint8_t mode     : 3;
        uint8_t sub_mode : 3;

        NodeStatus() :
            health(protocol::NodeStatus::HEALTH_CRITICAL),
            mode(protocol::NodeStatus::MODE_OFFLINE),
            sub_mode(0)
        {
            StaticAssert<protocol::NodeStatus::FieldTypes::health::BitLen   == 2>::check();
            StaticAssert<protocol::NodeStatus::FieldTypes::mode::BitLen     == 3>::check();
            StaticAssert<protocol::NodeStatus::FieldTypes::sub_mode::BitLen == 3>::check();
        }

        bool operator!=(const NodeStatus rhs) const { return !operator==(rhs); }
        bool operator==(const NodeStatus rhs) const
        {
            return std::memcmp(this, &rhs, sizeof(NodeStatus)) == 0;
        }

#if UAVCAN_TOSTRING
        std::string toString() const
        {
            char buf[40];
            (void)snprintf(buf, sizeof(buf), "health=%d mode=%d sub_mode=%d", int(health), int(mode), int(sub_mode));
            return std::string(buf);
        }
#endif
    };

    struct NodeStatusChangeEvent
    {
        NodeID node_id;
        NodeStatus status;
        NodeStatus old_status;
        bool was_known;

        NodeStatusChangeEvent() :
            was_known(false)
        { }
    };

private:
    enum { TimerPeriodMs100 = 2 };

    typedef MethodBinder<NodeStatusMonitor*,
                         void (NodeStatusMonitor::*)(const ReceivedDataStructure<protocol::NodeStatus>&)>
            NodeStatusCallback;

    typedef MethodBinder<NodeStatusMonitor*, void (NodeStatusMonitor::*)(const TimerEvent&)> TimerCallback;

    Subscriber<protocol::NodeStatus, NodeStatusCallback, MaxNetworkSizeHint, 0> sub_;

    TimerEventForwarder<TimerCallback> timer_;

    struct Entry
    {
        NodeStatus status;
        int8_t time_since_last_update_ms100;
        Entry() :
            time_since_last_update_ms100(-1)
        { }
    };

    mutable Entry entries_[NodeID::Max];  // [1, NodeID::Max]

    Entry& getEntry(NodeID node_id) const
    {
        if (node_id.get() < 1 || node_id.get() > NodeID::Max)
        {
            handleFatalError("NodeStatusMonitor NodeID");
        }
        return entries_[node_id.get() - 1];
    }

    void changeNodeStatus(const NodeID node_id, const Entry new_entry_value)
    {
        Entry& entry = getEntry(node_id);
        if (entry.status != new_entry_value.status)
        {
            NodeStatusChangeEvent event;
            event.node_id    = node_id;
            event.old_status = entry.status;
            event.status     = new_entry_value.status;
            event.was_known  = entry.time_since_last_update_ms100 >= 0;

            UAVCAN_TRACE("NodeStatusMonitor", "Node %i [%s] status change: [%s] --> [%s]", int(node_id.get()),
                         (event.was_known ? "known" : "new"),
                         event.old_status.toString().c_str(), event.status.toString().c_str());

            handleNodeStatusChange(event);
        }
        entry = new_entry_value;
    }

    void handleNodeStatus(const ReceivedDataStructure<protocol::NodeStatus>& msg)
    {
        Entry new_entry;
        new_entry.time_since_last_update_ms100 = 0;
        new_entry.status.health   = msg.health   & ((1 << protocol::NodeStatus::FieldTypes::health::BitLen) - 1);
        new_entry.status.mode     = msg.mode     & ((1 << protocol::NodeStatus::FieldTypes::mode::BitLen) - 1);
        new_entry.status.sub_mode = msg.sub_mode & ((1 << protocol::NodeStatus::FieldTypes::sub_mode::BitLen) - 1);

        changeNodeStatus(msg.getSrcNodeID(), new_entry);

        handleNodeStatusMessage(msg);
    }

    void handleTimerEvent(const TimerEvent&)
    {
        const int OfflineTimeoutMs100 = protocol::NodeStatus::OFFLINE_TIMEOUT_MS / 100;

        for (uint8_t i = 1; i <= NodeID::Max; i++)
        {
            Entry& entry = getEntry(i);
            if (entry.time_since_last_update_ms100 >= 0 &&
                entry.status.mode != protocol::NodeStatus::MODE_OFFLINE)
            {
                entry.time_since_last_update_ms100 =
                    int8_t(entry.time_since_last_update_ms100 + int8_t(TimerPeriodMs100));

                if (entry.time_since_last_update_ms100 > OfflineTimeoutMs100)
                {
                    Entry new_entry_value = entry;
                    new_entry_value.time_since_last_update_ms100 = OfflineTimeoutMs100;
                    new_entry_value.status.mode = protocol::NodeStatus::MODE_OFFLINE;
                    changeNodeStatus(i, new_entry_value);
                }
            }
        }
    }

protected:
    /**
     * Called when a node becomes online, changes status or goes offline.
     * Refer to uavcan.protocol.NodeStatus for the offline timeout value.
     * Overriding is not required.
     */
    virtual void handleNodeStatusChange(const NodeStatusChangeEvent& event)
    {
        (void)event;
    }

    /**
     * Called for every received message uavcan.protocol.NodeStatus after handleNodeStatusChange(), even
     * if the status code did not change.
     * Overriding is not required.
     */
    virtual void handleNodeStatusMessage(const ReceivedDataStructure<protocol::NodeStatus>& msg)
    {
        (void)msg;
    }

public:
    explicit NodeStatusMonitor(INode& node)
        : sub_(node)
        , timer_(node)
    { }

    virtual ~NodeStatusMonitor() { }

    /**
     * Starts the monitor.
     * Destroy the object to stop it.
     * Returns negative error code.
     */
    int start()
    {
        const int res = sub_.start(NodeStatusCallback(this, &NodeStatusMonitor::handleNodeStatus));
        if (res >= 0)
        {
            timer_.setCallback(TimerCallback(this, &NodeStatusMonitor::handleTimerEvent));
            timer_.startPeriodic(MonotonicDuration::fromMSec(TimerPeriodMs100 * 100));
        }
        return res;
    }

    /**
     * Make the node unknown.
     */
    void forgetNode(NodeID node_id)
    {
        if (node_id.isValid())
        {
            Entry& entry = getEntry(node_id);
            entry = Entry();
        }
        else
        {
            UAVCAN_ASSERT(0);
        }
    }

    /**
     * Make all nodes unknown.
     */
    void forgetAllNodes()
    {
        for (unsigned i = 0; i < (sizeof(entries_) / sizeof(entries_[0])); i++)
        {
            entries_[i] = Entry();
        }
    }

    /**
     * Returns status of a given node.
     * Unknown nodes are considered offline.
     * Complexity O(1).
     */
    NodeStatus getNodeStatus(NodeID node_id) const
    {
        if (!node_id.isValid())
        {
            UAVCAN_ASSERT(0);
            return NodeStatus();
        }

        const Entry& entry = getEntry(node_id);
        if (entry.time_since_last_update_ms100 >= 0)
        {
            return entry.status;
        }
        else
        {
            return NodeStatus();
        }
    }

    /**
     * Whether the class has observed this node at least once since initialization.
     * Complexity O(1).
     */
    bool isNodeKnown(NodeID node_id) const
    {
        if (!node_id.isValid())
        {
            UAVCAN_ASSERT(0);
            return false;
        }
        return getEntry(node_id).time_since_last_update_ms100 >= 0;
    }

    /**
     * This helper method allows to quickly estimate the overall network health.
     * Health of the local node is not considered.
     * Returns an invalid Node ID value if there's no known nodes in the network.
     */
    NodeID findNodeWithWorstHealth() const
    {
        NodeID nid_with_worst_health;
        uint8_t worst_health = protocol::NodeStatus::HEALTH_OK;

        for (uint8_t i = 1; i <= NodeID::Max; i++)
        {
            const NodeID nid(i);
            UAVCAN_ASSERT(nid.isUnicast());
            const Entry& entry = getEntry(nid);
            if (entry.time_since_last_update_ms100 >= 0)
            {
                if (entry.status.health > worst_health || !nid_with_worst_health.isValid())
                {
                    nid_with_worst_health = nid;
                    worst_health = entry.status.health;
                }
            }
        }

        return nid_with_worst_health;
    }

    /**
     * Calls the operator for every known node.
     * Operator signature:
     *   void (NodeID, NodeStatus)
     */
    template <typename Operator>
    void forEachNode(Operator op) const
    {
        for (uint8_t i = 1; i <= NodeID::Max; i++)
        {
            const NodeID nid(i);
            UAVCAN_ASSERT(nid.isUnicast());
            const Entry& entry = getEntry(nid);
            if (entry.time_since_last_update_ms100 >= 0)
            {
                op(nid, entry.status);
            }
        }
    }
};

}

#endif // UAVCAN_PROTOCOL_NODE_STATUS_MONITOR_HPP_INCLUDED


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Threading;

namespace IronAHK.Rusty.Common
{
    /// <summary>
    /// Create a global Instance of CoordProvider and use it multithreaded
    /// </summary>
    sealed class CoordProvider
    {
        #region Fields

        private Size mMaxMovement;
        private Point mCurrent;
        private bool mDone;

        private object Locker = new object();

        #endregion

        #region Constructor

        /// <summary>
        /// Create new CoordProvider with given Settings.
        /// </summary>
        /// <param name="uSourceSize">Size of Searchable Image Area</param>
        /// <param name="uNeedleSize">Size of Needle Image</param>
        public CoordProvider(Size uSourceSize, Size uNeedleSize) {
            mMaxMovement = new Size(uSourceSize.Width - uNeedleSize.Width, uSourceSize.Height - uNeedleSize.Height);
            mCurrent = new Point(-1, 0);
            mDone = false;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Returns the next Workitem (thread save)
        /// </summary>
        /// <returns>Next Coord (Point) or Null if the work is done.</returns>
        public Point? Next() {

            lock(Locker) {
                if(mDone)
                    return null;
                mCurrent.X++;
                if(mCurrent.X > mMaxMovement.Width) {
                    mCurrent.X = 0;
                    mCurrent.Y++;
                    if(mCurrent.Y > mMaxMovement.Height) {
                        mDone = true;
                        return null;
                    }
                }
                return mCurrent;
            }
        }

        #endregion
    }
}


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

<title>io.limberest.api.validate.params Class Hierarchy (Limberest API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package io.limberest.api.validate.params

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

io.limberest.api.validate.params.BodyParameterValidator (implements io.limberest.api.validate.params.ParameterValidator<T>)

io.limberest.api.validate.params.ParameterValidators

io.limberest.api.validate.params.SimpleParameterValidator

io.limberest.api.validate.params.HeaderParameterValidator (implements io.limberest.api.validate.params.ParameterValidator<T>)

io.limberest.api.validate.params.PathParameterValidator (implements io.limberest.api.validate.params.ParameterValidator<T>)

io.limberest.api.validate.params.QueryParameterValidator (implements io.limberest.api.validate.params.ParameterValidator<T>)

Interface Hierarchy

io.limberest.api.validate.params.ParameterValidator<T>

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2018


text:
package com.intellij.openapi.editor.colors.impl;

import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.editor.colors.EditorFontCache;
import com.intellij.openapi.editor.colors.FontPreferences;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@State(name = "DefaultFont", storages = @Storage("editor.xml"))
public class AppEditorFontOptions implements PersistentStateComponent<AppEditorFontOptions.PersistentFontPreferences> {

  private final FontPreferencesImpl myFontPreferences = new FontPreferencesImpl();

  public AppEditorFontOptions() {
    myFontPreferences.register(
      FontPreferences.DEFAULT_FONT_NAME,
      UISettings.restoreFontSize(FontPreferences.DEFAULT_FONT_SIZE, 1.0f));
  }

  public static class PersistentFontPreferences {
    public int FONT_SIZE = FontPreferences.DEFAULT_FONT_SIZE;
    public @NotNull String FONT_FAMILY = FontPreferences.DEFAULT_FONT_NAME;
    public float FONT_SCALE = 1.0f;

    /**
     * Serialization constructor.
     */
    @SuppressWarnings("unused")
    private PersistentFontPreferences() {
    }

    public PersistentFontPreferences(FontPreferences fontPreferences) {
      FONT_FAMILY = fontPreferences.getFontFamily();
      FONT_SIZE = fontPreferences.getSize(FONT_FAMILY);
      FONT_SCALE = UISettings.getNormalizingScale();
    }
  }

  public static AppEditorFontOptions getInstance() {
    return ServiceManager.getService(AppEditorFontOptions.class);
  }

  @Nullable
  @Override
  public PersistentFontPreferences getState() {
    return new PersistentFontPreferences(myFontPreferences);
  }

  @Override
  public void loadState(PersistentFontPreferences state) {
    myFontPreferences.clear();
    int fontSize = UISettings.restoreFontSize(state.FONT_SIZE, state.FONT_SCALE);
    myFontPreferences.register(state.FONT_FAMILY, fontSize);
    myFontPreferences.setChangeListener(() -> EditorFontCache.getInstance().reset());
  }

  @NotNull
  public FontPreferences getFontPreferences() {
    return myFontPreferences;
  }
}


text:
package org.opencb.cellbase.core.serializer;

import java.io.IOException;

/**
 * Created by parce on 9/02/15.
 */
public interface CellBaseSerializer {

    void serialize(Object object);

    void close() throws IOException;

}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-547-2.js
 * @description ES5 Attributes - Updating a named accessor property 'P' whose [[Configurable]] attribute is false to a data property does not succeed, 'A' is an Arguments object (8.12.9 step 9.a)
 */

function testcase() {
        var obj = (function () {
            return arguments;
        }());

        obj.verifySetFunc = "data";
        var getFunc = function () {
            return obj.verifySetFunc;
        };

        var setFunc = function (value) {
            obj.verifySetFunc = value;
        };

        Object.defineProperty(obj, "prop", {
            get: getFunc,
            set: setFunc,
            enumerable: true,
            configurable: false
        });
        var desc1 = Object.getOwnPropertyDescriptor(obj, "prop");

        try {
            Object.defineProperty(obj, "prop", {
                value: 1001
            });

            return false;
        } catch (e) {
            var desc2 = Object.getOwnPropertyDescriptor(obj, "prop");

            return desc1.hasOwnProperty("get") && !desc2.hasOwnProperty("value") && e instanceof TypeError &&
                accessorPropertyAttributesAreCorrect(obj, "prop", getFunc, setFunc, "verifySetFunc", true, false);
        }
    }
runTestCase(testcase);


text:
jQuery(function() {
	"use strict"

	jQuery.sap.require("sap/m/Panel");
	jQuery.sap.require("sap/m/Text");

	var oPanel = new sap.m.Panel({
		headerText: "README",
		expandable: true,
		expanded: true
	});
	var oText = new sap.m.Text();

	oText.setText("******Definition******\n" +
		"	The function iStartMyAppInAFrame allows starting an app by using a (index).html\n" +
		"	The (index).html file will be displayed in a new iFrame\n\n" +
		"******Use Case******\n" +
		"	Use iStartMyAppInAFrame if you would like to run your app isolated in its own iFrame\n\n" +
		"******Advantages******\n" +
		"+ Isolated testing environment for your app\n\n" +
		"******Disadvantages******\n" +
		"- Debugging is more complex because you have to switch between different frames\n" +
		"- Client side code coverage is not available\n" +
		"- Tests are very slow because each frame has to load the sap.ui.core separately\n" +
		"	");

	oPanel.addContent(oText);
	oPanel.placeAt("readme");

});


text:
using System;
using System.Windows.Forms;
using Be.Windows.Forms;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Drawing;

namespace NBTExplorer.Windows
{
    public partial class HexEditor : Form
    {
        private abstract class EditView
        {
            protected EditView (StatusStrip statusBar, int bytesPerElem)
            {
                BytesPerElem = bytesPerElem;
                StatusBar = statusBar;
            }

            public event EventHandler Modified;

            public int BytesPerElem { get; set; }
            public StatusStrip StatusBar { get; set; }

            public abstract TabPage TabPage { get; }

            public abstract void Initialize ();
            public abstract void Activate ();
            public abstract byte[] GetRawData ();
            public abstract void SetRawData (byte[] data);

            protected virtual void OnModified ()
            {
                var ev = Modified;
                if (ev != null)
                    ev(this, EventArgs.Empty);
            }
        }

        private class TextView : EditView
        {
            private TabPage _tabPage;
            private TextBox _textBox;

            private ToolStripStatusLabel _elementLabel;
            private ToolStripStatusLabel _spaceLabel;

            private Dictionary<int, int> _elemIndex = new Dictionary<int, int>();

            public TextView (StatusStrip statusBar, int bytesPerElem)
                : base(statusBar, bytesPerElem)
            { }

            public override void Initialize ()
            {
                _textBox = new TextBox() {
                    Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                    Font = new Font("Courier New", 9F, FontStyle.Regular, GraphicsUnit.Point, 0),
                    Location = new Point(0, 0),
                    Margin = new Padding(0),
                    Multiline = true,
                    ScrollBars = ScrollBars.Vertical,
                    Size = new Size(500, 263),
                    TabIndex = 0,
                    MaxLength = 0,
                };

                _tabPage = new TabPage() {
                    Location = new Point(4, 22),
                    Padding = new Padding(3),
                    Size = new Size(500, 263),
                    TabIndex = 1,
                    Text = "Text View",
                    UseVisualStyleBackColor = true,
                };

                _tabPage.Controls.Add(_textBox);

                _textBox.TextChanged += (s, e) => { OnModified(); RebuildElementIndex(); };
                _textBox.PreviewKeyDown += (s, e) => { e.IsInputKey = true; };
                _textBox.KeyUp += (s, e) => { UpdateElementLabel(); };
                _textBox.MouseClick += (s, e) => { UpdateElementLabel(); };

                InitializeStatusBar();
            }

            private void InitializeStatusBar ()
            {
                _elementLabel = new ToolStripStatusLabel() {
                    Size = new Size(100, 17),
                    Text = "Element 0",
                    TextAlign = ContentAlignment.MiddleLeft,
                };

                _spaceLabel = new ToolStripStatusLabel() {
                    Spring = true,
                };
            }

            public override void Activate ()
            {
                StatusBar.Items.Clear();
                StatusBar.Items.AddRange(new ToolStripItem[] {
                    _elementLabel, _spaceLabel,
                });
            }

            public override TabPage TabPage
            {
                get { return _tabPage; }
            }

            public override byte[] GetRawData ()
            {
                return HexEditor.TextToRaw(_textBox.Text, BytesPerElem);
            }

            public override void SetRawData (byte[] data)
            {
                _textBox.Text = HexEditor.RawToText(data, BytesPerElem);
                RebuildElementIndex();
            }

            private void RebuildElementIndex ()
            {
                _elemIndex.Clear();

                int element = 0;
                String text = _textBox.Text;
                bool lcw = true;

                for (int i = 0; i < text.Length; i++) {
                    bool w = IsWhiteSpace(text[i]);
                    if (lcw && !w)
                        _elemIndex[i] = element++;
                    lcw = w;
                }
            }

            private bool IsWhiteSpace (char c)
            {
                return c == ' ' || c == '\n' || c == '\r' || c == '\t';
            }

            private void UpdateElementLabel ()
            {
                int index = _textBox.SelectionStart;
                int element = 0;

                while (index >= 0 && !_elemIndex.TryGetValue(index, out element))
                    index--;

                _elementLabel.Text = "Element " + element;
            }
        }

        private class HexView : EditView
        {
            private TabPage _tabPage;
            private HexBox _hexBox;

            private ToolStripStatusLabel _positionLabel;
            private ToolStripStatusLabel _elementLabel;
            private ToolStripStatusLabel _spaceLabel;
            private ToolStripStatusLabel _insertLabel;

            private DynamicByteProvider _byteProvider;

            public HexView (StatusStrip statusBar, int bytesPerElem)
                : base(statusBar, bytesPerElem)
            { }

            public override void Initialize ()
            {
                _byteProvider = new DynamicByteProvider(new byte[0]);
                _byteProvider.Changed += (o, e) => { OnModified(); };

                _hexBox = new HexBox() {
                    Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                    Font = new Font("Courier New", 9F, FontStyle.Regular, GraphicsUnit.Point, 0),
                    LineInfoForeColor = Color.Empty,
                    LineInfoVisible = true,
                    Location = new Point(0, 0),
                    ShadowSelectionColor = Color.FromArgb(100, 60, 188, 255),
                    Size = new Size(500, 263),
                    TabIndex = 0,
                    VScrollBarVisible = true,
                    ByteProvider = _byteProvider,
                };

                _tabPage = new TabPage() {
                    Location = new Point(4, 22),
                    Padding = new Padding(3),
                    Size = new Size(500, 263),
                    TabIndex = 0,
                    Text = "Hex View",
                    UseVisualStyleBackColor = true,
                };

                _tabPage.Controls.Add(_hexBox);

                _hexBox.HorizontalByteCountChanged += (s, e) => { UpdatePosition(); };
                _hexBox.CurrentLineChanged += (s, e) => { UpdatePosition(); };
                _hexBox.CurrentPositionInLineChanged += (s, e) => { UpdatePosition(); };

                _hexBox.InsertActiveChanged += (s, e) => { _insertLabel.Text = (_hexBox.InsertActive) ? "Insert" : "Overwrite"; };

                InitializeStatusBar();
            }

            private void InitializeStatusBar ()
            {
                _positionLabel = new ToolStripStatusLabel() {
                    AutoSize = false,
                    Size = new Size(100, 17),
                    Text = "0000",
                };

                _elementLabel = new ToolStripStatusLabel() {
                    Size = new Size(59, 17),
                    Text = "Element 0",
                    TextAlign = ContentAlignment.MiddleLeft,
                };

                _spaceLabel = new ToolStripStatusLabel() {
                    Size = new Size(300, 17),
                    Spring = true,
                };

                _insertLabel = new ToolStripStatusLabel() {
                    Size = new Size(58, 17),
                    Text = (_hexBox.InsertActive) ? "Insert" : "Overwrite",
                };
            }

            public override void Activate ()
            {
                StatusBar.Items.Clear();
                StatusBar.Items.AddRange(new ToolStripItem[] {
                    _positionLabel, _elementLabel, _spaceLabel, _insertLabel,
                });

                UpdatePosition();
            }

            public override TabPage TabPage
            {
                get { return _tabPage; }
            }

            public override byte[] GetRawData ()
            {
                byte[] data = new byte[_byteProvider.Length];
                for (int i = 0; i < data.Length; i++) {
                    data[i] = _byteProvider.Bytes[i];
                }

                return data;
            }

            public override void SetRawData (byte[] data)
            {
                _byteProvider = new DynamicByteProvider(data);
                _byteProvider.Changed += (o, e2) => { OnModified(); };

                _hexBox.ByteProvider = _byteProvider;
            }

            private void UpdatePosition ()
            {
                long pos = (_hexBox.CurrentLine - 1) * _hexBox.HorizontalByteCount + _hexBox.CurrentPositionInLine - 1;

                _positionLabel.Text = "0x" + pos.ToString("X4");
                _elementLabel.Text = "Element " + pos / BytesPerElem;
            }
        }

        private class FixedByteProvider : DynamicByteProvider
        {
            public FixedByteProvider (byte[] data)
                : base(data)
            { }

            public override bool SupportsInsertBytes ()
            {
                return false;
            }
        }

        private TabPage _previousPage;
        private int _bytesPerElem;
        private byte[] _data;
        private bool _modified;

        private Dictionary<TabPage, EditView> _views = new Dictionary<TabPage, EditView>();

        public HexEditor (string tagName, byte[] data, int bytesPerElem)
        {
            InitializeComponent();

            EditView textView = new TextView(statusStrip1, bytesPerElem);
            textView.Initialize();
            textView.SetRawData(data);
            textView.Modified += (s, e) => { _modified = true; };

            _views.Add(textView.TabPage, textView);
            viewTabs.TabPages.Add(textView.TabPage);

            EditView hexView = null;

            if (!IsMono()) {
                hexView = new HexView(statusStrip1, bytesPerElem);
                hexView.Initialize();
                hexView.SetRawData(data);
                hexView.Modified += (s, e) => { _modified = true; };

                _views.Add(hexView.TabPage, hexView);
                viewTabs.TabPages.Add(hexView.TabPage);
            }

            if (bytesPerElem > 1 || IsMono()) {
                textView.Activate();
                viewTabs.SelectedTab = textView.TabPage;
            }
            else {
                hexView.Activate();
                viewTabs.SelectedTab = hexView.TabPage;
            }

            viewTabs.Deselected += (o, e) => { _previousPage = e.TabPage; };
            viewTabs.Selecting += HandleTabChanged;

            this.Text = "Editing: " + tagName;

            _bytesPerElem = bytesPerElem;

            _data = new byte[data.Length];
            Array.Copy(data, _data, data.Length);
        }

        private bool IsMono ()
        {
            return Type.GetType("Mono.Runtime") != null;
        }

        public byte[] Data
        {
            get { return _data; }
        }

        public bool Modified
        {
            get { return _modified; }
        }

        private void HandleTabChanged (object sender, TabControlCancelEventArgs e)
        {
            if (e.Action != TabControlAction.Selecting)
                return;

            if (e.TabPage == _previousPage)
                return;

            EditView oldView = _views[_previousPage];
            EditView newView = _views[e.TabPage];

            byte[] data = oldView.GetRawData();
            newView.SetRawData(data);

            newView.Activate();
        }

        private void Apply ()
        {
            EditView view = _views[viewTabs.SelectedTab];
            _data = view.GetRawData();

            DialogResult = DialogResult.OK;
            Close();
        }

        private String RawToText (byte[] data)
        {
            return RawToText(data, _bytesPerElem);
        }

        private static String RawToText (byte[] data, int bytesPerElem)
        {
            switch (bytesPerElem) {
                case 1: return RawToText(data, bytesPerElem, 16);
                case 2: return RawToText(data, bytesPerElem, 8);
                case 4: return RawToText(data, bytesPerElem, 4);
                case 8: return RawToText(data, bytesPerElem, 2);
                default: return RawToText(data, bytesPerElem, 1);
            }
        }

        private static String RawToText (byte[] data, int bytesPerElem, int elementsPerLine)
        {
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < data.Length; i += bytesPerElem) {
                if (data.Length - i < bytesPerElem)
                    break;

                switch (bytesPerElem) {
                    case 1:
                        builder.Append(((sbyte)data[i]).ToString());
                        break;

                    case 2:
                        builder.Append(BitConverter.ToInt16(data, i).ToString());
                        break;

                    case 4:
                        builder.Append(BitConverter.ToInt32(data, i).ToString());
                        break;

                    case 8:
                        builder.Append(BitConverter.ToInt64(data, i).ToString());
                        break;
                }

                if ((i / bytesPerElem) % elementsPerLine == elementsPerLine - 1)
                    builder.AppendLine();
                else
                    builder.Append("  ");
            }

            return builder.ToString();
        }

        private byte[] TextToRaw (string text)
        {
            return TextToRaw(text, _bytesPerElem);
        }

        private static byte[] TextToRaw (string text, int bytesPerElem)
        {
            string[] items = text.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
            byte[] data = new byte[bytesPerElem * items.Length];

            for (int i = 0; i < items.Length; i++) {
                int index = i * bytesPerElem;

                switch (bytesPerElem) {
                    case 1:
                        sbyte val1;
                        if (sbyte.TryParse(items[i], out val1))
                            data[index] = (byte)val1;
                        break;

                    case 2:
                        short val2;
                        if (short.TryParse(items[i], out val2)) {
                            byte[] buffer = BitConverter.GetBytes(val2);
                            Array.Copy(buffer, 0, data, index, 2);
                        }
                        break;

                    case 4:
                        int val4;
                        if (int.TryParse(items[i], out val4)) {
                            byte[] buffer = BitConverter.GetBytes(val4);
                            Array.Copy(buffer, 0, data, index, 4);
                        }
                        break;

                    case 8:
                        long val8;
                        if (long.TryParse(items[i], out val8)) {
                            byte[] buffer = BitConverter.GetBytes(val8);
                            Array.Copy(buffer, 0, data, index, 8);
                        }
                        break;
                }
            }

            return data;
        }

        private void ImportRaw (string path)
        {
            try {
                using (FileStream fstr = File.OpenRead(path)) {
                    _data = new byte[fstr.Length];
                    fstr.Read(_data, 0, (int)fstr.Length);

                    EditView view = _views[viewTabs.SelectedTab];
                    view.SetRawData(_data);

                    _modified = true;
                }
            }
            catch (Exception e) {
                MessageBox.Show("Failed to import data from \"" + path + "\"\n\nException: " + e.Message);
            }
        }

        private void ImportText (string path)
        {
            try {
                using (FileStream fstr = File.OpenRead(path)) {
                    byte[] raw = new byte[fstr.Length];
                    fstr.Read(raw, 0, (int)fstr.Length);

                    string text = System.Text.Encoding.UTF8.GetString(raw, 0, raw.Length);
                    _data = TextToRaw(text);

                    EditView view = _views[viewTabs.SelectedTab];
                    view.SetRawData(_data);

                    _modified = true;
                }
            }
            catch (Exception e) {
                MessageBox.Show("Failed to import data from \"" + path + "\"\n\nException: " + e.Message);
            }
        }

        private void ExportRaw (string path)
        {
            try {
                using (FileStream fstr = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None)) {
                    EditView view = _views[viewTabs.SelectedTab];
                    byte[] data = view.GetRawData();

                    fstr.Write(data, 0, data.Length);
                }
            }
            catch (Exception e) {
                MessageBox.Show("Failed to export data to \"" + path + "\"\n\nException: " + e.Message);
            }
        }

        private void ExportText (string path)
        {
            try {
                using (FileStream fstr = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None)) {
                    EditView view = _views[viewTabs.SelectedTab];
                    string text = RawToText(view.GetRawData());

                    byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
                    fstr.Write(data, 0, data.Length);
                }
            }
            catch (Exception e) {
                MessageBox.Show("Failed to export data to \"" + path + "\"\n\nException: " + e.Message);
            }
        }

        private void _buttonOK_Click (object sender, EventArgs e)
        {
            Apply();
        }

        private void _buttonImport_Click (object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog()) {
                ofd.RestoreDirectory = true;
                ofd.Multiselect = false;
                ofd.Filter = "Binary Data|*|Text Data (*.txt)|*.txt";
                ofd.FilterIndex = 0;

                if (ofd.ShowDialog() == DialogResult.OK) {
                    if (Path.GetExtension(ofd.FileName) == ".txt")
                        ImportText(ofd.FileName);
                    else
                        ImportRaw(ofd.FileName);
                }
            }
        }

        private void _buttonExport_Click (object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog()) {
                sfd.RestoreDirectory = true;
                sfd.Filter = "Binary Data|*|Text Data (*.txt)|*.txt";
                sfd.FilterIndex = 0;
                sfd.OverwritePrompt = true;

                if (sfd.ShowDialog() == DialogResult.OK) {
                    if (Path.GetExtension(sfd.FileName) == ".txt")
                        ExportText(sfd.FileName);
                    else
                        ExportRaw(sfd.FileName);
                }
            }
        }
    }
}


text:
"""
Config file specific to uk to create automated survey
"""

class config:

    additional_language = 'nl'
    # To modify, just add the keys of the dictionary
    header_to_modify = [{'class': 'S', 'name': 'sid', 'text': '421498'},
                        {'class': 'S', 'name': 'admin_email', 'text': 'olivier.philippe@soton.ac.uk'}]
    # Same as header_to_modify
    description_to_modify = []

    # Add header and description. Tuple of a dictionary + the position where it is supposed
    # to be inserted
    header_to_add = []
    description_to_add = [({'class': 'S', 'name': 'additional_languages', 'text': 'nl'}, 12)] # The index positions starts at 0


text:
"""
Support for Futures (asynchronously executed callables).
If you're using Python 3.2 or newer, also see
http://docs.python.org/3/library/concurrent.futures.html#future-objects

Pyro - Python Remote Objects.  Copyright by Irmen de Jong (irmen@razorvine.net).
"""

import sys
import functools
import logging
import threading
import time

__all__ = ["Future", "FutureResult", "_ExceptionWrapper"]

log = logging.getLogger("Pyro4.futures")

class Future(object):
    """
    Holds a callable that will be executed asynchronously and provide its
    result value some time in the future.
    This is a more general implementation than the AsyncRemoteMethod, which
    only works with Pyro proxies (and provides a bit different syntax).
    This class has a few extra features as well (delay, canceling).
    """

    def __init__(self, somecallable):
        self.callable = somecallable
        self.chain = []
        self.exceptionhandler = None
        self.call_delay = 0
        self.cancelled = False
        self.completed = False

    def __call__(self, *args, **kwargs):
        """
        Start the future call with the provided arguments.
        Control flow returns immediately, with a FutureResult object.
        """
        if self.completed or not hasattr(self, "chain"):
            raise RuntimeError("the future has already been evaluated")
        if self.cancelled:
            raise RuntimeError("the future has been cancelled")
        chain = self.chain
        del self.chain  # make it impossible to add new calls to the chain once we started executing it
        result = FutureResult()  # notice that the call chain doesn't sit on the result object
        thread = threading.Thread(target=self.__asynccall, args=(result, chain, args, kwargs))
        thread.setDaemon(True)
        thread.start()
        return result

    def __asynccall(self, asyncresult, chain, args, kwargs):
        while self.call_delay > 0 and not self.cancelled:
            delay = min(self.call_delay, 2)
            time.sleep(delay)
            self.call_delay -= delay
        if self.cancelled:
            self.completed = True
            asyncresult.set_cancelled()
            return
        try:
            self.completed = True
            self.cancelled = False
            value = self.callable(*args, **kwargs)
            # now walk the callchain, passing on the previous value as first argument
            for call, args, kwargs in chain:
                call = functools.partial(call, value)
                value = call(*args, **kwargs)
            asyncresult.value = value
        except Exception as x:
            if self.exceptionhandler:
                self.exceptionhandler(x)
            asyncresult.value = _ExceptionWrapper(x)

    def delay(self, seconds):
        """
        Delay the evaluation of the future for the given number of seconds.
        Return True if successful otherwise False if the future has already been evaluated.
        """
        if self.completed:
            return False
        self.call_delay = seconds
        return True

    def cancel(self):
        """
        Cancels the execution of the future altogether.
        If the execution hasn't been started yet, the cancellation is successful and returns True.
        Otherwise, it failed and returns False.
        """
        if self.completed:
            return False
        self.cancelled = True
        return True

    def then(self, call, *args, **kwargs):
        """
        Add a callable to the call chain, to be invoked when the results become available.
        The result of the current call will be used as the first argument for the next call.
        Optional extra arguments can be provided in args and kwargs.
        Returns self so you can easily chain then() calls.
        """
        self.chain.append((call, args, kwargs))
        return self

    def iferror(self, exceptionhandler):
        """
        Specify the exception handler to be invoked (with the exception object as only
        argument) when calculating the result raises an exception.
        If no exception handler is set, any exception raised in the asynchronous call will be silently ignored.
        Returns self so you can easily chain other calls.
        """
        self.exceptionhandler = exceptionhandler
        return self

class FutureResult(object):
    """
    The result object for asynchronous Pyro calls.
    Unfortunatley it should be similar to the more general Future class but
    it is still somewhat limited (no delay, no canceling).
    """

    def __init__(self):
        self.__ready = threading.Event()
        self.callchain = []
        self.valueLock = threading.Lock()
        self.exceptionhandler = None

    def wait(self, timeout=None):
        """
        Wait for the result to become available, with optional timeout (in seconds).
        Returns True if the result is ready, or False if it still isn't ready.
        """
        result = self.__ready.wait(timeout)
        if result is None:
            # older pythons return None from wait()
            return self.__ready.isSet()
        return result

    @property
    def ready(self):
        """Boolean that contains the readiness of the asynchronous result"""
        return self.__ready.isSet()

    def get_value(self):
        self.__ready.wait()
        if isinstance(self.__value, _ExceptionWrapper):
            self.__value.raiseIt()
        else:
            return self.__value

    def set_value(self, value):
        with self.valueLock:
            self.__value = value
            # walk the call chain if the result is not an exception, otherwise invoke the errorhandler (if any)
            if isinstance(value, _ExceptionWrapper):
                if self.exceptionhandler:
                    self.exceptionhandler(value.exception)
            else:
                for call, args, kwargs in self.callchain:
                    call = functools.partial(call, self.__value)
                    self.__value = call(*args, **kwargs)
                    if isinstance(self.__value, _ExceptionWrapper):
                        break
            self.callchain = []
            self.__ready.set()

    value = property(get_value, set_value, None, "The result value of the call. Reading it will block if not available yet.")

    def set_cancelled(self):
        self.set_value(_ExceptionWrapper(RuntimeError("future has been cancelled")))

    def then(self, call, *args, **kwargs):
        """
        Add a callable to the call chain, to be invoked when the results become available.
        The result of the current call will be used as the first argument for the next call.
        Optional extra arguments can be provided in args and kwargs.
        Returns self so you can easily chain then() calls.
        """
        with self.valueLock:
            if self.__ready.isSet():
                # value is already known, we need to process it immediately (can't use the call chain anymore)
                call = functools.partial(call, self.__value)
                self.__value = call(*args, **kwargs)
            else:
                # add the call to the call chain, it will be processed later when the result arrives
                self.callchain.append((call, args, kwargs))
            return self

    def iferror(self, exceptionhandler):
        """
        Specify the exception handler to be invoked (with the exception object as only
        argument) when asking for the result raises an exception.
        If no exception handler is set, any exception result will be silently ignored (unless
        you explicitly ask for the value). Returns self so you can easily chain other calls.
        """
        self.exceptionhandler = exceptionhandler
        return self

class _ExceptionWrapper(object):
    """Class that wraps a remote exception. If this is returned, Pyro will
    re-throw the exception on the receiving side. Usually this is taken care of
    by a special response message flag, but in the case of batched calls this
    flag is useless and another mechanism was needed."""

    def __init__(self, exception):
        self.exception = exception

    def raiseIt(self):
        from Pyro4.util import fixIronPythonExceptionForPickle  # XXX circular
        if sys.platform == "cli":
            fixIronPythonExceptionForPickle(self.exception, False)
        raise self.exception

    def __serialized_dict__(self):
        """serialized form as a dictionary"""
        from Pyro4.util import SerializerBase  # XXX circular
        return {
            "__class__": "Pyro4.futures._ExceptionWrapper",
            "exception": SerializerBase.class_to_dict(self.exception)
        }


text:
package org.rdtif.zaxslackbot;

import com.google.inject.Guice;
import org.rdtif.zaxslackbot.slack.SlackApplicationServer;

import javax.inject.Inject;

class ZaxSlackBot {
    public static void main(String... arguments) {
        Guice.createInjector(new ZaxSlackBotModule()).getInstance(ZaxSlackBot.class).run();
    }

    private final SlackApplicationServer slackApplicationServer;

    @Inject
    ZaxSlackBot(SlackApplicationServer slackApplicationServer) {
        this.slackApplicationServer = slackApplicationServer;
    }

    void run() {
        slackApplicationServer.start();
    }
}


text:
description: This template allows you deploy a cluster into your VNet.
page_type: sample
products:
- azure
- azure-resource-manager
urlFragment: kusto-vnet
languages:
- json
---
# Deploy Azure Data Explorer cluster into your VNet.

![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.kusto/kusto-vnet/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.kusto/kusto-vnet/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.kusto/kusto-vnet/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.kusto/kusto-vnet/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.kusto/kusto-vnet/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.kusto/kusto-vnet/CredScanResult.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.kusto%2Fkusto-vnet%2Fazuredeploy.json)
[![Deploy To Azure US Gov](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazuregov.svg?sanitize=true)](https://portal.azure.us/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.kusto%2Fkusto-vnet%2Fazuredeploy.json)
[![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.kusto%2Fkusto-vnet%2Fazuredeploy.json)

This template allows you deploy a cluster into your VNet.

`Tags: Microsoft.Kusto/Clusters, Microsoft.Network/networkSecurityGroups, Microsoft.Network/routeTables, Microsoft.Network/publicIPAddresses, Microsoft.Network/virtualNetworks`


text:
  <button class="menu-button" (click)="toggleMenu()" [class.gold]="_menuState">

  </button>

<app-side-menu [menuState]="_menuState"></app-side-menu>


text:
name: Kong Path Whitelist
publisher: Seifchen

categories:
  - security

type: plugin

desc: Determine if the path is in the path whitelist, and if not, return a 403

description: |
  You can use the Kong Path Whitelist plugin on a Service, Route, or Consumer with paths. The plugin will check if the path is in the path whitelist, and if not, return a 403.

support_url: https://github.com/seifchen/kong-path-whitelist/issues

source_url: https://github.com/seifchen/kong-path-whitelist

license_type: Apache-2.0

kong_version_compatibility:
  community_edition:
    compatible:
      - 2.0.x
      - 1.5.x
      - 1.4.x
      - 1.3.x
      - 1.2.x

params:
  name: kong-path-whitelist
  api_id: false
  service_id: true
  consumer_id: true
  route_id: true
  protocols: ["http", "https"]
  dbless_compatible: yes

  config:
    - name: white_paths
      required: yes
      default: []
      value_in_examples: ["/api/services", "/api/routes"]
      description: An allowed path. Any request path that does not match one of the paths in this list will be forbidden and return a 403 error code.
    - name: regex
      required: true
      default: true
      value_in_examples:
      description: A boolean value that specifies whether the plugin uses regex for path matching. If `true`, the plugin will use `ngx.re.match` to match the `request_path` and `white_paths` values. If `false`, it will strictly judge whether the two paths are equal.

---

# Install
### Luarocks
```
luarocks install kong-path-whitelist
```

### Source Code
```
$ git clone https://github.com/seifchen/kong-path-whitelist.git
$ cd /path/to/kong/plugins/kong-path-whitelist
$ luarocks make *.rockspec
```
See the README in the plugin source repository for more usage examples.

### Maintainers
[seifchen](https://github.com/seifchen)


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

<title>com.binghamton.jhelp.util</title>
<meta name="date" content="2021-03-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.binghamton.jhelp.util

Interfaces

StringMatcher.CharEquater

Classes

ArrayUtils

ColorStringBuilder

Compiler

DamerauLevenshteinStringMatcher

DiGraph

FileBuffer

LevenshteinStringMatcher

Logger

StringMatcher

StringUtils

SymbolFinder

Enums

ColorStringBuilder.Color

ColorStringBuilder.Format


text:
class PageTagging < ActiveRecord::Base
  belongs_to :page
  belongs_to :page_tag, :counter_cache => true
end