text:
#ifndef WASMINT_JITCOMPILER_H
#define WASMINT_JITCOMPILER_H

#include "RegisterAllocator.h"
#include "ByteCode.h"
#include <Function.h>
#include <stdexcept>

namespace wasmint {
    class WasmintVM;

    ExceptionMessage(CompilerHasNotCompiledInstruction)

    class JITCompiler {

        ByteCode code_;
        std::map<const wasm_module::Instruction*, uint32_t> instructionStartAddresses;
        std::map<const wasm_module::Instruction*, uint32_t> instructionEndAddresses;

        std::map<uint32_t, const wasm_module::Instruction*> instructionFinishedAddresses;

        std::vector<std::pair<const wasm_module::Instruction*, uint32_t>> needsInstructionStartAddress;
        std::vector<std::pair<const wasm_module::Instruction*, uint32_t>> needsInstructionEndAddress;
        std::vector<std::pair<wasm_module::FunctionSignature, uint32_t>> needsFunctionIndex;

        void compileInstruction(const wasm_module::Instruction* instruction);

        void addBranchAddress(const wasm_module::Instruction* instruction, bool before);
        void addBranchAddress(const wasm_module::BranchInformation* information);
        void addBranch(const wasm_module::Instruction* instruction, bool before);
        void addBranch(const wasm_module::BranchInformation* information);
        void addBranchIf(const wasm_module::BranchInformation* information);
        void addBranchIfNot(const wasm_module::BranchInformation* information);
        void addBranchIf(const wasm_module::Instruction* instruction, bool before);
        void addBranchIfNot(const wasm_module::Instruction* instruction, bool before);

        void linkLocally();

    public:
        JITCompiler() {
        }

        void compile(const wasm_module::Function* function);

        const ByteCode& code() const {
            return code_;
        }

        void linkGlobally(WasmintVM* registerMachine);

        const wasm_module::Instruction* getInstruction(uint32_t address) const {
            auto iter = instructionFinishedAddresses.find(address);
            if (iter != instructionFinishedAddresses.end()) {
                return iter->second;
            } else {
                return nullptr;
            }
        }

        uint32_t getInstructionEndAddress(const wasm_module::Instruction* instruction) const {
            auto iter = instructionEndAddresses.find(instruction);
            if (iter != instructionEndAddresses.end()) {
                return iter->second;
            }
            throw CompilerHasNotCompiledInstruction(instruction->dataString());
        }
    };
}

#endif //WASMINT_JITCOMPILER_H


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Achras pohlmaniana F.Muell.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <title>Say I Won't!?</title>

  <link href="lib/ionic/css/ionic.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

    <ion-header-bar class="bar bar-header bar-dark" ng-controller="loginCtrl">
       <button class="button icon ion-person">
        Friends
      </button>

Say I Won't?!

      <button class="button" ng-show="getAuthState()" ng-click="logout()">Logout</button>
    </ion-header-bar>

    <ion-nav-view class="has-header"></ion-nav-view>
    <ion-tabs class="tabs-dark tabs-icon-only">
      <ion-tab ui-sref="home" title="Home" icon-on="ion-ios-home" icon-off="ion-ios-home-outline"></ion-tab>
      <ion-tab ui-sref="video" title="Challenge" icon-on="ion-videocamera" icon-off="ion-videocamera"></ion-tab>
      <ion-tab ui-sref="responses" title="Settings" icon-on="ion-ios-cog" icon-off="ion-ios-gear-outline"></ion-tab>
    </ion-tabs>


text:
<?php

namespace Minimalism\Test;

use Minimalism\Terminal as T;
use Minimalism\Terminal;

require __DIR__ . "/../src/Terminal.php";

$t = new Terminal();

echo "123\n";

$t->cursorUp();
$t->cursorForward(1);

$t->setGraphicsMode(Terminal::FG_RED);
while (true) {
    echo time() & 1;
    $t->cursorBackward(1);
    sleep(1);
}


text:
package main

import (
	"flag"
	"fmt"
	"github.com/aodin/aspect"
	_ "github.com/aodin/aspect/postgres"
	"github.com/aodin/denver/grocery"
	"github.com/aodin/volta/config"
)

func InitSQL() {
	// TODO Actually create the table
	fmt.Println(grocery.Stores.Create())
}

// TODO Does not clear previous entries
func LoadFile(db *aspect.DB, path string) error {
	stores, err := grocery.ParseConvertedStoresCSV(path)
	if err != nil {
		return err
	}
	stmt := grocery.Stores.Insert(stores)
	_, err = db.Execute(stmt)
	return err
}

func main() {
	var init bool
	var load string
	flag.BoolVar(&init, "init", false, "print SQL for CREATE TABLE")
	flag.StringVar(&load, "load", "", "load the given file")
	flag.Parse()

	// Get the database driver
	c, err := config.ParseFile("../../settings.json")
	if err != nil {
		panic(err)
	}

	if init {
		InitSQL()
	}

	if load != "" {
		// Connect
		db, err := aspect.Connect(
			c.Database.Driver,
			c.Database.Credentials(),
		)
		if err != nil {
			panic(err)
		}
		if err = LoadFile(db, load); err != nil {
			panic(err)
		}
	}
}

// CREATE TABLE "hearings" (
//   "id" INTEGER PRIMARY KEY,
//   "notice_link" VARCHAR,
//   "name" VARCHAR,
//   "address" VARCHAR,
//   "latitude" REAL,
//   "longitude" REAL,
//   "time" TIMESTAMP WITH TIME ZONE,
//   "outcome" VARCHAR
// );


text:
package org.apache.kafka.common.security.token.delegation;

import org.apache.kafka.common.security.auth.KafkaPrincipal;

import java.util.ArrayList;
import java.util.Collection;

public class TokenInformation {

    private KafkaPrincipal owner;
    private Collection<KafkaPrincipal> renewers;
    private long issueTimestamp;
    private long maxTimestamp;
    private long expiryTimestamp;
    private String tokenId;

    public TokenInformation(String tokenId, KafkaPrincipal owner, Collection<KafkaPrincipal> renewers,
                            long issueTimestamp, long maxTimestamp, long expiryTimestamp) {
        this.tokenId = tokenId;
        this.owner = owner;
        this.renewers = renewers;
        this.issueTimestamp =  issueTimestamp;
        this.maxTimestamp =  maxTimestamp;
        this.expiryTimestamp =  expiryTimestamp;
    }

    public KafkaPrincipal owner() {
        return owner;
    }

    public String ownerAsString() {
        return owner.toString();
    }

    public Collection<KafkaPrincipal> renewers() {
        return renewers;
    }

    public Collection<String> renewersAsString() {
        Collection<String> renewerList = new ArrayList<>();
        for (KafkaPrincipal renewer : renewers) {
            renewerList.add(renewer.toString());
        }
        return renewerList;
    }

    public long issueTimestamp() {
        return issueTimestamp;
    }

    public long expiryTimestamp() {
        return expiryTimestamp;
    }

    public void setExpiryTimestamp(long expiryTimestamp) {
        this.expiryTimestamp = expiryTimestamp;
    }

    public String tokenId() {
        return tokenId;
    }

    public long maxTimestamp() {
        return maxTimestamp;
    }

    public boolean ownerOrRenewer(KafkaPrincipal principal) {
        if (owner.equals(principal) || renewers.contains(principal))
            return true;
        return false;
    }

    @Override
    public String toString() {
        return "TokenInformation{" +
            "owner=" + owner +
            ", renewers=" + renewers +
            ", issueTimestamp=" + issueTimestamp +
            ", maxTimestamp=" + maxTimestamp +
            ", expiryTimestamp=" + expiryTimestamp +
            ", tokenId='" + tokenId + '\'' +
            '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        TokenInformation that = (TokenInformation) o;

        if (issueTimestamp != that.issueTimestamp) {
            return false;
        }
        if (maxTimestamp != that.maxTimestamp) {
            return false;
        }
        if (owner != null ? !owner.equals(that.owner) : that.owner != null) {
            return false;
        }
        if (renewers != null ? !renewers.equals(that.renewers) : that.renewers != null) {
            return false;
        }
        return tokenId != null ? tokenId.equals(that.tokenId) : that.tokenId == null;
    }

    @Override
    public int hashCode() {
        int result = owner != null ? owner.hashCode() : 0;
        result = 31 * result + (renewers != null ? renewers.hashCode() : 0);
        result = 31 * result + (int) (issueTimestamp ^ (issueTimestamp >>> 32));
        result = 31 * result + (int) (maxTimestamp ^ (maxTimestamp >>> 32));
        result = 31 * result + (tokenId != null ? tokenId.hashCode() : 0);
        return result;
    }
}


text:
void add(char*, char*, char*);

#endif


text:
#ifndef QPLATFORMMENU_H
#define QPLATFORMMENU_H
//
//  W A R N I N G
//  -------------
//
// This file is part of the QPA API and is not meant to be used
// in applications. Usage of this API may make your code
// source and binary incompatible with future versions of Qt.
//

#include <QtCore/qglobal.h>
#include <QtCore/qpointer.h>
#include <QtGui/QFont>
#include <QtGui/QKeySequence>
#include <QtGui/QIcon>

QT_BEGIN_NAMESPACE

class QPlatformMenu;
class Q_GUI_EXPORT QPlatformMenuItem : public QObject
{
Q_OBJECT
public:
    // copied from, and must stay in sync with, QAction menu roles.
    enum MenuRole { NoRole = 0, TextHeuristicRole, ApplicationSpecificRole, AboutQtRole,
                    AboutRole, PreferencesRole, QuitRole,
                    // However these roles are private, perhaps temporarily.
                    // They could be added as public QAction roles if necessary.
                    CutRole, CopyRole, PasteRole, SelectAllRole,
                    RoleCount };

    virtual void setTag(quintptr tag) = 0;
    virtual quintptr tag()const = 0;

    virtual void setText(const QString &text) = 0;
    virtual void setIcon(const QIcon &icon) = 0;
    virtual void setMenu(QPlatformMenu *menu) = 0;
    virtual void setVisible(bool isVisible) = 0;
    virtual void setIsSeparator(bool isSeparator) = 0;
    virtual void setFont(const QFont &font) = 0;
    virtual void setRole(MenuRole role) = 0;
    virtual void setCheckable(bool checkable) = 0;
    virtual void setChecked(bool isChecked) = 0;
    virtual void setShortcut(const QKeySequence& shortcut) = 0;
    virtual void setEnabled(bool enabled) = 0;
    virtual void setIconSize(int size) = 0;
    virtual void setNativeContents(WId item) { Q_UNUSED(item); }

Q_SIGNALS:
    void activated();
    void hovered();
};

class Q_GUI_EXPORT QPlatformMenu : public QObject
{
Q_OBJECT
public:
    enum MenuType { DefaultMenu = 0, EditMenu };

    virtual void insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before) = 0;
    virtual void removeMenuItem(QPlatformMenuItem *menuItem) = 0;
    virtual void syncMenuItem(QPlatformMenuItem *menuItem) = 0;
    virtual void syncSeparatorsCollapsible(bool enable) = 0;

    virtual void setTag(quintptr tag) = 0;
    virtual quintptr tag()const = 0;

    virtual void setText(const QString &text) = 0;
    virtual void setIcon(const QIcon &icon) = 0;
    virtual void setEnabled(bool enabled) = 0;
    virtual bool isEnabled() const { return true; }
    virtual void setVisible(bool visible) = 0;
    virtual void setMinimumWidth(int width) { Q_UNUSED(width); }
    virtual void setFont(const QFont &font) { Q_UNUSED(font); }
    virtual void setMenuType(MenuType type) { Q_UNUSED(type); }

    virtual void showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item)
    {
        Q_UNUSED(parentWindow);
        Q_UNUSED(targetRect);
        Q_UNUSED(item);
        setVisible(true);
    }

    virtual void dismiss() { } // Closes this and all its related menu popups

    virtual QPlatformMenuItem *menuItemAt(int position) const = 0;
    virtual QPlatformMenuItem *menuItemForTag(quintptr tag) const = 0;

    virtual QPlatformMenuItem *createMenuItem() const;
    virtual QPlatformMenu *createSubMenu() const;
Q_SIGNALS:
    void aboutToShow();
    void aboutToHide();
};

class Q_GUI_EXPORT QPlatformMenuBar : public QObject
{
Q_OBJECT
public:
    virtual void insertMenu(QPlatformMenu *menu, QPlatformMenu *before) = 0;
    virtual void removeMenu(QPlatformMenu *menu) = 0;
    virtual void syncMenu(QPlatformMenu *menuItem) = 0;
    virtual void handleReparent(QWindow *newParentWindow) = 0;

    virtual QPlatformMenu *menuForTag(quintptr tag) const = 0;
};

QT_END_NAMESPACE

#endif


text:
<?php

/*
 * This file is part of the MassiveSearchBundle
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Massive\Bundle\SearchBundle\Search;

/**
 * Representation of a one indexed document.
 */
class Document implements \JsonSerializable
{
    /**
     * @var Field[]
     */
    protected $fields = [];

    /**
     * @var string
     */
    protected $id;

    /**
     * @var string
     */
    protected $class;

    /**
     * @var string
     */
    protected $title;

    /**
     * @var string
     */
    protected $description;

    /**
     * @var string
     */
    protected $url;

    /**
     * @var string
     */
    protected $imageUrl;

    /**
     * @var string
     */
    protected $locale;

    /**
     * @var string
     */
    protected $index;

    /**
     * @param Field $field
     */
    public function addField(Field $field)
    {
        if ($this->hasField($field->getName())) {
            throw new \InvalidArgumentException(sprintf(
                'Field "%s" already exists in search document',
                $field->getName()
            ));
        }

        $this->fields[$field->getName()] = $field;
    }

    /**
     * @return string
     */
    public function getClass()
    {
        return $this->class;
    }

    /**
     * @param string $class
     */
    public function setClass($class)
    {
        $this->class = $class;
    }

    /**
     * Return the URL for the image which should be
     * displayed with this search result.
     *
     * @return string
     */
    public function getImageUrl()
    {
        return $this->imageUrl;
    }

    /**
     * Set the URL to the image which should be displayed
     * with this search result.
     *
     * @param string $imageUrl
     */
    public function setImageUrl($imageUrl)
    {
        $this->imageUrl = $imageUrl;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param string $description
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * @param string $url
     */
    public function setUrl($url)
    {
        $this->url = $url;
    }

    /**
     * @return string
     */
    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * @param string
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;
    }

    /**
     * @return string
     */
    public function getIndex()
    {
        return $this->index;
    }

    /**
     * @param string $index
     */
    public function setIndex($index)
    {
        $this->index = $index;
    }

    /**
     * @return Field[]
     */
    public function getFields()
    {
        return $this->fields;
    }

    /**
     * Return the named field.
     *
     * @return Field
     *
     * @throws \InvalidArgumentException When it doesn't exist
     */
    public function getField($name)
    {
        if (!isset($this->fields[$name])) {
            throw new \InvalidArgumentException(sprintf(
                'Trying to get undefined field "%s", defined fields are "%s"',
                $name, implode(', ', array_keys($this->fields))
            ));
        }

        return $this->fields[$name];
    }

    /**
     * Return true if the field exists.
     *
     * @return bool
     */
    public function hasField($name)
    {
        return isset($this->fields[$name]);
    }

    /**
     * {@inheritdoc}
     */
    public function jsonSerialize()
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'description' => $this->description,
            'class' => $this->class,
            'url' => $this->url,
            'image_url' => $this->imageUrl,
            'locale' => $this->locale,
        ];
    }
}


text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*             CLIPS Version 6.24  06/05/06            */
   /*                                                     */
   /*            SYSTEM DEPENDENT HEADER FILE             */
   /*******************************************************/

/*************************************************************/
/* Purpose: Isolation of system dependent routines.          */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*                                                           */
/* Revision History:                                         */
/*                                                           */
/*      6.24: Support for run-time programs directly passing */
/*            the hash tables for initialization.            */
/*                                                           */
/*            Added BeforeOpenFunction and AfterOpenFunction */
/*            hooks.                                         */
/*                                                           */
/*            Added environment parameter to GenClose.       */
/*            Added environment parameter to GenOpen.        */
/*                                                           */
/*************************************************************/

#ifndef _H_sysdep
#define _H_sysdep

#ifndef _H_symbol
#include "symbol.h"
#endif

#ifndef _STDIO_INCLUDED_
#define _STDIO_INCLUDED_
#include <stdio.h>
#endif

#include <setjmp.h>

#if WIN_BTC || WIN_MVC
#include <dos.h>
#endif

#if WIN_BTC
#define LLONG_MAX 0x7fffffffffffffffLL
#define LLONG_MIN (~LLONG_MAX)
#endif

#ifdef LOCALE
#undef LOCALE
#endif

#ifdef _SYSDEP_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif

   LOCALE void                        InitializeEnvironment(void);
   LOCALE void                        EnvInitializeEnvironment(void *,struct symbolHashNode **,struct floatHashNode **,
															   struct integerHashNode **,struct bitMapHashNode **,
															   struct externalAddressHashNode **);
   LOCALE void                        SetRedrawFunction(void *,void (*)(void *));
   LOCALE void                        SetPauseEnvFunction(void *,void (*)(void *));
   LOCALE void                        SetContinueEnvFunction(void *,void (*)(void *,int));
   LOCALE void                        (*GetRedrawFunction(void *))(void *);
   LOCALE void                        (*GetPauseEnvFunction(void *))(void *);
   LOCALE void                        (*GetContinueEnvFunction(void *))(void *,int);
   LOCALE void                        RerouteStdin(void *,int,char *[]);
   LOCALE double                      gentime(void);
   LOCALE void                        gensystem(void *theEnv);
   LOCALE void                        VMSSystem(char *);
   LOCALE int                         GenOpenReadBinary(void *,char *,char *);
   LOCALE void                        GetSeekCurBinary(void *,long);
   LOCALE void                        GetSeekSetBinary(void *,long);
   LOCALE void                        GenTellBinary(void *,long *);
   LOCALE void                        GenCloseBinary(void *);
   LOCALE void                        GenReadBinary(void *,void *,size_t);
   LOCALE FILE                       *GenOpen(void *,char *,char *);
   LOCALE int                         GenClose(void *,FILE *);
   LOCALE void                        genexit(void *,int);
   LOCALE int                         genrand(void);
   LOCALE void                        genseed(int);
   LOCALE int                         genremove(char *);
   LOCALE int                         genrename(char *,char *);
   LOCALE char                       *gengetcwd(char *,int);
   LOCALE void                        GenWrite(void *,size_t,FILE *);
   LOCALE int                       (*EnvSetBeforeOpenFunction(void *,int (*)(void *)))(void *);
   LOCALE int                       (*EnvSetAfterOpenFunction(void *,int (*)(void *)))(void *);
   LOCALE int                         gensprintf(char *,const char *,...);
   LOCALE char                       *genstrcpy(char *,const char *);
   LOCALE char                       *genstrncpy(char *,const char *,size_t);
   LOCALE char                       *genstrcat(char *,const char *);
   LOCALE char                       *genstrncat(char *,const char *,size_t);
   LOCALE void                        SetJmpBuffer(void *,jmp_buf *);
   LOCALE void                        genprintfile(void *,FILE *,char *);

#if WIN_BTC
   LOCALE __int64 _RTLENTRY _EXPFUNC  strtoll(const char *,char **,int);
   LOCALE __int64 _RTLENTRY _EXPFUNC  llabs(__int64 val);
#endif

#endif


text:
namespace atom {

::Atom GetAtom(const char* name) {
  return XInternAtom(gfx::GetXDisplay(), name, false);
}

void SetWMSpecState(::Window xwindow, bool enabled, ::Atom state) {
  XEvent xclient;
  memset(&xclient, 0, sizeof(xclient));
  xclient.type = ClientMessage;
  xclient.xclient.window = xwindow;
  xclient.xclient.message_type = GetAtom("_NET_WM_STATE");
  xclient.xclient.format = 32;
  xclient.xclient.data.l[0] = enabled ? 1 : 0;
  xclient.xclient.data.l[1] = state;
  xclient.xclient.data.l[2] = None;
  xclient.xclient.data.l[3] = 1;
  xclient.xclient.data.l[4] = 0;

  XDisplay* xdisplay = gfx::GetXDisplay();
  XSendEvent(xdisplay, DefaultRootWindow(xdisplay), False,
             SubstructureRedirectMask | SubstructureNotifyMask,
             &xclient);
}

void SetWindowType(::Window xwindow, const std::string& type) {
  XDisplay* xdisplay = gfx::GetXDisplay();
  std::string type_prefix = "_NET_WM_WINDOW_TYPE_";
  ::Atom window_type = XInternAtom(
      xdisplay, (type_prefix + base::StringToUpperASCII(type)).c_str(), False);
  XChangeProperty(xdisplay, xwindow,
                  XInternAtom(xdisplay, "_NET_WM_WINDOW_TYPE", False),
                  XA_ATOM,
                  32, PropModeReplace,
                  reinterpret_cast<unsigned char*>(&window_type), 1);
}

bool ShouldUseGlobalMenuBar() {
  scoped_ptr<base::Environment> env(base::Environment::Create());
  if (env->HasVar("ELECTRON_FORCE_WINDOW_MENU_BAR"))
    return false;

  dbus::Bus::Options options;
  scoped_refptr<dbus::Bus> bus(new dbus::Bus(options));

  dbus::ObjectProxy* object_proxy =
      bus->GetObjectProxy(DBUS_SERVICE_DBUS, dbus::ObjectPath(DBUS_PATH_DBUS));
  dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, "ListNames");
  scoped_ptr<dbus::Response> response(object_proxy->CallMethodAndBlock(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
  if (!response) {
    bus->ShutdownAndBlock();
    return false;
  }

  dbus::MessageReader reader(response.get());
  dbus::MessageReader array_reader(NULL);
  if (!reader.PopArray(&array_reader)) {
    bus->ShutdownAndBlock();
    return false;
  }
  while (array_reader.HasMoreData()) {
    std::string name;
    if (array_reader.PopString(&name) &&
        name == "com.canonical.AppMenu.Registrar") {
      bus->ShutdownAndBlock();
      return true;
    }
  }

  bus->ShutdownAndBlock();
  return false;
}

}  // namespace atom


text:
namespace OpenInEmacs
{
    static class Vsix
    {
        public const string Id = "CF1D7CEE-7F85-44E5-A4E3-9213877B8EBF";
        public const string Name = "Open in Emacs";
        public const string Description = @"Open multiple files simultaneously in Emacs directly from Solution Explorer or Code Editor window.";
        public const string Language = "en-US";
        public const string Version = "1.1.51";
        public const string Author = "GregTrevellick";
        public const string Tags = "open, open in, emacs";
    }
}


text:
                Post

            <form class="form-horizontal" role="form" data-ng-controller="PostFormController">

                        Region

                            <select data-ng-model="region" ng-options="r.name for r in regions" class="form-control">
                            </select>

                        Area Name

                            <input type="text" class="form-control" placeholder="Area Name" data-ng-model="areaName" />

                        Crime Statistics

                            <button type="button" class="btn btn-success btn-block" data-ng-click="addStatistic()">Add</button>

                                Crime Type

                                    <select data-ng-model="crimeStatistic.type" ng-options="t.name for t in crimeTypes" class="form-control">
                                    </select>

                                Crime Number

                                    <input type="text" class="form-control" placeholder="Crime Number" data-ng-model="crimeStatistic.number" />

                            <button type="button" class="btn btn-danger" data-ng-click="removeStatistic(crimeStatistic)">Remove</button>

                        <button type="button" class="btn btn-primary btn-block" data-ng-click="post()">Post</button>

Request URI

{{requestUri}}

Response

{{json}}

            </form>


text:
//Problem 8. Maximal sum
//
//Write a program that finds the sequence of maximal sum in given array.
using System;
class Program
    {
    static void Main()
    {
        Console.Write("Enter array size: ");
        int n = int.Parse(Console.ReadLine());
        int[] array = new int[n];
        Console.WriteLine("Enter array elements:");
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write("Element {0}: ", i);
            array[i] = int.Parse(Console.ReadLine());
        }
        int sum = 0;
        int maxSum = int.MinValue;
        string sequence = "";
        string sequenceWithMaxSum = "";

        for (int i = 0; i < array.Length; i++)
        {
            sum += array[i];
            sequence = sequence + " " + array[i];
            if (sum > maxSum)
            {
                maxSum = sum;
                sequenceWithMaxSum = sequence;
            }
            if (sum < 0)
            {
                sum = 0;
                sequence = "";
            }
        }
        Console.WriteLine("The sequence of maximal sum is {{{0} }} with sum = {1}", sequenceWithMaxSum, maxSum);
    }
    }


text:
<?php

namespace app\models;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "users".
 *
 * @property integer $id
 * @property integer $org
 * @property string $name
 * @property string $nik
 * @property string $pas
 * @property integer $count
 * @property string $data_reg
 * @property string $icon
 * @property string $email
 * @property string $ip_addr
 * @property integer $theme
 * @property string $last_log
 * @property integer $active
 * @property integer $field_set
 * @property integer $config
 * @property string $type
 * @property string $addon
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['org', 'name', 'username', 'data_reg', 'ip_addr', 'last_log', 'addon'], 'required'],
            [['org', 'count', 'theme', 'active', 'field_set', 'config'], 'integer'],
            [['data_reg', 'last_log'], 'safe'],
            [['type'], 'string'],
            [['name'], 'string', 'max' => 75],
            [['username'], 'string', 'max' => 30],
            [['password'], 'string', 'max' => 32],
            [['icon'], 'string', 'max' => 20],
            [['email'], 'string', 'max' => 35],
            [['ip_addr'], 'string', 'max' => 15],
            [['addon'], 'string', 'max' => 36],
            [['auth_key'], 'string', 'max' => 32],
            [['access_token'], 'string', 'max' => 32],
            [['username'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'org' => 'Org',
            'name' => 'Name',
            'username' => 'Username',
            'password' => 'Password',
            'count' => 'Count',
            'data_reg' => 'Data Reg',
            'icon' => 'Icon',
            'email' => 'Email',
            'ip_addr' => 'Ip Addr',
            'theme' => 'Theme',
            'last_log' => 'Last Log',
            'active' => 'Active',
            'field_set' => 'Field Set',
            'config' => 'Config',
            'type' => 'Type',
            'addon' => 'Addon',
            'auth_key' => 'Authentication key',
            'access_token' => 'Access Token'
        ];
    }

    /**
     * Finds an identity by the given ID.
     *
     * @param string|integer $id the ID to be looked for
     * @return IdentityInterface|null the identity object that matches the given ID.
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * Finds an identity by the given token.
     *
     * @param string $token the token to be looked for
     * @return IdentityInterface|null the identity object that matches the given token.
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    /**
     * @return int|string current user ID
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string current user auth key
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @param string $authKey
     * @return boolean if auth key is valid for current user
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public function findByUsername($username)
    {
        $user = new User();
        return $user->findOne(['username' => $username]);
    }

    public function validatePassword($password)
    {
        return $this->password === $password;
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $hash = Yii::$app->getSecurity()->generatePasswordHash($this->password);
                $this->pas = $hash;
            }
            return true;
        }
        return false;
    }
}


text:
using System;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Base;
using OGDC.Silverlight.Toolkit.ViewModels;
using System.ComponentModel.DataAnnotations;

namespace EspaceClient.BackOffice.Silverlight.ViewModels.DtoViewModels
{
    public partial class CertificatDtoViewModel : ViewModelBaseEx
    {
		private long _id;
        [TrackProperty]
        public long ID
        {
            get
            {
                return _id;
            }

            set
            {
                if (_id != value)
                {
                    _id = value;
                    NotifyPropertyChanged(() => ID);
                }
                NotifyCheckErrorEvent(() => ID);
            }
        }
		private long _certificationid;
        [TrackProperty]
        public long CertificationID
        {
            get
            {
                return _certificationid;
            }

            set
            {
                if (_certificationid != value)
                {
                    _certificationid = value;
                    NotifyPropertyChanged(() => CertificationID);
                }
                NotifyCheckErrorEvent(() => CertificationID);
            }
        }
		private Nullable<long> _organismecertificationid;
        [TrackProperty]
        public Nullable<long> OrganismeCertificationID
        {
            get
            {
                return _organismecertificationid;
            }

            set
            {
                if (_organismecertificationid != value)
                {
                    _organismecertificationid = value;
                    NotifyPropertyChanged(() => OrganismeCertificationID);
                }
                NotifyCheckErrorEvent(() => OrganismeCertificationID);
            }
        }
		private Nullable<long> _perimetrecertificationid;
        [TrackProperty]
        public Nullable<long> PerimetreCertificationID
        {
            get
            {
                return _perimetrecertificationid;
            }

            set
            {
                if (_perimetrecertificationid != value)
                {
                    _perimetrecertificationid = value;
                    NotifyPropertyChanged(() => PerimetreCertificationID);
                }
                NotifyCheckErrorEvent(() => PerimetreCertificationID);
            }
        }
		private Nullable<DateTime> _datedebutvalidite;
        [TrackProperty]
        public Nullable<DateTime> DateDebutValidite
        {
            get
            {
                return _datedebutvalidite;
            }

            set
            {
                if (_datedebutvalidite != value)
                {
                    _datedebutvalidite = value;
                    NotifyPropertyChanged(() => DateDebutValidite);
                }
                NotifyCheckErrorEvent(() => DateDebutValidite);
            }
        }
		private Nullable<DateTime> _datefinvalidite;
        [TrackProperty]
        public Nullable<DateTime> DateFinValidite
        {
            get
            {
                return _datefinvalidite;
            }

            set
            {
                if (_datefinvalidite != value)
                {
                    _datefinvalidite = value;
                    NotifyPropertyChanged(() => DateFinValidite);
                }
                NotifyCheckErrorEvent(() => DateFinValidite);
            }
        }
		private string _numerocertificat;
							[StringLength(200)]
        [TrackProperty]
        public string NumeroCertificat
        {
            get
            {
                return _numerocertificat;
            }

            set
            {
                if (_numerocertificat != value)
                {
                    _numerocertificat = value;
                    NotifyPropertyChanged(() => NumeroCertificat);
                }
                NotifyCheckErrorEvent(() => NumeroCertificat);
            }
        }
		private Nullable<int> _suffixecertificat;
        [TrackProperty]
        public Nullable<int> SuffixeCertificat
        {
            get
            {
                return _suffixecertificat;
            }

            set
            {
                if (_suffixecertificat != value)
                {
                    _suffixecertificat = value;
                    NotifyPropertyChanged(() => SuffixeCertificat);
                }
                NotifyCheckErrorEvent(() => SuffixeCertificat);
            }
        }
		private string _lienweb;
							[StringLength(500)]
        [TrackProperty]
        public string LienWeb
        {
            get
            {
                return _lienweb;
            }

            set
            {
                if (_lienweb != value)
                {
                    _lienweb = value;
                    NotifyPropertyChanged(() => LienWeb);
                }
                NotifyCheckErrorEvent(() => LienWeb);
            }
        }
		private Nullable<long> _versionreferentielid;
        [TrackProperty]
        public Nullable<long> VersionReferentielID
        {
            get
            {
                return _versionreferentielid;
            }

            set
            {
                if (_versionreferentielid != value)
                {
                    _versionreferentielid = value;
                    NotifyPropertyChanged(() => VersionReferentielID);
                }
                NotifyCheckErrorEvent(() => VersionReferentielID);
            }
        }
		private Nullable<DateTime> _datesignaturesace;
        [TrackProperty]
        public Nullable<DateTime> DateSignatureSACE
        {
            get
            {
                return _datesignaturesace;
            }

            set
            {
                if (_datesignaturesace != value)
                {
                    _datesignaturesace = value;
                    NotifyPropertyChanged(() => DateSignatureSACE);
                }
                NotifyCheckErrorEvent(() => DateSignatureSACE);
            }
        }
		private bool _estrenouvelle;
        [TrackProperty]
        public bool EstRenouvelle
        {
            get
            {
                return _estrenouvelle;
            }

            set
            {
                if (_estrenouvelle != value)
                {
                    _estrenouvelle = value;
                    NotifyPropertyChanged(() => EstRenouvelle);
                }
                NotifyCheckErrorEvent(() => EstRenouvelle);
            }
        }
		private string _urlreportbuilder;
							[StringLength(1000)]
        [TrackProperty]
        public string UrlReportBuilder
        {
            get
            {
                return _urlreportbuilder;
            }

            set
            {
                if (_urlreportbuilder != value)
                {
                    _urlreportbuilder = value;
                    NotifyPropertyChanged(() => UrlReportBuilder);
                }
                NotifyCheckErrorEvent(() => UrlReportBuilder);
            }
        }
		   }
		}


text:
local TableUtils = require('utils.class')
local Character  = require('core.character')

-- Define prey character.
local Prey = TableUtils.class(Character)

-- Prey implementation of function g(d).
local gx = function (ratio) return (1 - ratio)^2 end

-- Prey implementation of function h(d).
local hx = function (ratio) return ratio^0.5 end

-- Set prey collision avoidance profile.
Prey.params_gx = TableUtils.default(gx)
Prey.params_hx = TableUtils.default(hx)

return Prey


text:
id: unit-api
title: Unit API
---

You can call `getUnit()` on a space to retrieve the unit located there (but keep
in mind that not all spaces have units on them):

```js
const unit = space.getUnit();
```

You can call methods on a unit to know more about it.

## Class Methods

Here are the various methods that are available to you:

### `unit.isBound()`

Determines if the unit is bound.

**Returns**

_(boolean)_: Whether this unit is bound or not.

### `unit.isEnemy()`:

Determines if the unit is an enemy.

**Returns**

_(boolean)_: Whether this is an enemy unit or not.


text:
package com.vladmihalcea.book.hpjp.hibernate.association;

import com.vladmihalcea.book.hpjp.util.AbstractTest;
import com.vladmihalcea.book.hpjp.util.providers.Database;
import org.junit.Test;

import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Vlad Mihalcea
 */
public class ElementCollectionListTest extends AbstractTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
            Post.class
        };
    }

    @Override
    protected Database database() {
        return Database.POSTGRESQL;
    }

    @Override
    protected void afterInit() {
        doInJPA(entityManager -> {
            entityManager.persist(
                new Post()
                    .setId(1L)
                    .setTitle("High-Performance Java Persistence")
                    .addComment("Best book on JPA and Hibernate!")
                    .addComment("A must-read for every Java developer!")
                    .addComment("A great reference book")
            );
        });
    }

    @Test
    public void testRemoveTail() {

        doInJPA(entityManager -> {
            Post post = entityManager.find(Post.class, 1L);

            List<String> comments = post.getComments();
            comments.remove(comments.size() - 1);
        });
    }

    @Test
    public void testFetchAndRemoveTail() {

        doInJPA(entityManager -> {
            Post post = entityManager.createQuery("""
                select p
                from Post p
                join fetch p.comments
                where p.id = :id
                """, Post.class)
                .setParameter("id", 1L)
                .getSingleResult();

            post.getComments().remove(post.getComments().size() - 1);
        });
    }

    @Test
    public void testFetchAndRemoveHead() {

        doInJPA(entityManager -> {
            Post post = entityManager.createQuery("""
                select p
                from Post p
                join fetch p.comments
                where p.id = :id
                """, Post.class)
                .setParameter("id", 1L)
                .getSingleResult();

            post.getComments().remove(0);
        });
    }

    @Entity(name = "Post")
    @Table(name = "post")
    public static class Post {

        @Id
        private Long id;

        private String title;

        @ElementCollection
        @JoinTable(name = "post_comments")
        private List<String> comments = new ArrayList<>();

        public Long getId() {
            return id;
        }

        public Post setId(Long id) {
            this.id = id;
            return this;
        }

        public String getTitle() {
            return title;
        }

        public Post setTitle(String title) {
            this.title = title;
            return this;
        }

        public List<String> getComments() {
            return comments;
        }

        public Post addComment(String comment) {
            comments.add(comment);
            return this;
        }
    }
}


text:
namespace base {
class SingleThreadTaskRunner;
}

namespace net {
class URLRequestContextGetter;
}

namespace precache {

class PrecacheConfigurationSettings;
class PrecacheUnfinishedWork;

// Visible for testing.
extern const int kNoTracking;

// Public interface to code that fetches resources that the user is likely to
// want to fetch in the future, putting them in the network stack disk cache.
// Precaching is intended to be done when Chrome is not actively in use, likely
// hours ahead of the time when the resources are actually needed.
//
// This class takes as input a prioritized list of URL domains that the user
// commonly visits, referred to as starting hosts. This class interacts with a
// server, sending it the list of starting hosts sequentially. For each starting
// host, the server returns a manifest of resource URLs that are good candidates
// for precaching. Every resource returned is fetched, and responses are cached
// as they are received. Destroying the PrecacheFetcher while it is precaching
// will cancel any fetch in progress and cancel precaching.
//
// The URLs of the server-side component must be specified in order for the
// PrecacheFetcher to work. This includes the URL that the precache
// configuration settings are fetched from and the prefix of URLs where precache
// manifests are fetched from. These can be set by using command line switches
// or by providing default values.
//
// Sample interaction:
//
// class MyPrecacheFetcherDelegate : public PrecacheFetcher::PrecacheDelegate {
//  public:
//   void PrecacheResourcesForTopURLs(
//       net::URLRequestContextGetter* request_context,
//       const std::list<GURL>& top_urls) {
//     fetcher_.reset(new PrecacheFetcher(...));
//     fetcher_->Start();
//   }
//
//   void Cancel() {
//     std::unique_ptr<PrecacheUnfinishedWork> unfinished_work =
//         fetcher_->CancelPrecaching();
//     fetcher_.reset();
//   }
//
//   virtual void OnDone() {
//     // Do something when precaching is done.
//   }
//
//  private:
//   std::unique_ptr<PrecacheFetcher> fetcher_;
// };
class PrecacheFetcher : public base::SupportsWeakPtr<PrecacheFetcher> {
 public:
  class PrecacheDelegate {
   public:
    // Called when the fetching of resources has finished, whether the resources
    // were fetched or not. If the PrecacheFetcher is destroyed before OnDone is
    // called, then precaching will be canceled and OnDone will not be called.
    virtual void OnDone() = 0;

  };

  // Visible for testing.
  class Fetcher;

  static void RecordCompletionStatistics(
      const PrecacheUnfinishedWork& unfinished_work,
      size_t remaining_manifest_urls_to_fetch,
      size_t remaining_resource_urls_to_fetch);

  // Constructs a new PrecacheFetcher. The |starting_hosts| parameter is a
  // prioritized list of hosts that the user commonly visits. These hosts are
  // used by a server side component to construct a list of resource URLs that
  // the user is likely to fetch. Takes ownership of |unfinished_work|.
  PrecacheFetcher(net::URLRequestContextGetter* request_context,
                  const GURL& config_url,
                  const std::string& manifest_url_prefix,
                  std::unique_ptr<PrecacheUnfinishedWork> unfinished_work,
                  uint32_t experiment_id,
                  PrecacheDelegate* precache_delegate);

  virtual ~PrecacheFetcher();

  // Starts fetching resources to precache. URLs are fetched sequentially. Can
  // be called from any thread. Start should only be called once on a
  // PrecacheFetcher instance.
  void Start();

  // Stops all precaching work. The PreacheFetcher should not be used after
  // calling this method.
  std::unique_ptr<PrecacheUnfinishedWork> CancelPrecaching();

 private:
  friend class PrecacheFetcherTest;
  FRIEND_TEST_ALL_PREFIXES(PrecacheFetcherTest, FetcherPoolMaxLimitReached);

  // Notifies the precache delete that precaching is done, and report
  // completion statistics.
  void NotifyDone(size_t remaining_manifest_urls_to_fetch,
                  size_t remaining_resource_urls_to_fetch);

  // Fetches the next resource or manifest URL, if any remain. Fetching is done
  // sequentially and depth-first: all resources are fetched for a manifest
  // before the next manifest is fetched. This is done to limit the length of
  // the |resource_urls_to_fetch_| list, reducing the memory usage.
  void StartNextFetch();

  void StartNextManifestFetch();
  void StartNextResourceFetch();

  // Called when the precache configuration settings have been fetched.
  // Determines the list of manifest URLs to fetch according to the list of
  // |starting_hosts_| and information from the precache configuration settings.
  // If the fetch of the configuration settings fails, then precaching ends.
  void OnConfigFetchComplete(const Fetcher& source);

  // Constructs manifest URLs using a manifest URL prefix, and lists of hosts.
  void DetermineManifests();

  // Called when a precache manifest has been fetched. Builds the list of
  // resource URLs to fetch according to the URLs in the manifest. If the fetch
  // of a manifest fails, then it skips to the next manifest.
  void OnManifestFetchComplete(const Fetcher& source);

  // Called when a resource has been fetched.
  void OnResourceFetchComplete(const Fetcher& source);

  // Adds up the response sizes.
  void UpdateStats(int64_t response_bytes, int64_t network_response_bytes);

  // The request context used when fetching URLs.
  const scoped_refptr<net::URLRequestContextGetter> request_context_;

  // The custom URL to use when fetching the config. If not provided, the
  // default flag-specified URL will be used.
  const GURL config_url_;

  // The custom URL prefix to use when fetching manifests. If not provided, the
  // default flag-specified prefix will be used.
  const std::string manifest_url_prefix_;

  // Non-owning pointer. Should not be NULL.
  PrecacheDelegate* precache_delegate_;

  std::list<GURL> manifest_urls_to_fetch_;
  std::list<GURL> resource_urls_to_fetch_;

  FetcherPool<Fetcher> pool_;

  std::unique_ptr<PrecacheUnfinishedWork> unfinished_work_;

  // The fieldtrial experiment ID.
  uint32_t experiment_id_;

  DISALLOW_COPY_AND_ASSIGN(PrecacheFetcher);
};

// Class that fetches a URL, and runs the specified callback when the fetch is
// complete. This class exists so that a different method can be run in
// response to different kinds of fetches, e.g. OnConfigFetchComplete when
// configuration settings are fetched, OnManifestFetchComplete when a manifest
// is fetched, etc.
//
// This class tries to increase freshness while limiting network usage, by using
// the following strategy:
// 1.  Fetch the URL from the cache.
// 2a. If it's present and lacks revalidation headers, then stop.
// 2b. If it's not present, or it's present and has revalidation headers, then
//     refetch over the network.
//
// This allows the precache to "refresh" cache entries by increasing their
// expiration date, but minimizes the network impact of doing so, by performing
// only conditional GETs.
//
// On completion it calls the given callback. This class cancels requests whose
// responses are or will be larger than max_bytes. In such cases,
// network_url_fetcher() will return nullptr.
class PrecacheFetcher::Fetcher : public net::URLFetcherDelegate {
 public:
  // Construct a new Fetcher. This will create and start a new URLFetcher for
  // the specified URL using the specified request context.
  Fetcher(net::URLRequestContextGetter* request_context,
          const GURL& url,
          const base::Callback<void(const Fetcher&)>& callback,
          bool is_resource_request,
          size_t max_bytes);
  ~Fetcher() override;
  void OnURLFetchDownloadProgress(const net::URLFetcher* source,
                                  int64_t current,
                                  int64_t total) override;
  void OnURLFetchComplete(const net::URLFetcher* source) override;
  int64_t response_bytes() const { return response_bytes_; }
  int64_t network_response_bytes() const { return network_response_bytes_; }
  const net::URLFetcher* network_url_fetcher() const {
    return network_url_fetcher_.get();
  }
  const GURL& url() const { return url_; }
  bool is_resource_request() const { return is_resource_request_; }

 private:
  enum class FetchStage { CACHE, NETWORK };

  void LoadFromCache();
  void LoadFromNetwork();

  net::URLRequestContextGetter* const request_context_;
  const GURL url_;
  const base::Callback<void(const Fetcher&)> callback_;
  const bool is_resource_request_;
  const size_t max_bytes_;

  FetchStage fetch_stage_;
  // The cache_url_fetcher_ is kept alive until Fetcher destruction for testing.
  std::unique_ptr<net::URLFetcher> cache_url_fetcher_;
  std::unique_ptr<net::URLFetcher> network_url_fetcher_;
  int64_t response_bytes_;
  int64_t network_response_bytes_;

  DISALLOW_COPY_AND_ASSIGN(Fetcher);
};

}  // namespace precache

#endif  // COMPONENTS_PRECACHE_CORE_PRECACHE_FETCHER_H_


text:
module Statification
  VERSION = "0.0.1"
end


text:
from .aws import Action as BaseAction
from .aws import BaseARN

service_name = "Amazon Managed Blockchain"
prefix = "managedblockchain"

class Action(BaseAction):
    def __init__(self, action: str = None) -> None:
        super().__init__(prefix, action)

class ARN(BaseARN):
    def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
        super().__init__(
            service=prefix, resource=resource, region=region, account=account
        )

CreateMember = Action("CreateMember")
CreateNetwork = Action("CreateNetwork")
CreateNode = Action("CreateNode")
CreateProposal = Action("CreateProposal")
DeleteMember = Action("DeleteMember")
DeleteNode = Action("DeleteNode")
GetMember = Action("GetMember")
GetNetwork = Action("GetNetwork")
GetNode = Action("GetNode")
GetProposal = Action("GetProposal")
ListInvitations = Action("ListInvitations")
ListMembers = Action("ListMembers")
ListNetworks = Action("ListNetworks")
ListNodes = Action("ListNodes")
ListProposalVotes = Action("ListProposalVotes")
ListProposals = Action("ListProposals")
ListTagsForResource = Action("ListTagsForResource")
RejectInvitation = Action("RejectInvitation")
TagResource = Action("TagResource")
UntagResource = Action("UntagResource")
UpdateMember = Action("UpdateMember")
UpdateNode = Action("UpdateNode")
VoteOnProposal = Action("VoteOnProposal")


text:
package descriptor

import (
	"github.com/golang/protobuf/proto"
	"github.com/ligato/cn-infra/logging"
	"github.com/pkg/errors"

	interfaces "go.ligato.io/vpp-agent/v3/examples/kvscheduler/mock_plugins/ifplugin/model"
	"go.ligato.io/vpp-agent/v3/examples/kvscheduler/mock_plugins/l2plugin/descriptor/adapter"
	"go.ligato.io/vpp-agent/v3/examples/kvscheduler/mock_plugins/l2plugin/mockcalls"
	l2 "go.ligato.io/vpp-agent/v3/examples/kvscheduler/mock_plugins/l2plugin/model"
	"go.ligato.io/vpp-agent/v3/pkg/idxvpp"
	kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
)

const (
	// BDInterfaceDescriptorName is the name of the descriptor for bindings
	// between mock bridge domains and mock interfaces.
	BDInterfaceDescriptorName = "mock-bd-interface"

	// dependency labels
	interfaceDep = "interface-exists"
)

// BDInterfaceDescriptor teaches KVScheduler how to put interface into bridge
// domain in the mock SB.
// A binding between bridge domain and an interface is a value derived from the
// bridge domain. This descriptor is therefore only for derived values.
type BDInterfaceDescriptor struct {
	// dependencies
	log       logging.Logger
	bdIndex   idxvpp.NameToIndex
	bdHandler mockcalls.MockBDAPI
}

// NewBDInterfaceDescriptor creates a new instance of the BDInterface descriptor.
func NewBDInterfaceDescriptor(bdIndex idxvpp.NameToIndex, bdHandler mockcalls.MockBDAPI, log logging.PluginLogger) *kvs.KVDescriptor {
	// descriptors are supposed to be stateless and this principle is not broken
	// here - we only need to keep context consisting of references to logger,
	// index with BD metadata and the BD handler, to be used inside the CRUD
	// methods
	descrCtx := &BDInterfaceDescriptor{
		bdIndex:   bdIndex,
		bdHandler: bdHandler,
		log:       log.NewLogger("mock-bd-iface-descriptor"),
	}

	// use adapter to convert typed descriptor into generic descriptor API
	typedDescr := &adapter.BDInterfaceDescriptor{
		Name:          BDInterfaceDescriptorName,
		KeySelector:   descrCtx.IsBDInterfaceKey,
		ValueTypeName: proto.MessageName(&l2.BridgeDomain_Interface{}),
		Create:        descrCtx.Create,
		Delete:        descrCtx.Delete,
		Dependencies:  descrCtx.Dependencies,

		// Note: this descriptor is only for derived values, therefore it doesn't
		//       need to define the Retrieve method - the values under its scope
		//       are derived from bridge domains, which are already Retrieved by
		//       BridgeDomainDescriptor.
	}
	return adapter.NewBDInterfaceDescriptor(typedDescr)
}

// IsBDInterfaceKey returns true if the key is identifying binding between
// bridge domain and interface in the mock SB.
func (d *BDInterfaceDescriptor) IsBDInterfaceKey(key string) bool {
	_, _, isBDIfaceKey := l2.ParseBDInterfaceKey(key)
	return isBDIfaceKey
}

// Create puts interface into bridge domain.
func (d *BDInterfaceDescriptor) Create(key string, bdIface *l2.BridgeDomain_Interface) (metadata interface{}, err error) {
	// get bridge domain index
	bdName, _, _ := l2.ParseBDInterfaceKey(key)
	bdMeta, found := d.bdIndex.LookupByName(bdName)
	if !found {
		err = errors.Errorf("failed to obtain metadata for bridge domain %s", bdName)
		d.log.Error(err)
		return nil, err
	}

	// put interface into the bridge domain
	err = d.bdHandler.AddInterfaceToBridgeDomain(bdMeta.GetIndex(), bdIface.Name, bdIface.BridgedVirtualInterface)
	if err != nil {
		d.log.Error(err)
		return nil, err

	}
	return nil, nil
}

// Delete removes interface from bridge domain.
func (d *BDInterfaceDescriptor) Delete(key string, bdIface *l2.BridgeDomain_Interface, metadata interface{}) error {
	// get bridge domain index
	bdName, _, _ := l2.ParseBDInterfaceKey(key)
	bdMeta, found := d.bdIndex.LookupByName(bdName)
	if !found {
		err := errors.Errorf("failed to obtain metadata for bridge domain %s", bdName)
		d.log.Error(err)
		return err
	}

	err := d.bdHandler.DeleteInterfaceFromBridgeDomain(bdMeta.GetIndex(), bdIface.Name)
	if err != nil {
		d.log.Error(err)
		return err

	}
	return nil
}

// Dependencies lists the interface as the only dependency for the binding.
//
// Note: some bindings derived from a given bridge domain may be pending (waiting
// for their interfaces), but others and the bridge domain itself will be unaffected
// and free to get configured. This is the power of derived values, which allows
// you to break complex items into multiple parts handled separately.
func (d *BDInterfaceDescriptor) Dependencies(key string, value *l2.BridgeDomain_Interface) []kvs.Dependency {
	return []kvs.Dependency{
		{
			Label: interfaceDep,
			Key:   interfaces.InterfaceKey(value.Name),
		},
	}
}


text:
using System;

class Factoriel2
{
	static void Main()
	{
		int numberN = GetNumber(1);
		int numberK = GetNumber(numberN);
		decimal multiplier1 = 1;
		decimal multiplier2 = 1;
		decimal devider = 1;
		for (int i = 2; i <= numberN; i++)
		{
			multiplier1 *= i;
		}
		for (int j = 2; j <= numberK; j++)
		{
			multiplier2 *= j;
		}
		for (int k = 2; k <= (numberK - numberN); k++)
		{
			devider *= k;
		}
		decimal theResult = multiplier1 * multiplier2 / devider;
		Console.WriteLine("The result is {0}", theResult);
	}

	static int GetNumber(int min)
	{
		int number;
		do
		{
			Console.WriteLine("Please enter a valid integer number greater than {0}.", min);
		}
		while (!int.TryParse(Console.ReadLine(), out number) || number <= min);
		return number;
	}
}


text:
package com.opengamma.financial.analytics.ircurve;

import java.util.Set;

import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.financial.property.StaticDefaultPropertyFunction;

/**
 * Function to inject default yield curve shifts into the dependency graph. Shifts are taken from the default properties in the following order:
 *

 *
curve name_currency_YIELD_CURVE_SHIFT
 *
curve_name_YIELD_CURVE_SHIFT
 *
currency_YIELD_CURVE_SHIFT
 *
YIELD_CURVE_SHIFT
 *

 * This should allow either specific curves to be adjusted or more global changes.
 *
 * @deprecated {@link YieldCurveDefinition}s are deprecated.
 */
@Deprecated
public class DefaultYieldCurveShiftFunction extends StaticDefaultPropertyFunction {

  /**
   * Property to shift all yield curves.
   */
  protected static final String YIELD_CURVE_SHIFT = "YIELD_CURVE_" + YieldCurveShiftFunction.SHIFT;

  public DefaultYieldCurveShiftFunction() {
    super(ComputationTargetType.CURRENCY, YieldCurveShiftFunction.SHIFT, false, ValueRequirementNames.YIELD_CURVE);
  }

  @Override
  protected Set<String> getDefaultValue(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
    final String currency = target.getUniqueId().getValue();
    final ValueProperties defaults = context.getViewCalculationConfiguration().getDefaultProperties();
    final String name = desiredValue.getConstraints().getStrictValue(ValuePropertyNames.CURVE);
    Set<String> values;
    if (name != null) {
      values = defaults.getValues(name + "_" + currency + "_" + YIELD_CURVE_SHIFT);
      if (values != null) {
        return values;
      }
      values = defaults.getValues(name + "_" + YIELD_CURVE_SHIFT);
      if (values != null) {
        return values;
      }
    }
    values = defaults.getValues(currency + "_" + YIELD_CURVE_SHIFT);
    if (values != null) {
      return values;
    }
    return defaults.getValues(YIELD_CURVE_SHIFT);
  }

}


text:
package handshake

import (
	"bytes"

	"github.com/lucas-clemente/quic-go/qerr"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Handshake Message", func() {
	Context("when parsing", func() {
		It("parses sample CHLO message", func() {
			tag, msg, err := ParseHandshakeMessage(bytes.NewReader(sampleCHLO))
			Expect(err).ToNot(HaveOccurred())
			Expect(tag).To(Equal(TagCHLO))
			Expect(msg).To(Equal(sampleCHLOMap))
		})

		It("rejects large numbers of pairs", func() {
			r := bytes.NewReader([]byte("CHLO\xff\xff\xff\xff"))
			_, _, err := ParseHandshakeMessage(r)
			Expect(err).To(MatchError(qerr.CryptoTooManyEntries))
		})

		It("rejects too long values", func() {
			r := bytes.NewReader([]byte{
				'C', 'H', 'L', 'O',
				1, 0, 0, 0,
				0, 0, 0, 0,
				0xff, 0xff, 0xff, 0xff,
			})
			_, _, err := ParseHandshakeMessage(r)
			Expect(err).To(MatchError(qerr.Error(qerr.CryptoInvalidValueLength, "value too long")))
		})
	})

	Context("when writing", func() {
		It("writes sample message", func() {
			b := &bytes.Buffer{}
			WriteHandshakeMessage(b, TagCHLO, sampleCHLOMap)
			Expect(b.Bytes()).To(Equal(sampleCHLO))
		})
	})
})


text:
<?xml version="1.0" ?>
<install version="1.5" type="extension" extension="jceplayer" folder="mediaplayer" core="1">
	<name>WF_MEDIAPLAYER_JCEPLAYER_TITLE</name>
	<version>2.3.3.2</version>
	<creationDate>13 July 2013</creationDate>
	<author>Ryan Demmer</author>
	<authorEmail>info@joomlacontenteditor.net</authorEmail>
	<authorUrl>http://www.joomlacontenteditor.net/</authorUrl>
	<copyright>Copyright (C) 2006 - 2013 Ryan Demmer. All rights reserved</copyright>
	<license>GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html</license>
	<description>WF_MEDIAPLAYER_JCEPLAYER_DESC</description>
	<files>
		<filename>jceplayer.php</filename>
		<folder>jceplayer</folder>
	</files>
	<params group="jceplayer" parent="mediaplayer">
		<param name="extensions" type="text" default="flv,f4v,mp3,mp4,xml" size="50" label="WF_MEDIAPLAYER_EXTENSIONS" description="WF_MEDIAPLAYER_EXTENSIONS_DESC" />
		<param name="path" type="text" size="50" default="media/jce/mediaplayer/mediaplayer.swf" label="WF_MEDIAPLAYER_PATH" description="WF_MEDIAPLAYER_PATH_DESC" />
	</params>
	<media folder="components/com_jce/editor/libraries" destination="jce">
    	<folder>mediaplayer</folder>
  	</media>
	<plugins></plugins>
	<languages></languages>
</install>


text:
/*
 * vim:ts=4:sw=4:expandtab
 *
 * i3 - an improved dynamic tiling window manager
 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
 *
 * i3-dump-log/main.c: Dumps the i3 SHM log to stdout.
 *
 */
#include <stdio.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <err.h>
#include <stdint.h>
#include <getopt.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>

#include "libi3.h"
#include "shmlog.h"
#include <i3/ipc.h>

static uint32_t offset_next_write,
    wrap_count;

static i3_shmlog_header *header;
static char *logbuffer,
    *walk;

static int check_for_wrap(void) {
    if (wrap_count == header->wrap_count)
        return 0;

    /* The log wrapped. Print the remaining content and reset walk to the top
     * of the log. */
    wrap_count = header->wrap_count;
    const int len = (logbuffer + header->offset_last_wrap) - walk;
    swrite(STDOUT_FILENO, walk, len);
    walk = logbuffer + sizeof(i3_shmlog_header);
    return 1;
}

static void print_till_end(void) {
    check_for_wrap();
    const int len = (logbuffer + header->offset_next_write) - walk;
    swrite(STDOUT_FILENO, walk, len);
    walk += len;
}

int main(int argc, char *argv[]) {
    int o, option_index = 0;
    bool verbose = false,
         follow = false;

    static struct option long_options[] = {
        {"version", no_argument, 0, 'v'},
        {"verbose", no_argument, 0, 'V'},
        {"follow", no_argument, 0, 'f'},
        {"help", no_argument, 0, 'h'},
        {0, 0, 0, 0}};

    char *options_string = "s:vfVh";

    while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
        if (o == 'v') {
            printf("i3-dump-log " I3_VERSION "\n");
            return 0;
        } else if (o == 'V') {
            verbose = true;
        } else if (o == 'f') {
            follow = true;
        } else if (o == 'h') {
            printf("i3-dump-log " I3_VERSION "\n");
            printf("i3-dump-log [-f] [-s <socket>]\n");
            return 0;
        }
    }

    char *shmname = root_atom_contents("I3_SHMLOG_PATH", NULL, 0);
    if (shmname == NULL) {
        /* Something failed. Let's invest a little effort to find out what it
         * is. This is hugely helpful for users who want to debug i3 but are
         * not used to the procedure yet. */
        xcb_connection_t *conn;
        int screen;
        if ((conn = xcb_connect(NULL, &screen)) == NULL ||
            xcb_connection_has_error(conn)) {
            fprintf(stderr, "i3-dump-log: ERROR: Cannot connect to X11.\n\n");
            if (getenv("DISPLAY") == NULL) {
                fprintf(stderr, "Your DISPLAY environment variable is not set.\n");
                fprintf(stderr, "Are you running i3-dump-log via SSH or on a virtual console?\n");
                fprintf(stderr, "Try DISPLAY=:0 i3-dump-log\n");
                exit(1);
            }
            fprintf(stderr, "FYI: The DISPLAY environment variable is set to \"%s\".\n", getenv("DISPLAY"));
            exit(1);
        }
        if (root_atom_contents("I3_CONFIG_PATH", conn, screen) != NULL) {
            fprintf(stderr, "i3-dump-log: ERROR: i3 is running, but SHM logging is not enabled.\n\n");
            if (!is_debug_build()) {
                fprintf(stderr, "You seem to be using a release version of i3:\n  %s\n\n", I3_VERSION);
                fprintf(stderr, "Release versions do not use SHM logging by default,\ntherefore i3-dump-log does not work.\n\n");
                fprintf(stderr, "Please follow this guide instead:\nhttp://i3wm.org/docs/debugging-release-version.html\n");
                exit(1);
            }
        }
        errx(EXIT_FAILURE, "Cannot get I3_SHMLOG_PATH atom contents. Is i3 running on this display?");
    }

    if (*shmname == '\0')
        errx(EXIT_FAILURE, "Cannot dump log: SHM logging is disabled in i3.");

    struct stat statbuf;

    /* NB: While we must never write, we need O_RDWR for the pthread condvar. */
    int logbuffer_shm = shm_open(shmname, O_RDWR, 0);
    if (logbuffer_shm == -1)
        err(EXIT_FAILURE, "Could not shm_open SHM segment for the i3 log (%s)", shmname);

    if (fstat(logbuffer_shm, &statbuf) != 0)
        err(EXIT_FAILURE, "stat(%s)", shmname);

    /* NB: While we must never write, we need PROT_WRITE for the pthread condvar. */
    logbuffer = mmap(NULL, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
    if (logbuffer == MAP_FAILED)
        err(EXIT_FAILURE, "Could not mmap SHM segment for the i3 log");

    header = (i3_shmlog_header *)logbuffer;

    if (verbose)
        printf("next_write = %d, last_wrap = %d, logbuffer_size = %d, shmname = %s\n",
               header->offset_next_write, header->offset_last_wrap, header->size, shmname);
    free(shmname);
    walk = logbuffer + header->offset_next_write;

    /* We first need to print old content in case there was at least one
     * wrapping already. */

    if (*walk != '\0') {
        /* In case there was a write to the buffer already, skip the first
         * old line, it very likely is mangled. Not a problem, though, the log
         * is chatty enough to have plenty lines left. */
        while (*walk != '\n')
            walk++;
        walk++;
    }

    /* In case there was no wrapping, this is a no-op, otherwise it prints the
     * old lines. */
    wrap_count = 0;
    check_for_wrap();

    /* Then start from the beginning and print the newer lines */
    walk = logbuffer + sizeof(i3_shmlog_header);
    print_till_end();

    if (follow) {
        /* Since pthread_cond_wait() expects a mutex, we need to provide one.
         * To not lock i3 (that's bad, mhkay?) we just define one outside of
         * the shared memory. */
        pthread_mutex_t dummy_mutex = PTHREAD_MUTEX_INITIALIZER;
        pthread_mutex_lock(&dummy_mutex);
        while (1) {
            pthread_cond_wait(&(header->condvar), &dummy_mutex);
            /* If this was not a spurious wakeup, print the new lines. */
            if (header->offset_next_write != offset_next_write) {
                offset_next_write = header->offset_next_write;
                print_till_end();
            }
        }
    }

    return 0;
}


text:
package org.commcare.suite.model;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.parser.XPathSyntaxException;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import io.reactivex.Single;

/**
 * A Menu definition describes the structure of how
 * actions should be provided to the user in a CommCare
 * application.
 *
 * @author ctsims
 */
public class Menu implements Externalizable, MenuDisplayable {
    public static final String ROOT_MENU_ID = "root";
    public static final String TRAINING_MENU_ROOT = "training-root";

    private DisplayUnit display;
    private Vector<String> commandIds;
    private String[] commandExprs;
    private String id;
    private String root;
    private String rawRelevance;
    private String style;
    private XPathExpression relevance;

    /**
     * Serialization only!!!
     */
    public Menu() {

    }

    public Menu(String id, String root, String rawRelevance,
                XPathExpression relevance, DisplayUnit display,
                Vector<String> commandIds, String[] commandExprs, String style) {
        this.id = id;
        this.root = root;
        this.rawRelevance = rawRelevance;
        this.relevance = relevance;
        this.display = display;
        this.commandIds = commandIds;
        this.commandExprs = commandExprs;
        this.style = style;
    }

    /**
     * @return The ID of what menu an option to navigate to
     * this menu should be displayed in.
     */
    public String getRoot() {
        return root;
    }

    /**
     * @return A Text which should be displayed to the user as
     * the action which will display this menu.
     */
    public Text getName() {
        return display.getText();
    }

    /**
     * @return The ID of this menu.
If this value is "root"
     * many CommCare applications will support displaying this
     * menu's options at the app home screen

     */
    public String getId() {
        return id;
    }

    /**
     * @return A parsed XPath expression that determines
     * whether or not to display this menu.
     */
    public XPathExpression getMenuRelevance() throws XPathSyntaxException {
        if (relevance == null && rawRelevance != null) {
            relevance = XPathParseTool.parseXPath(rawRelevance);
        }
        return relevance;
    }

    /**
     * @return A string representing an XPath expression to determine
     * whether or not to display this menu.
     */
    public String getMenuRelevanceRaw() {
        return rawRelevance;
    }

    /**
     * @return The ID of what command actions should be available
     * when viewing this menu.
     */
    public Vector<String> getCommandIds() {
        //UNSAFE! UNSAFE!
        return commandIds;
    }

    public XPathExpression getCommandRelevance(int index) throws XPathSyntaxException {
        //Don't cache this for now at all
        return commandExprs[index] == null ? null : XPathParseTool.parseXPath(commandExprs[index]);
    }

    /**
     * @return an optional string indicating how this menu wants to display its items
     */
    public String getStyle() {
        return style;
    }

    /**
     * @param index the
     * @return the raw xpath string for a relevant condition (if available). Largely for
     * displaying to the user in the event of a failure
     */
    public String getCommandRelevanceRaw(int index) {
        return commandExprs[index];
    }

    @Override
    public void readExternal(DataInputStream in, PrototypeFactory pf)
            throws IOException, DeserializationException {
        id = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
        root = ExtUtil.readString(in);
        rawRelevance = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
        display = (DisplayUnit)ExtUtil.read(in, DisplayUnit.class, pf);
        commandIds = (Vector<String>)ExtUtil.read(in, new ExtWrapList(String.class), pf);
        commandExprs = new String[ExtUtil.readInt(in)];
        for (int i = 0; i < commandExprs.length; ++i) {
            if (ExtUtil.readBool(in)) {
                commandExprs[i] = ExtUtil.readString(in);
            }
        }
        style = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
    }

    @Override
    public void writeExternal(DataOutputStream out) throws IOException {
        ExtUtil.writeString(out, ExtUtil.emptyIfNull(id));
        ExtUtil.writeString(out, root);
        ExtUtil.writeString(out, ExtUtil.emptyIfNull(rawRelevance));
        ExtUtil.write(out, display);
        ExtUtil.write(out, new ExtWrapList(commandIds));
        ExtUtil.writeNumeric(out, commandExprs.length);
        for (String commandExpr : commandExprs) {
            if (commandExpr == null) {
                ExtUtil.writeBool(out, false);
            } else {
                ExtUtil.writeBool(out, true);
                ExtUtil.writeString(out, commandExpr);
            }
        }

        ExtUtil.writeString(out, ExtUtil.emptyIfNull(style));
    }

    @Override
    public String getImageURI() {
        if (display.getImageURI() == null) {
            return null;
        }
        return display.getImageURI().evaluate();
    }

    @Override
    public String getAudioURI() {
        if (display.getAudioURI() == null) {
            return null;
        }
        return display.getAudioURI().evaluate();
    }

    @Override
    public String getDisplayText(EvaluationContext ec) {
        if (display.getText() == null) {
            return null;
        }
        return display.getText().evaluate(ec);
    }

    @Override
    public Single<String> getTextForBadge(final EvaluationContext ec) {
        if (display.getBadgeText() == null) {
            return Single.just("");
        }

        return display.getBadgeText().getDisposableSingleForEvaluation(ec);
    }

    @Override
    public Text getRawBadgeTextObject() {
        return display.getBadgeText();
    }

    @Override
    public Text getRawText() {
        return display.getText();
    }

    @Override
    public String getCommandID() {
        return id;
    }

    // unsafe! assumes that xpath expressions evaluate properly...
    public int indexOfCommand(String cmd) {
        return commandIds.indexOf(cmd);
    }

    @Override
    public String toString() {
        return "Menu with id " + this.getId();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveSupport::FileWatcher::Backend</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.0.2

            Class
            ActiveSupport::FileWatcher::Backend

                <

                    Object

/usr/local/lib/ruby/gems/2.1.0/gems/activesupport-4.0.2/lib/active_support/file_watcher.rb

Methods

N

                new

T

                trigger

Class Public methods

              new(path, watcher)

            Link

                Source:
                show

# File ../../../../usr/local/lib/ruby/gems/2.1.0/gems/activesupport-4.0.2/lib/active_support/file_watcher.rb, line 4
def initialize(path, watcher)
  @watcher = watcher
  @path    = path
end

Instance Public methods

              trigger(files)

            Link

                Source:
                show

# File ../../../../usr/local/lib/ruby/gems/2.1.0/gems/activesupport-4.0.2/lib/active_support/file_watcher.rb, line 9
def trigger(files)
  @watcher.trigger(files)
end


text:
package org.spongepowered.api.block.entity.carrier.furnace;

import org.spongepowered.api.block.entity.carrier.NameableCarrierBlockEntity;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.data.value.Value;
import org.spongepowered.api.item.recipe.Recipe;
import org.spongepowered.api.util.Ticks;

/**
 * Represents the types of furnaces in Vanilla minecraft.
 */
public interface FurnaceBlockEntity extends NameableCarrierBlockEntity {

    /**
     * Attempts to process the {@link Recipe} for results.
     *
     * @return If the process was successful.
     */
    boolean process();

    /**
     * Gets the {@link org.spongepowered.api.data.value.Value.Mutable} for the remaining fuel.
     *
     * @return The value for the remaining fuel
     */
    default Value.Mutable<Integer> remainingFuel() {
        return this.requireValue(Keys.FUEL).asMutable();
    }

    /**
     * Gets the {@link org.spongepowered.api.data.value.Value.Mutable} for the maximum amount of fuel that
     * can be supplied with the used fuel item.
     *
     * @return The value for the maximum amount of fuel that can be supplied
     *         with the used fuel item
     */
    default Value.Mutable<Ticks> maxBurnTime() {
        return this.requireValue(Keys.MAX_BURN_TIME).asMutable();
    }

    /**
     * Gets the {@link org.spongepowered.api.data.value.Value.Mutable} for the already passed cook time of
     * the item stack in this furnace.
     *
     * @return The value for the already passed cook time
     */
    default Value.Mutable<Ticks> passedCookTime() {
        return this.requireValue(Keys.PASSED_COOK_TIME).asMutable();
    }

    /**
     * Gets the {@link org.spongepowered.api.data.value.Value.Mutable} for the total time the item stack
     * has to cook until it is cooked.
     *
     * @return The value for the time the item has to cook
     */
    default Value.Mutable<Ticks> maxCookTime() {
        return this.requireValue(Keys.MAX_COOK_TIME).asMutable();
    }

}


text:
/**
 * Created by Lzientek on 02-10-2016.
 */

import mongoose = require("mongoose");
import IVote = require("./VoteModel");

interface CardModel extends mongoose.Document {
    title: string;
    startDate: Date;
    timeToConsensus: number;
    evaluation: number;
    votes: IVote[];
}

export = CardModel;


text:
package org.tfdroid.screen;

import org.tfdroid.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

public class ScrollScreen extends ViewGroup {

	private ScreenIndicator indicator;
    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;

    private int mTouchSlop;
    private int mMaximumVelocity;
    private int mDefaultScreen;
    private int mCurrentScreen;
	private boolean mFirstLayout = true;

    private float mLastMotionX;
    private int mTouchState = TOUCH_STATE_REST;
	private OnScreenChangeListener mOnScreenChangeListener;

    private static final int DEFAULT_SCREEN = 0;
    private static final int SNAP_VELOCITY = 600;
    private final static int TOUCH_STATE_REST = 0;
    private final static int TOUCH_STATE_SCROLLING = 1;

    public ScrollScreen(Context context, AttributeSet attrs) {
		super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ScrollScreen);
        mDefaultScreen = a.getInt(R.styleable.ScrollScreen_default_screen, DEFAULT_SCREEN);
        a.recycle();

        initScrollScreen();
	}

    private void initScrollScreen() {
        Context context = getContext();
        mScroller = new Scroller(context);

        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
        mTouchSlop = configuration.getScaledTouchSlop();
        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
        mCurrentScreen = mDefaultScreen;

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        final int width = MeasureSpec.getSize(widthMeasureSpec);
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        if (widthMode != MeasureSpec.EXACTLY) {
            throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
        }

        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode != MeasureSpec.EXACTLY) {
            throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
        }

        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
        }

        if (mFirstLayout) {
            setHorizontalScrollBarEnabled(false);
            scrollTo(mCurrentScreen * width, 0);
            setHorizontalScrollBarEnabled(true);
            mFirstLayout = false;

        	if (indicator != null) {
        		indicator.setCurrentScreen(mCurrentScreen);
        	}
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int childLeft = 0;

        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                final int childWidth = child.getMeasuredWidth();
                child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
                childLeft += childWidth;
            }
        }
    }

    @Override
    public void computeScroll() {///²»Í¬
        if (mScroller.computeScrollOffset()) {
        	scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
            return true;
        }

        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);

        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                final float x = ev.getX();
                final int xDiff = (int) Math.abs(x - mLastMotionX);

                final int touchSlop = mTouchSlop;
                boolean xMoved = xDiff > touchSlop;

                if (xMoved) {
                    mTouchState = TOUCH_STATE_SCROLLING;
                    mLastMotionX = x;
                }
                break;
            }

            case MotionEvent.ACTION_DOWN: {
                final float x = ev.getX();
                mLastMotionX = x;

                mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
                break;
            }

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mTouchState = TOUCH_STATE_REST;

                if (mVelocityTracker != null) {
                    mVelocityTracker.recycle();
                    mVelocityTracker = null;
                }

                break;
        }

        return mTouchState != TOUCH_STATE_REST;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);

        final int action = ev.getAction();

        switch (action & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            if (!mScroller.isFinished()) {
                mScroller.abortAnimation();
            }

            mLastMotionX = ev.getX();
            break;
        case MotionEvent.ACTION_MOVE:///²»Í¬
            final float x = ev.getX();
            final float deltaX = mLastMotionX - x;
            mLastMotionX = x;

            scrollBy((int) deltaX, 0);
            break;
        case MotionEvent.ACTION_UP:///²»Í¬
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            final int velocityX = (int) velocityTracker.getXVelocity();

            if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
            	snapToScreen(mCurrentScreen - 1);
            } else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
            	snapToScreen(mCurrentScreen + 1);
            } else {
            	snapToDestination();
            }

            if (mVelocityTracker != null) {
                mVelocityTracker.recycle();
                mVelocityTracker = null;
            }
            mTouchState = TOUCH_STATE_REST;
            break;
        case MotionEvent.ACTION_CANCEL:
            mTouchState = TOUCH_STATE_REST;
            break;
        }

        return true;
    }

	public void snapToDestination() {
		final int screenWidth = getWidth();
		final int destScreen = (getScrollX() + screenWidth / 2) / screenWidth;
		snapToScreen(destScreen);
	}

    private void snapToScreen(int whichScreen) {
        whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
		if (getScrollX() != (whichScreen * getWidth())) {
			final int delta = whichScreen * getWidth() - getScrollX();
			mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
			mCurrentScreen = whichScreen;
			invalidate();

			if (indicator != null) {
				indicator.setCurrentScreen(mCurrentScreen);
			}

			invokeOnScreenChangeListener();
		}
    }

    public void addScreen(View view) {
    	addView(view,new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    	if (indicator == null) {
    		return;
    	}

		indicator.addIndicator();
    }

    public void addScreen(int count, ScreenContentFactory contentFactory) {
    	for (int i = 0; i < count; i++) {
    		addScreen(contentFactory.createScreenContent(i));
		}
    }

    public interface ScreenContentFactory {

    	View createScreenContent(int index);
    }

    public void setScreenIndicator(ScreenIndicator indicator) {
		this.indicator = indicator;
	}

	public int getCurrentScreen() {
		return mCurrentScreen;
	}

	public void setToScreen(int whichScreen) {
		whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
		mCurrentScreen = whichScreen;
		scrollTo(whichScreen * getWidth(), 0);

    	if (indicator != null) {
    		indicator.setCurrentScreen(mCurrentScreen);
    	}
	}

	public interface ScreenIndicator {

    	void addIndicator();

    	void setCurrentScreen(int index);
    }

    public void setOnScreenChangedListener(OnScreenChangeListener l) {
        mOnScreenChangeListener = l;
    }

    private void invokeOnScreenChangeListener() {
        if (mOnScreenChangeListener != null) {
            mOnScreenChangeListener.onScreenChanged(getCurrentScreen());
        }
    }

	public interface OnScreenChangeListener {

		void onScreenChanged(int index);
	}
}


text:
require 'cms_scanner/finders/finder/smart_url_checker'
require 'cms_scanner/finders/finder/enumerator'
require 'cms_scanner/finders/finder/fingerprinter'

module CMSScanner
  module Finders
    # Finder
    class Finder
      # Constants for common found_by
      DIRECT_ACCESS = 'Direct Access (Aggressive Detection)'

      attr_accessor :target

      def initialize(target)
        @target = target
      end

      # @return [ String ] The titleized name of the finder
      def titleize
        self.class.to_s.demodulize.underscore.titleize
      end

      # @param [ Hash ] _opts
      def passive(_opts = {})
      end

      # @param [ Hash ] _opts
      def aggressive(_opts = {})
      end

      # @param [ Hash ] opts See https://github.com/jfelchner/ruby-progressbar/wiki/Options
      #
      # @return [ ProgressBar::Base ]
      def progress_bar(opts = {})
        ProgressBar.create({ format: '%t %a <%B> (%c / %C) %P%% %e' }.merge(opts))
      end

      # @return [ Browser ]
      def browser
        @browser ||= NS::Browser.instance
      end

      # @return [ Typhoeus::Hydra ]
      def hydra
        @hydra ||= browser.hydra
      end

      def found_by
        caller_locations.each do |call|
          label = call.label

          next unless label == 'aggressive' || label == 'passive'

          return "#{titleize} (#{label.capitalize} Detection)"
        end
        nil
      end
    end
  end
end


text:
/*eslint-disable no-console */

'use strict';

var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var livereload = require('gulp-livereload');
var babelify = require('babelify');
var babel = require('gulp-babel');
var eslint = require('gulp-eslint');
var connect = require('gulp-connect');

gulp.task('default', ['connect'], function() {
  livereload.listen(35729);

  var watcher = watchify(browserify({
    entries: ['./examples/index.js'],
    transform: [babelify],
    debug: true,
    cache: {}, packageCache: {}, fullPaths: true
  }));

  watcher.on('update', rebundle);
  function rebundle() {
    return watcher
      .bundle()
      .on('error', function(err) { console.log('Error : ' + err.message); })
      .pipe(source('bundle.js'))
      .pipe(gulp.dest('./examples'))
      .pipe(livereload());
  }
  return rebundle();
});

gulp.task('eslint', function() {
  return gulp.src(['lib/**/*.js', 'gulpfile.js'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('build', function() {
  return gulp.src('./lib/portal.js')
    .pipe(babel())
    .pipe(gulp.dest('./'));
});

gulp.task('connect', function() {
  connect.server({
    root: 'examples',
    livereload: true
  });
});


text:
jQuery.sap.declare("sap.m.ColumnListItemRenderer");
jQuery.sap.require("sap.ui.core.Renderer");
jQuery.sap.require("sap.m.ListRenderer");
jQuery.sap.require("sap.m.ListItemBaseRenderer");

/**
 * @class ColumnListItem renderer.
 * @static
 */
sap.m.ColumnListItemRenderer = sap.ui.core.Renderer.extend(sap.m.ListItemBaseRenderer);

/**
 * Renders the HTML for the given control, using the provided
 * {@link sap.ui.core.RenderManager}.
 *
 * @param {sap.ui.core.RenderManager}
 *            oRenderManager the RenderManager that can be used for writing to
 *            the Render-Output-Buffer
 * @param {sap.ui.core.Control}
 *            oControl an object representation of the control that should be
 *            rendered
 */
sap.m.ColumnListItemRenderer.renderLIAttributes = function(rm, oLI) {
	rm.addClass("sapMListTblRow");
	var vAlign = oLI.getVAlign();
	if (vAlign != sap.ui.core.VerticalAlign.Inherit) {
		rm.addClass("sapMListTblRow" + vAlign);
	}
};

/**
 * Overwriting hook method of ListItemBase
 *
 * @public
 *
 * @param {sap.ui.core.RenderManager} rm RenderManager
 * @param {sap.m.ListItemBase} oLI List item
 * @param {sap.m.Table} oTable Table control
 */
sap.m.ColumnListItemRenderer.renderLIContent = function(rm, oLI, oTable) {
	if (!oTable) {
		return;
	}

	var aColumns = oTable.getColumns(true),
		aCells = oLI.getCells();

	// remove cloned headers
	oLI.destroyAggregation("clonedHeaders", true);

	// remove pop-in if list is not in rendering phase
	// in rendering phase all pop-ins are already removed
	if (!oTable._bRendering) {
		oLI.removePopin();
	}

	aColumns.forEach(function(oColumn, i) {
		var cls,
			bRenderCell = true,
			oCell = aCells[oColumn.getInitialOrder()];

		if (!oCell || !oColumn.getVisible() || oColumn.isNeverVisible(true) || oColumn.isPopin()) {
			return;
		}

		rm.write("<td");
		rm.addClass("sapMListTblCell");
		rm.writeAttribute("id", oLI.getId() + "_cell" + i);

		// check column properties
		if (oColumn) {
			cls = oColumn.getStyleClass(true);
			cls && rm.addClass(cls);

			// merge duplicate cells
			if (!oTable.hasPopin() && oColumn.getMergeDuplicates()) {
				var sFuncWithParam = oColumn.getMergeFunctionName(),
					aFuncWithParam = sFuncWithParam.split("#"),
					sFuncParam = aFuncWithParam[1],
					sFuncName = aFuncWithParam[0];

				if (typeof oCell[sFuncName] != "function") {
					jQuery.sap.log.warning("mergeFunctionName property is defined on " + oColumn + " but this is not function of " + oCell);
				} else {
					var lastColumnValue = oColumn.getLastValue(),
						cellValue = oCell[sFuncName](sFuncParam);

					if (lastColumnValue === cellValue) {
						bRenderCell = false;
						rm.addClass("sapMListTblCellDup");
					} else {
						oColumn.setLastValue(cellValue);
					}
				}
			}

			oColumn.getVAlign() != "Inherit" && rm.addStyle("vertical-align", oColumn.getVAlign().toLowerCase());
			rm.addStyle("text-align", oColumn.getCssAlign());
			rm.writeStyles();
		}

		rm.writeClasses();
		rm.write(">");
		if (bRenderCell) {
			rm.renderControl(oColumn.applyAlignTo(oCell));
		}
		rm.write("	");
	});
};

/**
 * Renders pop-ins for Table Rows
 *
 * @private
 *
 * @param {sap.ui.core.RenderManager} rm RenderManager
 * @param {sap.m.ListItemBase} oLI List item
 * @param {sap.m.Table} oTable Table control
 */
sap.m.ColumnListItemRenderer.renderPopin = function(rm, oLI, oTable) {
	oLI._popinId = oLI.getId() + "-sub";
	rm.write("

");

	var aCells = oLI.getCells(),
		aColumns = oTable.getColumns(true);

	aColumns.forEach(function(oColumn) {
		if (!oColumn.getVisible() || !oColumn.isPopin()) {
			return;
		}

		var oCell = aCells[oColumn.getInitialOrder()],
			oHeader = oColumn.getHeader();

		if (!oHeader && !oCell) {
			return;
		}

		var cls = oColumn.getStyleClass();

		/* row start */
		rm.write("
");

		/* header cell */
		if (oHeader) {
			rm.write("
");
			oHeader = oHeader.clone();
			oLI.addAggregation("clonedHeaders", oHeader, true);
			oColumn.applyAlignTo(oHeader, "Begin");
			rm.renderControl(oHeader);
			rm.write("
");

			/* separator cell */
			rm.write("
:
");
		}

		/* value cell */
		if (oCell) {
			rm.write("
");
			oColumn.applyAlignTo(oCell, "Begin");
			rm.renderControl(oCell);
			rm.write("
");
		}

		/* row end */
		rm.write("
");
	});

	rm.write("

");
};