text:
"""
@package mi.dataset.parser.rasfl_a_subcon
@file marine-integrations/mi/dataset/parser/rasfl_a_subcon_recovered_driver.py
@author Rachel Manoni
@brief Parser for the rasfl_a_subcon dataset driver

Release notes:

Initial Release
"""

__author__ = 'Rachel Manoni'
__license__ = 'Apache 2.0'

import calendar
import time
import csv
import math

from mi.core.instrument.data_particle import DataParticle, DataParticleKey
from mi.dataset.dataset_parser import SimpleParser
from mi.core.log import get_logger
log = get_logger()

RASFL_DATA_MAP = [
    ('serial_number', 1, str),
    ('start_time', 2, str),
    ('stop_time', 3, str),
    ('port_number', 4, int),
    ('lat', 5, float),
    ('lon', 6, float),
    ('m_depth', 7, int),
    ('temp', 8, float),
    ('acidity', 9, float),
    ('alkalinity', 10, float),
    ('hydrogen_sulfide_concentration', 11, float),
    ('silicon_concentration', 12, float),
    ('ammonia_concentration', 13, float),
    ('chloride_concentration', 14, float),
    ('sulfate_concentration', 15, float),
    ('sodium_concentration', 16, float),
    ('potassium_concentration', 17, float),
    ('magnesium_concentration', 18, float),
    ('calcium_concentration', 19, float),
    ('bromide_concentration', 20, float),
    ('iron_concentration', 21, float),
    ('manganese_concentration', 22, float),
    ('lithium_concentration', 23, float),
    ('strontium_icpaes_concentration', 24, float),
    ('boron_concentration', 25, float),
    ('rubidium_concentration', 26, float),
    ('cesium_concentration', 27, float),
    ('strontium_icpms_concentration', 28, float),
    ('barium_concentration', 29, float),
    ('cobalt_concentration', 30, float),
    ('nickel_concentration', 31, float),
    ('copper_concentration', 32, float),
    ('zinc_concentration', 33, float),
    ('molybdenum_concentration', 34, float),
    ('silver_concentration', 35, float),
    ('cadmium_concentration', 36, float),
    ('titanium_concentration', 37, float),
    ('aluminum_concentration', 38, float),
    ('lead_concentration', 39, float),
    ('vanadium_concentration', 40, float),
    ('uranium_concentration', 41, float),
    ('yttrium_concentration', 42, float),
    ('gadolinium_concentration', 43, float)
]

START_TIME_IDX = 2

class RasflASubconInstrumentDataParticle(DataParticle):

    _data_particle_type = 'rasfl_a_subcon_instrument_recovered'
    instrument_particle_map = RASFL_DATA_MAP

    def __init__(self, raw_data, *args, **kwargs):

        super(RasflASubconInstrumentDataParticle, self).__init__(raw_data, *args, **kwargs)

        # set timestamp mm/dd/yy hh:mm
        struct_time = time.strptime(self.raw_data[START_TIME_IDX], "%m/%d/%y %H:%M")
        elapsed_seconds = calendar.timegm(struct_time)
        self.set_internal_timestamp(unix_time=elapsed_seconds)

    def _build_parsed_values(self):
        """
        Build parsed values for the Instrument Data Particle.
        """
        return [self._encode_value(name, self.raw_data[group], function)
                for name, group, function in self.instrument_particle_map]

    def _encode_value(self, name, value, encoding_function):
        """
        Encode a value using the encoding function,
        If there is an error, return None as a value for that parameter
        """
        try:
            if encoding_function is float and math.isnan(float(value)):
                encoded_val = None
            else:
                encoded_val = encoding_function(value)
        except Exception as e:
            log.warn("Data particle error encoding. Name:%s Value:%s", name, value)
            encoded_val = None
        finally:
            return {DataParticleKey.VALUE_ID: name,
                    DataParticleKey.VALUE: encoded_val}

class RasflASubconParser(SimpleParser):

    def parse_file(self):
        """
        Parse a .csv input file. Build a data particle from the parsed data.
        """
        reader = csv.reader(self._stream_handle)
        for row in reader:
            log.debug("Read in line: %r", row)

            try:
                # Extract a particle and append it to the record buffer
                particle = self._extract_sample(RasflASubconInstrumentDataParticle, None, row, None)
                self._record_buffer.append(particle)
            except:
                log.warn("Data cannot be parsed: %r", row)


text:
var fs = require('fs');
var path = require('path');
var lazoPath = path.dirname(module.filename);
var os = require('os');
var lazo = require('./index.js')
var args = parseArgs();

// helper functions
function getAppDir() {
    var fileRepo = args._[1] ? path.resolve(args._[1]) : undefined;
    return fileRepo && fs.existsSync(fileRepo) ? fileRepo : 0;
}

function parseArgs() {
    return require('yargs')
        .alias('c', 'cluster')
        .alias('v', 'version')
        .alias('d', 'daemon')
        .alias('p', 'port')
        .default('port', '8080')
        .alias('r', 'robust')
        .boolean(['d', 'r'])
        .string(['p', 'c'])
        .argv;
}

// get the options for a lazo command
function getStartEnvOptions() {
    var options = {};

    for (var k in args) {
        switch (k) {
            case 'daemon':
            case 'robust':
                options[k] = args[k] === true ? '1' : '0';
                break;
            case 'cluster':
                options[k] = args[k] ? args[k] : os.cpus().length;
                break;
            case 'port':
                options[k] = args[k];
                break;
        }
    }

    return options;
}

// lazo --help [command]
function help(command) {
    switch (command) {
        case 'start':
            console.log('\nUsage: lazo start app_dir -c [num] -d -p [num]\n');
            console.log('Options:\n');
            console.log('app_dir [required] application directory');
            console.log('-c [optional] cluster, value [optional]\n');
            console.log('-d [optional] daemonize process using forever\n');
            console.log('-p [optional] port, value [required]\n');
            break;
        case 'stop':
            console.log('\nUsage: lazo stop\n');
            break;
        default:
            console.log('\nUsage: lazo --help command\n');
            console.log('Available commands: start stop\n');
            console.log('Options:\n');
            console.log('command [optional]\n');
            break;
    }
}

// entry point
function main() {
    if (args._.length) {
        switch (args._[0]) {
            case 'start':
                args.app_dir = getAppDir();
                lazo('start', args);
                break;
            case 'stop':
                lazo('stop', args);
                break;
            default:
                help();
                break;
        }
    } else {
        if (args.version) {
            console.log('v' + lazo('version'));
        } else if (args.help) {
            help(args.help);
        } else {
            help();
        }
    }
}

module.exports = main;

redpajama_set_name: RedPajamaGithub


text:
package dao.sitedata

import scala.concurrent.Future
import javax.inject.Inject
import play.api.db.slick.DatabaseConfigProvider
import play.api.db.slick.HasDatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import slick.driver.JdbcProfile
import slick.jdbc.GetResult
import models.sitedata.SiteInfoAccessMail
import play.db.NamedDatabase
import play.api.Logger
import org.joda.time.DateTime
import java.sql.Timestamp
import com.github.tototoshi.slick.PostgresJodaSupport._

trait ISiteInfoAccessMailDao extends BaseDao[SiteInfoAccessMail]{
  def findAll(): Future[Seq[SiteInfoAccessMail]]
  def findById(id: Long): Future[Option[SiteInfoAccessMail]]
  def remove(id: Long): Future[Int]
  def insert(p: SiteInfoAccessMail): Future[Unit]
  def update(p2: SiteInfoAccessMail): Future[Unit]
}

class SiteInfoAccessMailDao @Inject()(@NamedDatabase("SiteData") protected val dbConfigProvider: DatabaseConfigProvider)
    extends HasDatabaseConfigProvider[JdbcProfile] with ISiteInfoAccessMailDao {

//  import driver.api._
  import com.typesafe.slick.driver.ms.SQLServerDriver.api._

  class SiteInfoAccessMailTable(tag: Tag)
      extends Table[SiteInfoAccessMail](tag, models.sitedata.SiteInfoAccessMailDef.toTable) {

    def id                = column[Long]("ID", O.PrimaryKey)
    def siteid            = column[String]("SiteID")
    def mailaddress       = column[Option[String]]("MailAddress")
    def mailaddresstype   = column[String]("MailAddressType")
//  def lastmodifiedtime  = column[DateTime]("LastModifiedTime")
//  def lastmodifier      = column[Option[String]]("LastModifier")
//  def modifiedtimestamp = column[TimeStamp]

    def * = (
      id,
      siteid,
      mailaddress,
      mailaddresstype
//      lastmodifiedtime: DateTime,
//      lastmodifier: String,
//      modifiedtimestamp: Timestamp
    ) <> (SiteInfoAccessMail.tupled, SiteInfoAccessMail.unapply _)
  }

  lazy val sourcefilename = new Exception().getStackTrace.head.getFileName

  override def toTable = TableQuery[SiteInfoAccessMailTable]

  private val Sites = toTable()

  override def findAll(): Future[Seq[SiteInfoAccessMail]] = {
    db.run(Sites.result)
  }

  override def findById(id: Long): Future[Option[SiteInfoAccessMail]] = {
    Logger.info("(" + sourcefilename + ")" + " findById(" + id + ") called.")
    db.run(Sites.filter( _.id === id).result.headOption)
  }

  override def remove(id: Long): Future[Int] = {
    /* db.run(Sites.filter( _.siteid === id).delete) */
    Future(0) // dummy
  }

  override def insert(p: SiteInfoAccessMail): Future[Unit] = {
    /* db.run(Sites += p).map { _ => () } */
    Future(()) // dummy
  }

  override def update(p2: SiteInfoAccessMail) = Future[Unit] {
/*     db.run(
 *        Sites.filter(_.siteid === p2.siteid)
 * //         .map(p => (p.name,p.details, p.price))
 *          .map(p => (p.sitename))
 * //         .update((p2.name,p2.details,p2.price))
 *          .update((p2.sitename))
 *     ) */
  Future(()) // dummy
  }
}


text:
<?php

namespace humhub\modules\user\authclient;

/**
 * Extended BaseClient with additional events
 *
 * @since 1.1
 * @author luke
 */
class BaseClient extends \yii\authclient\BaseClient
{

    /**
     * @event Event an event raised on update user data.
     * @see AuthClientHelpers::updateUser()
     */
    const EVENT_UPDATE_USER = 'update';

    /**
     * @event Event an event raised on create user.
     * @see AuthClientHelpers::createUser()
     */
    const EVENT_CREATE_USER = 'create';

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sarcinella puzolziae Hosag.

### Remarks
null


text:
using System;
using System.Windows.Input;

namespace Stamper.UI.ViewModels.Base
{
    /// <summary>
    /// Implementation of ICommand that provides a mechanism for enabling/disabling
    /// the bound element based on the given predicate.
    /// </summary>
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;

        private readonly Predicate<object> _canExecute;

        public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
        {
            if (execute == null)
            {
                throw new ArgumentNullException(nameof(execute));
            }
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute?.Invoke(parameter) ?? true;
        }

        public event EventHandler CanExecuteChanged;

        public void OnCanExecuteChanged(object sender)
        {
            CanExecuteChanged?.Invoke(sender, EventArgs.Empty);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}


text:
/**
 Sego Presentation Styling
**/
.sego-logo {
  position: absolute;
  bottom: 1em;
  left: 2em; }

.reveal section img.no-style-image {
  background: none;
  border: none;
  box-shadow: none; }

.spin-code {
  float: right; }
  .spin-code blockquote {
    color: white;
    font-family: 'Source Sans Pro', Helvetica, sans-serif;
    font-size: 1.7em;
    background: #527c97;
    padding: 10px; }

.stack-starter {
  float: left; }
  .stack-starter blockquote {
    color: white;
    font-family: 'Source Sans Pro', Helvetica, sans-serif;
    font-size: 1.7em; }

.reveal a.p2-logo {
  margin-left: 25px; }

.reveal section img.clean {
  background: transparent;
  border: none;
  box-shadow: none; }

.mai.photo {
  width: 25%; }


text:
package net.bytebuddy.asm;

import net.bytebuddy.test.utility.MockitoRule;
import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import org.objectweb.asm.ClassVisitor;

import static org.mockito.Mockito.*;

public class ClassVisitorWrapperChainTest {

    @Rule
    public TestRule mockitoRule = new MockitoRule(this);

    @Mock
    private ClassVisitorWrapper first, prepend, append;

    @Mock
    private ClassVisitor classVisitor;

    @Before
    public void setUp() throws Exception {
        when(first.wrap(any(ClassVisitor.class))).thenReturn(classVisitor);
        when(prepend.wrap(any(ClassVisitor.class))).thenReturn(classVisitor);
        when(append.wrap(any(ClassVisitor.class))).thenReturn(classVisitor);
    }

    @Test
    public void testWrapperChain() throws Exception {
        ClassVisitorWrapper.Chain chain = new ClassVisitorWrapper.Chain();
        chain = chain.append(first).append(append).prepend(prepend);
        chain.wrap(classVisitor);
        verify(prepend).wrap(classVisitor);
        verifyNoMoreInteractions(prepend);
        verify(first).wrap(classVisitor);
        verifyNoMoreInteractions(first);
        verify(append).wrap(classVisitor);
        verifyNoMoreInteractions(append);
    }

    @Test
    public void testObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(ClassVisitorWrapper.Chain.class).apply();
    }
}


text:
package proc

import (
	"golang.org/x/arch/arm64/arm64asm"
)

// AsmDecode decodes the assembly instruction starting at mem[0:] into asmInst.
// It assumes that the Loc and AtPC fields of asmInst have already been filled.
func (a *ARM64) AsmDecode(asmInst *AsmInstruction, mem []byte, regs Registers, memrw MemoryReadWriter, bi *BinaryInfo) error {
	asmInst.Size = 4
	asmInst.Bytes = mem[:asmInst.Size]

	inst, err := arm64asm.Decode(mem)
	if err != nil {
		asmInst.Inst = (*arm64ArchInst)(nil)
		return err
	}

	asmInst.Inst = (*arm64ArchInst)(&inst)
	asmInst.Kind = OtherInstruction

	switch inst.Op {
	case arm64asm.BL, arm64asm.BLR:
		asmInst.Kind = CallInstruction
	case arm64asm.RET, arm64asm.ERET:
		asmInst.Kind = RetInstruction
	}

	asmInst.DestLoc = resolveCallArgARM64(&inst, asmInst.Loc.PC, asmInst.AtPC, regs, memrw, bi)

	return nil
}

func (a *ARM64) Prologues() []opcodeSeq {
	return prologuesARM64
}

func resolveCallArgARM64(inst *arm64asm.Inst, instAddr uint64, currentGoroutine bool, regs Registers, mem MemoryReadWriter, bininfo *BinaryInfo) *Location {
	if inst.Op != arm64asm.BL && inst.Op != arm64asm.BLR {
		return nil
	}

	var pc uint64
	var err error

	switch arg := inst.Args[0].(type) {
	case arm64asm.Imm:
		pc = uint64(arg.Imm)
	case arm64asm.Reg:
		if !currentGoroutine || regs == nil {
			return nil
		}
		pc, err = regs.Get(int(arg))
		if err != nil {
			return nil
		}
	case arm64asm.PCRel:
		pc = uint64(instAddr) + uint64(arg)
	default:
		return nil
	}

	file, line, fn := bininfo.PCToLine(pc)
	if fn == nil {
		return &Location{PC: pc}
	}
	return &Location{PC: pc, File: file, Line: line, Fn: fn}
}

// Possible stacksplit prologues are inserted by stacksplit in
// $GOROOT/src/cmd/internal/obj/arm64/obj7.go.
var prologuesARM64 []opcodeSeq

func init() {
	var tinyStacksplit = opcodeSeq{uint64(arm64asm.MOV), uint64(arm64asm.CMP), uint64(arm64asm.B)}
	var smallStacksplit = opcodeSeq{uint64(arm64asm.SUB), uint64(arm64asm.CMP), uint64(arm64asm.B)}
	var bigStacksplit = opcodeSeq{uint64(arm64asm.CMP), uint64(arm64asm.B), uint64(arm64asm.ADD), uint64(arm64asm.SUB), uint64(arm64asm.MOV), uint64(arm64asm.CMP), uint64(arm64asm.B)}
	var unixGetG = opcodeSeq{uint64(arm64asm.LDR)}

	prologuesARM64 = make([]opcodeSeq, 0, 3)
	for _, getG := range []opcodeSeq{unixGetG} {
		for _, stacksplit := range []opcodeSeq{tinyStacksplit, smallStacksplit, bigStacksplit} {
			prologue := make(opcodeSeq, 0, len(getG)+len(stacksplit))
			prologue = append(prologue, getG...)
			prologue = append(prologue, stacksplit...)
			prologuesARM64 = append(prologuesARM64, prologue)
		}
	}
}

type arm64ArchInst arm64asm.Inst

func (inst *arm64ArchInst) Text(flavour AssemblyFlavour, pc uint64, symLookup func(uint64) (string, uint64)) string {
	if inst == nil {
		return "?"
	}

	var text string

	switch flavour {
	case GNUFlavour:
		text = arm64asm.GNUSyntax(arm64asm.Inst(*inst))
	default:
		text = arm64asm.GoSyntax(arm64asm.Inst(*inst), pc, symLookup, nil)
	}

	return text
}

func (inst *arm64ArchInst) OpcodeEquals(op uint64) bool {
	if inst == nil {
		return false
	}
	return uint64(inst.Op) == op
}


text:
<?php

/**
 *		\file       htdocs/install/repair.php
 *      \brief      Run repair script
 *      \version    $Id: repair.php,v 1.10 2010/12/15 18:15:08 eldy Exp $
 */

include_once("./inc.php");
if (file_exists($conffile)) include_once($conffile);
require_once($dolibarr_main_document_root."/lib/databases/".$dolibarr_main_db_type.".lib.php");
require_once($dolibarr_main_document_root."/lib/admin.lib.php");

$grant_query='';
$etape = 2;
$ok = 0;

// Cette page peut etre longue. On augmente le delai autorise.
// Ne fonctionne que si on est pas en safe_mode.
$err=error_reporting();
error_reporting(0);
@set_time_limit(120);
error_reporting($err);

$setuplang=isset($_POST["selectlang"])?$_POST["selectlang"]:(isset($_GET["selectlang"])?$_GET["selectlang"]:'auto');
$langs->setDefaultLang($setuplang);
$versionfrom=isset($_GET["versionfrom"])?$_GET["versionfrom"]:'';
$versionto=isset($_GET["versionto"])?$_GET["versionto"]:'';

$langs->load("admin");
$langs->load("install");

if ($dolibarr_main_db_type == "mysql") $choix=1;
if ($dolibarr_main_db_type == "mysqli") $choix=1;
if ($dolibarr_main_db_type == "pgsql") $choix=2;
if ($dolibarr_main_db_type == "mssql") $choix=3;

dolibarr_install_syslog("repair: Entering upgrade.php page");
if (! is_object($conf)) dolibarr_install_syslog("repair: conf file not initialized",LOG_ERR);

/*
 * View
 */

pHeader('',"upgrade2",GETPOST('action'));

$actiondone=0;

// Action to launch the repair script
$actiondone=1;

print '
'.$langs->trans("Repair").'
';

print '
';
$error=0;

// If password is encoded, we decode it
if (preg_match('/crypted:/i',$dolibarr_main_db_pass) || ! empty($dolibarr_main_db_encrypted_pass))
{
	require_once($dolibarr_main_document_root."/lib/security.lib.php");
	if (preg_match('/crypted:/i',$dolibarr_main_db_pass))
	{
		$dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
		$dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
		$dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass;	// We need to set this as it is used to know the password was initially crypted
	}
	else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
}

// $conf is already instancied inside inc.php
$conf->db->type = $dolibarr_main_db_type;
$conf->db->host = $dolibarr_main_db_host;
$conf->db->port = $dolibarr_main_db_port;
$conf->db->name = $dolibarr_main_db_name;
$conf->db->user = $dolibarr_main_db_user;
$conf->db->pass = $dolibarr_main_db_pass;

$db = new DoliDb($conf->db->type,$conf->db->host,$conf->db->user,$conf->db->pass,$conf->db->name,$conf->db->port);
if ($db->connected == 1)
{
	print '
';
	print $langs->trans("ServerConnection")." : $dolibarr_main_db_host	".$langs->trans("OK")."
";
	dolibarr_install_syslog("repair: ".$langs->transnoentities("ServerConnection")." : $dolibarr_main_db_host ".$langs->transnoentities("OK"));
	$ok = 1;
}
else
{
	print "
".$langs->trans("ErrorFailedToConnectToDatabase",$dolibarr_main_db_name)."	".$langs->transnoentities("Error")."
";
	dolibarr_install_syslog("repair: ".$langs->transnoentities("ErrorFailedToConnectToDatabase",$dolibarr_main_db_name));
	$ok = 0;
}

if ($ok)
{
	if($db->database_selected == 1)
	{
		print '
';
		print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name."	".$langs->trans("OK")."
";
		dolibarr_install_syslog("repair: Database connection successfull : $dolibarr_main_db_name");
		$ok=1;
	}
	else
	{
		print "
".$langs->trans("ErrorFailedToConnectToDatabase",$dolibarr_main_db_name)."	".$langs->trans("Error")."
";
		dolibarr_install_syslog("repair: ".$langs->transnoentities("ErrorFailedToConnectToDatabase",$dolibarr_main_db_name));
		$ok=0;
	}
}

// Affiche version
if ($ok)
{
	$version=$db->getVersion();
	$versionarray=$db->getVersionArray();
	print '
'.$langs->trans("ServerVersion").'	';
	print ''.$version.'
';
	dolibarr_install_syslog("repair: ".$langs->transnoentities("ServerVersion")." : $version");
	//print ''.join('.',$versionarray).'
';
}

// Force l'affichage de la progression
print '
'.$langs->trans("PleaseBePatient").'
';
flush();

/*
 *	Load sql files
 */
if ($ok)
{
	if ($choix==1) $dir = "mysql/migration/";
	elseif ($choix==2) $dir = "pgsql/migration/";
	else $dir = "mssql/migration/";

	$filelist=array();
	$i = 0;
	$ok = 0;
	$from='^'.$versionfrom;
	$to=$versionto.'\.sql$';

	# Recupere list fichier
	$filesindir=array();
	$handle=opendir($dir);
    if (is_resource($handle))
    {
    	while (($file = readdir($handle))!==false)
    	{
    		if (preg_match('/\.sql$/i',$file)) $filesindir[]=$file;
    	}
    }
	sort($filesindir);

	foreach($filesindir as $file)
	{
		if (preg_match('/repair/i',$file))
		{
			$filelist[]=$file;
		}
	}

	# Boucle sur chaque fichier
	foreach($filelist as $file)
	{
		print '
';
		print $langs->trans("ChoosedMigrateScript").'	'.$file.'
';

		$name = substr($file, 0, dol_strlen($file) - 4);

		// Run sql script
		$ok=run_sql($dir.$file, 0, '', 1);
	}
}

print '
';

if ($db->connected) $db->close();

if (empty($actiondone))
{
    print '
'.$langs->trans("ErrorWrongParameters").'
';
}

print '';
print $langs->trans("GoToDolibarr");
print '';

pFooter(1,$setuplang);

?>


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>Class: GradingLevel</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Class
          GradingLevel

            In:

                app/models/grading_level.rb

            Parent:

                ActiveRecord::Base

Methods

      inactivate
      percentage_to_grade
      to_s

Public Class methods

          percentage_to_grade(percent_score, batch_id)

[Source]

    # File app/models/grading_level.rb, line 20
20:     def percentage_to_grade(percent_score, batch_id)
21:       batch_grades = GradingLevel.for_batch(batch_id)
22:       if batch_grades.empty?
23:         grade = GradingLevel.default.find :first,
24:           :conditions => [ "min_score <= ?", percent_score.round ], :order => 'min_score desc'
25:       else
26:         grade = GradingLevel.for_batch(batch_id).find :first,
27:           :conditions => [ "min_score <= ?", percent_score.round ], :order => 'min_score desc'
28:       end
29:       grade
30:     end

Public Instance methods

          inactivate()

[Source]

    # File app/models/grading_level.rb, line 11
11:   def inactivate
12:     update_attribute :is_deleted, true
13:   end

          to_s()

[Source]

    # File app/models/grading_level.rb, line 15
15:   def to_s
16:     name
17:   end

[Validate]


text:
A tiny util for discovering alive hosts in local network. It is fully compatible with the native `nodejs` [EventEmmiter](https://nodejs.org/api/events.html)

# Installation

```sh
npm install ping-subnet
```

# Usage

### You can specify the custom ranges parameter.

Ranges parameter is represented by array of strings. There are two possible forms: just a single IP or the range.

```javascript
const SubnetsPinger = require('ping-subnet');

const ranges = [
  '192.168.0.123',
  '192.168.0.1-192.168.0.100'
];

const subnetPinger = new SubnetsPinger(ranges);

subnetPinger.on('host:alive', ip => {
  console.log('alive', ip);
});

subnetPinger.once('ping:end', () => {
  console.log('ping completed');
});

subnetPinger.ping();
```

### If the custom ranges is not specified it would be assigned using current network settings

```javascript
const SubnetsPinger = require('ping-subnet');

const subnetPinger = new SubnetsPinger();

subnetPinger.on('host:alive', ip => {
  console.log('alive', ip);
});

subnetPinger.once('ping:end', () => {
  console.log('ping completed');
});

subnetPinger.ping();
```


text:
center=nersc
system=edison
nodes=128
threads=24
walltime=03:00:00

build_script=scripts/Cray_XC30/build-spate-intel.sh
app_path=applications/spate_metagenome_assembler/spate
job_template=tests/Edison_Cray_XC30/Template.spate.pbs

root=/project/projectdirs/m1523/Jobs-Edison
dataset=/project/projectdirs/m1523/Data/Iowa_Native_Prairie_Soil

submit_command=qsub

source tests/submit-actor-job-to-scheduler.sh


text:
@interface UIScrollView (PullBig)
@property (nonatomic, strong) UIView *bigView;
@property (nonatomic, strong) UIView *headerView;
-(void)setBigView:(UIView *)bigView withHeaderView:(UIView *)headerView;
@end


text:
<?php
define('lang_Select', 'Select');
define('lang_Erase', 'Erase');
define('lang_Open', 'Open');
define('lang_Confirm_del', 'Are you sure you want to delete this file?');
define('lang_All', 'All');
define('lang_Files', 'Files');
define('lang_Images', 'Images');
define('lang_Archives', 'Archives');
define('lang_Error_Upload', 'The uploaded file exceeds the max size allowed.');
define('lang_Error_extension', 'File extension is not allowed.');
define('lang_Upload_file', 'Upload');
define('lang_Filters', 'Filters');
define('lang_Videos', 'Videos');
define('lang_Music', 'Music');
define('lang_New_Folder', 'New Folder');
define('lang_Folder_Created', 'Folder correctly created');
define('lang_Existing_Folder', 'Existing folder');
define('lang_Confirm_Folder_del', 'Are you sure to delete the folder and all the elements in it?');
define('lang_Return_Files_List', 'Return to files list');
define('lang_Preview', 'Preview');
define('lang_Download', 'Download');
define('lang_Insert_Folder_Name', 'Insert folder name:');
define('lang_Root', 'root');
define('lang_Rename', 'Rename');
define('lang_Back', 'back');
define('lang_View', 'View');
define('lang_View_list', 'List view');
define('lang_View_columns_list', 'Columns list view');
define('lang_View_boxes', 'Box view');
define('lang_Toolbar', 'Toolbar');
define('lang_Actions', 'Actions');
define('lang_Rename_existing_file', 'The file is already existing');
define('lang_Rename_existing_folder', 'The folder is already existing');
define('lang_Empty_name', 'The name is empty');
define('lang_Text_filter', 'text filter');
define('lang_Swipe_help', 'Swipe the name of file/folder to show options');
define('lang_Upload_base', 'Base upload');
define('lang_Upload_java', 'JAVA upload (big size files)');
define('lang_Upload_java_help', "If the Java Applet doesn't load, 1. make sure you have Java installed, otherwise [download link]   2. make sure nothing is blocked by your firewall");
define('lang_Upload_base_help', "Drag & Drop files or click in the area above (modern browsers) and select the file(s). When the upload is complete, click the 'Return to files list' button.");
define('lang_Type_dir', 'dir');
define('lang_Type', 'Type');
define('lang_Dimension', 'Dimension');
define('lang_Size', 'Size');
define('lang_Date', 'Date');
define('lang_Filename', 'Filename');
define('lang_Operations', 'Operations');
define('lang_Date_type', 'y-m-d');
define('lang_OK', 'OK');
define('lang_Cancel', 'Cancel');
define('lang_Sorting', 'sorting');
define('lang_Show_url', 'show URL');
define('lang_Extract', 'extract here');
define('lang_File_info', 'file info');
define('lang_Edit_image', 'edit image');
define('lang_Duplicate', 'Duplicate');


text:
//
// ITemplateCache.cs
//
// Author:
//   Roman Lacko (backup.rlacko@gmail.com)
//
// Copyright (c) 2010 - 2014 Roman Lacko
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Reflection;

namespace SharpTAL.TemplateCache
{
	public interface ITemplateCache
	{
		/// <summary>
		/// Compile template to ensure that the compiled assembly is already in cache when
		/// RenderTemplate is called for the first time. For precompiling, the actual values
		/// of globals are not required, just the names and types of the global variables.
		/// </summary>
		/// <param name="templateBody">The template body</param>
		/// <param name="globalsTypes">Dictionary of types of global variables</param>
		/// <param name="referencedAssemblies">List of referenced assemblies</param>
		/// <returns>The TemplateInfo generated from compiled template body</returns>
		TemplateInfo CompileTemplate(string templateBody, Dictionary<string, Type> globalsTypes, List<Assembly> referencedAssemblies);
	}
}


text:
<?php
/* @var $this VisitorsController */
/* @var $model Visitors */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'id_visitor'); ?>
		<?php echo $form->textField($model,'id_visitor'); ?>

		<?php echo $form->label($model,'ip_visitor'); ?>
		<?php echo $form->textField($model,'ip_visitor',array('size'=>60,'maxlength'=>255)); ?>

		<?php echo $form->label($model,'browser_agent'); ?>
		<?php echo $form->textField($model,'browser_agent',array('size'=>60,'maxlength'=>255)); ?>

		<?php echo $form->label($model,'date_visited'); ?>
		<?php echo $form->textField($model,'date_visited'); ?>

		<?php echo CHtml::submitButton('Search'); ?>

<?php $this->endWidget(); ?>


text:
<?php

namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * Setting Entity
 *
 * @property int $id
 * @property string $key
 * @property string $value
 * @property string $context
 * @property string $scope
 */
class Setting extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false,
    ];
}


text:
package org.gradle.language.nativeplatform.internal.incremental;

import com.google.common.collect.ImmutableList;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.TaskInternal;
import org.gradle.api.internal.TaskOutputsInternal;
import org.gradle.api.internal.file.TaskFileVarFactory;
import org.gradle.api.internal.file.collections.DirectoryFileTreeFactory;
import org.gradle.api.internal.file.collections.MinimalFileSet;
import org.gradle.api.internal.tasks.LifecycleAwareTaskProperty;
import org.gradle.api.provider.Provider;
import org.gradle.cache.PersistentStateCache;
import org.gradle.internal.operations.BuildOperationExecutor;
import org.gradle.internal.snapshot.FileSystemSnapshotter;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.language.nativeplatform.internal.Expression;
import org.gradle.language.nativeplatform.internal.IncludeDirectives;
import org.gradle.language.nativeplatform.internal.Macro;
import org.gradle.language.nativeplatform.internal.incremental.sourceparser.CSourceParser;
import org.gradle.language.nativeplatform.internal.incremental.sourceparser.DefaultIncludeDirectives;
import org.gradle.language.nativeplatform.internal.incremental.sourceparser.MacroWithSimpleExpression;
import org.gradle.language.nativeplatform.internal.incremental.sourceparser.RegexBackedCSourceParser;
import org.gradle.nativeplatform.toolchain.internal.NativeCompileSpec;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DefaultIncrementalCompilerBuilder implements IncrementalCompilerBuilder {
    private final FileSystemSnapshotter fileSystemSnapshotter;
    private final CompilationStateCacheFactory compilationStateCacheFactory;
    private final CSourceParser sourceParser;
    private final DirectoryFileTreeFactory directoryFileTreeFactory;
    private final TaskFileVarFactory fileVarFactory;
    private final BuildOperationExecutor buildOperationExecutor;

    public DefaultIncrementalCompilerBuilder(FileSystemSnapshotter fileSystemSnapshotter, CompilationStateCacheFactory compilationStateCacheFactory, CSourceParser sourceParser, DirectoryFileTreeFactory directoryFileTreeFactory, TaskFileVarFactory fileVarFactory, BuildOperationExecutor buildOperationExecutor) {
        this.fileSystemSnapshotter = fileSystemSnapshotter;
        this.compilationStateCacheFactory = compilationStateCacheFactory;
        this.sourceParser = sourceParser;
        this.directoryFileTreeFactory = directoryFileTreeFactory;
        this.fileVarFactory = fileVarFactory;
        this.buildOperationExecutor = buildOperationExecutor;
    }

    @Override
    public IncrementalCompiler newCompiler(TaskInternal task, FileCollection sourceFiles, FileCollection includeDirs, Map<String, String> macros, Provider<Boolean> importAware) {
        return new StateCollectingIncrementalCompiler(task, includeDirs, sourceFiles, macros, fileSystemSnapshotter, compilationStateCacheFactory, sourceParser, directoryFileTreeFactory, fileVarFactory, buildOperationExecutor, importAware);
    }

    private static class StateCollectingIncrementalCompiler implements IncrementalCompiler, MinimalFileSet, LifecycleAwareTaskProperty {
        private final Map<String, String> macros;
        private final FileSystemSnapshotter fileSystemSnapshotter;
        private final CompilationStateCacheFactory compilationStateCacheFactory;
        private final CSourceParser sourceParser;
        private final DirectoryFileTreeFactory directoryFileTreeFactory;
        private final BuildOperationExecutor buildOperationExecutor;
        private final TaskOutputsInternal taskOutputs;
        private final FileCollection includeDirs;
        private final String taskPath;
        private final FileCollection sourceFiles;
        private final FileCollection headerFilesCollection;
        private final Provider<Boolean> importAware;
        private PersistentStateCache<CompilationState> compileStateCache;
        private IncrementalCompilation incrementalCompilation;

        StateCollectingIncrementalCompiler(TaskInternal task, FileCollection includeDirs, FileCollection sourceFiles, Map<String, String> macros, FileSystemSnapshotter fileSystemSnapshotter, CompilationStateCacheFactory compilationStateCacheFactory, CSourceParser sourceParser, DirectoryFileTreeFactory directoryFileTreeFactory, TaskFileVarFactory fileVarFactory, BuildOperationExecutor buildOperationExecutor, Provider<Boolean> importAware) {
            this.taskOutputs = task.getOutputs();
            this.taskPath = task.getPath();
            this.includeDirs = includeDirs;
            this.sourceFiles = sourceFiles;
            this.macros = macros;
            this.fileSystemSnapshotter = fileSystemSnapshotter;
            this.compilationStateCacheFactory = compilationStateCacheFactory;
            this.sourceParser = sourceParser;
            this.directoryFileTreeFactory = directoryFileTreeFactory;
            this.buildOperationExecutor = buildOperationExecutor;
            this.importAware = importAware;
            headerFilesCollection = fileVarFactory.newCalculatedInputFileCollection(task, this, sourceFiles, includeDirs);
        }

        @Override
        public <T extends NativeCompileSpec> Compiler<T> createCompiler(Compiler<T> compiler) {
            if (incrementalCompilation == null) {
                throw new IllegalStateException("Header files should be calculated before compiler is created.");
            }
            return new IncrementalNativeCompiler<T>(taskOutputs, compiler, compileStateCache, incrementalCompilation);
        }

        @Override
        public Set<File> getFiles() {
            List<File> includeRoots = ImmutableList.copyOf(includeDirs);
            compileStateCache = compilationStateCacheFactory.create(taskPath);
            DefaultSourceIncludesParser sourceIncludesParser = new DefaultSourceIncludesParser(sourceParser, importAware.get());
            DefaultSourceIncludesResolver dependencyParser = new DefaultSourceIncludesResolver(includeRoots, fileSystemSnapshotter);
            IncludeDirectives includeDirectives = directivesForMacros(macros);
            IncrementalCompileFilesFactory incrementalCompileFilesFactory = new IncrementalCompileFilesFactory(includeDirectives, sourceIncludesParser, dependencyParser, fileSystemSnapshotter);
            IncrementalCompileProcessor incrementalCompileProcessor = new IncrementalCompileProcessor(compileStateCache, incrementalCompileFilesFactory, buildOperationExecutor);

            incrementalCompilation = incrementalCompileProcessor.processSourceFiles(sourceFiles.getFiles());
            DefaultHeaderDependenciesCollector headerDependenciesCollector = new DefaultHeaderDependenciesCollector(directoryFileTreeFactory);
            return headerDependenciesCollector.collectExistingHeaderDependencies(taskPath, includeRoots, incrementalCompilation);
        }

        private IncludeDirectives directivesForMacros(Map<String, String> macros) {
            ImmutableList.Builder<Macro> builder = ImmutableList.builder();
            for (Map.Entry<String, String> entry : macros.entrySet()) {
                Expression expression = RegexBackedCSourceParser.parseExpression(entry.getValue());
                builder.add(new MacroWithSimpleExpression(entry.getKey(), expression.getType(), expression.getValue()));
            }
            return DefaultIncludeDirectives.of(ImmutableList.of(), builder.build(), ImmutableList.of());
        }

        @Override
        public void prepareValue() {
        }

        @Override
        public void cleanupValue() {
            compileStateCache = null;
            incrementalCompilation = null;
        }

        @Override
        public String getDisplayName() {
            return "header files for " + taskPath;
        }

        @Override
        public FileCollection getHeaderFiles() {
            return headerFilesCollection;
        }
    }
}


text:
package org.apache.streams.plugins.elasticsearch.test;

import org.apache.streams.plugins.elasticsearch.StreamsElasticsearchResourceGenerator;

import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.util.Collection;

/**
 * Test that StreamsElasticsearchResourceGeneratorCLI generates resources.
 */
public class StreamsElasticsearchResourceGeneratorCLITest {

  @Test
  public void testStreamsElasticsearchResourceGeneratorCLI() throws Exception {

    String sourceDirectory = "target/dependency/jsonschemaorg-schemas";
    String targetDirectory = "target/generated-resources/elasticsearch-cli";

    StreamsElasticsearchResourceGenerator.main(new String[]{sourceDirectory, targetDirectory});

    File testOutput = new File(targetDirectory);

    Assert.assertNotNull(testOutput);
    Assert.assertTrue(testOutput.exists());
    Assert.assertTrue(testOutput.isDirectory());

    Collection<File> outputCollection = FileUtils.listFiles(testOutput, StreamsElasticsearchResourceGeneratorTest.jsonFilter, true);
    Assert.assertEquals(4, outputCollection.size());
  }
}


text:
import * as winston from "winston";
import * as Transport from "winston-transport";

export type LogLevel =
  | "error"
  | "warn"
  | "help"
  | "data"
  | "info"
  | "debug"
  | "prompt"
  | "http"
  | "verbose"
  | "input"
  | "silly";

// Extend the Winston log methods to support error signatures
export interface LogMethod extends winston.LogMethod {
  (level: LogLevel, err: Error, ...meta: any[]): Logger;
}

export interface LeveledLogMessage extends winston.LeveledLogMethod {
  // We use empty log messages to create newlines
  (): Logger;

  // We transform Errors to strings dynamically
  (err: Error, ...meta: any[]): Logger;
}

export interface Logger {
  log: LogMethod;

  error: LeveledLogMessage;
  warn: LeveledLogMessage;
  help: LeveledLogMessage;
  data: LeveledLogMessage;
  info: LeveledLogMessage;
  debug: LeveledLogMessage;
  prompt: LeveledLogMessage;
  http: LeveledLogMessage;
  verbose: LeveledLogMessage;
  input: LeveledLogMessage;
  silly: LeveledLogMessage;

  add(transport: Transport): Logger;
  remove(transport: Transport): Logger;
}

function expandErrors(logger: winston.Logger): winston.Logger {
  const oldLogFunc: winston.LogMethod = logger.log.bind(logger);
  const newLogFunc: winston.LogMethod = function (
    levelOrEntry: string | winston.LogEntry,
    message?: string | Error,
    ...meta: any[]
  ): winston.Logger {
    if (message && message instanceof Error) {
      message = message.stack || message.message;
      return oldLogFunc(levelOrEntry as string, message, ...meta);
    }
    // Overloads are weird in TypeScript. This method works so long as the original
    // function isn't checking arguments.length.
    return oldLogFunc(levelOrEntry as string, message as string, ...meta);
  };
  logger.log = newLogFunc;
  return logger;
}

function annotateDebugLines(logger: winston.Logger): winston.Logger {
  const debug: winston.LeveledLogMethod = logger.debug.bind(logger);
  const newDebug: winston.LeveledLogMethod = function (
    message: string | any,
    ...meta: any[]
  ): winston.Logger {
    if (typeof message === "string") {
      message = `[${new Date().toISOString()}] ${message || ""}`;
    }
    return debug(message, ...meta);
  };
  logger.debug = newDebug;
  return logger;
}

const rawLogger = winston.createLogger();
// Set a default silent logger to suppress logs during tests
rawLogger.add(new winston.transports.Console({ silent: true }));
rawLogger.exitOnError = false;

// The type system for TypeScript is a bit wonky. The type of winston.LeveledLogMessage
// and winston.LogMessage is an interface of function overloads. There's no easy way to
// extend that and also subclass Logger to change the return type of those methods to
// allow error parameters.
// Casting looks super dodgy, but it should be safe because we know the underlying code
// handles all parameter types we care about.
export const logger = annotateDebugLines(expandErrors(rawLogger)) as unknown as Logger;


text:
gem uninstall wordpress_config_parser
rm wordpress_config_parser*gem
gem build wordpress_config_parser.gemspec
gem install wordpress_config_parser*gem

ruby -e "require 'wordpress_config_parser'; parser = WCParser.new('spec/resources'); puts parser.db_name; puts parser.db_name"


text:
.. This file is automatically generated. Do not edit this file directly.

Google Cloud Natural Language API Python Samples
===============================================================================

This directory contains samples for Google Cloud Natural Language API. The `Google Cloud Natural Language API`_ provides natural language understanding technologies to developers, including sentiment analysis, entity recognition, and syntax analysis. This API is part of the larger Cloud Machine Learning API.

.. _Google Cloud Natural Language API: https://cloud.google.com/natural-language/docs/

Setup
-------------------------------------------------------------------------------

Authentication
++++++++++++++

This sample requires you to have authentication setup. Refer to the
`Authentication Getting Started Guide`_ for instructions on setting up
credentials for applications.

.. _Authentication Getting Started Guide:
    https://cloud.google.com/docs/authentication/getting-started

Install Dependencies
++++++++++++++++++++

#. Install `pip`_ and `virtualenv`_ if you do not already have them.

#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+.

    .. code-block:: bash

        $ virtualenv env
        $ source env/bin/activate

#. Install the dependencies needed to run the samples.

    .. code-block:: bash

        $ pip install -r requirements.txt

.. _pip: https://pip.pypa.io/
.. _virtualenv: https://virtualenv.pypa.io/

Samples
-------------------------------------------------------------------------------

Analyze syntax
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

To run this sample:

.. code-block:: bash

    $ python analyze.py

    usage: analyze.py [-h] {entities,sentiment,syntax} text

    Analyzes text using the Google Cloud Natural Language API.

    positional arguments:
      {entities,sentiment,syntax}
      text

    optional arguments:
      -h, --help            show this help message and exit

.. _Google Cloud SDK: https://cloud.google.com/sdk/


text:
# kettil-rate-limiter

## Description

Rate limiter with redis as a backend for vertically and horizontally scalable applications.

The module counts the requests from a browser, API, or other.
When you reach a certain limit in a given period, appropriate measures can be taken.
The Module supports the clustering feature of node.js and/or it can run on multiple servers.

Supports promise [with q](https://www.npmjs.com/package/q).

### Delay-Mode

If a delay is defined, all calls are delayed, when the limit is reached.
The delay is automatically increased with each call.
If delay = 0 then the mode is disabled.

example:
```
limit: 10
delay: 1000ms
```

At the eleventh call a delay of one second occurs and the twelfth call is already delayed by two seconds,
in the thirteenth three seconds and so on...

### Express Middleware

If the option `withHeader` is true, then the response header is extended with every request.
The following header entries are added. The last entry will only be sent if the limit is exceeded.
```
res.header('X-RateLimit-Limit', limit);
res.header('X-RateLimit-Remaining', Math.max(0, remaining));
res.header('X-RateLimit-Reset', Math.ceil((Date.now() + reset) / 1000));
res.header('Retry-After', Math.ceil(reset / 1000));
```

## Requirements

- Redis 2.6.12+ (2.8 recommended)

## Install

```
$ npm install kettil-rate-limiter
```

## Usage

```
var limiter = require('kettil-rate-limiter');
var redis   = require('redis');

// limiter.create(name, options)
var rateLimiter = limiter.create('login', {
    client: redis.createClient(),
    period: 3600000, // 1 hour,
    limit:  100, // 100 requests per hour
});

// ...

// per callback
rateLimiter.exec('my-uniqid-id', function(err, limit, remaining, reset, withDelay) {
    if (err) {
        // ...
    }
    /**
     * limit     = defined limit
     * remaining = remaining attempts (less than 0, then no more attempts)
     * reset     = remaining time (in milliseconds) to reset the counter
     * withDelay = is true if a delay is defined
     */

    // ...
});

// or per promises with q ( https://www.npmjs.com/package/q )
rateLimiter.exec('my-uniqid-id').spread(function(limit, remaining, reset, withDelay) {
    // ...
}).fail(function(err) {
    // ...
});
```

### Middleware - express
```
var limiter = require('kettil-rate-limiter');
var redis   = require('redis');
var express = require('express')
var app = express()

// limiter.create(name, options)
var rateLimiter = limiter.create('login', {
    client: redis.createClient(),
    period: 3600000, // 1 hour,
    limit:  100, // 100 requests per hour
});

// rateLimiter.middleware.express(key, withHeader)
var middleware = rateLimiter.middleware.express(function(req) {
    // generate a Key or Keys (as a string, number or an array)
    var keys = [];
    keys.push('key1');
    keys.push('key2');
    return keys;
}, true)

app.get('/login', middleware, function (req, res) {
  res.send('Hello World!') // or other stuff
});
```

## Options

- `name`: Name for the distinction of multiple use (eg login, registration, etc.) (**required**)
- `options.client`: redis instance (**required**)
- `options.limit`: Number of allowed requests [default: 10]
- `options.period`: Length of period of requests (in milliseconds) [default: 60000]
- `options.delay`: Delay (in milliseconds) [default: 0]
- `options.namespace`: For the multiple use of the same redis instance [default: '']

## Test

```
npm test
```

## License
MIT


text:
<meta name="title" content="Test page">
Test page


text:
import imp
from test.test_support import TestFailed, TestSkipped
try:
    import thread
except ImportError:
    raise TestSkipped("test only valid when thread support is available")

def verify_lock_state(expected):
    if imp.lock_held() != expected:
        raise TestFailed("expected imp.lock_held() to be %r" % expected)

def testLock():
    LOOPS = 50

    # The import lock may already be held, e.g. if the test suite is run
    # via "import test.autotest".
    lock_held_at_start = imp.lock_held()
    verify_lock_state(lock_held_at_start)

    for i in range(LOOPS):
        imp.acquire_lock()
        verify_lock_state(True)

    for i in range(LOOPS):
        imp.release_lock()

    # The original state should be restored now.
    verify_lock_state(lock_held_at_start)

    if not lock_held_at_start:
        try:
            imp.release_lock()
        except RuntimeError:
            pass
        else:
            raise TestFailed("release_lock() without lock should raise "
                             "RuntimeError")

def test_main():
    testLock()

if __name__ == "__main__":
    test_main()


text:
require 'rest_client'

module LittleBits
  class CloudBit
    API_URL = 'https://api-http.littlebitscloud.cc'
    API_VERSION = 'v2'

    def initialize(access_token, device_id)
      @access_token = access_token
      @device_id = device_id
    end

    def output(percent = 100, duration_ms = 3000)
      RestClient.post "#{API_URL}/devices/#{device_id}/output",
                      {
                          :percent => percent,
                          :duration_ms => duration_ms
                      },
                      Accept: "application/vnd.littlebits.#{API_VERSION}+json",
                      Authorization: "Bearer #{access_token}"
    end

    private

    attr_reader :access_token, :device_id
  end
end


text:
static_assert(false, "Building with char8_t tests enabled, but EA_CHAR8_UNIQUE evaluates to false.");
#endif

// this mess is required inorder to inject string literal string conversion macros into the unit tests
#define TEST_STRING_NAME TestBasicStringView
#define LITERAL(x) x
#include "TestStringView.inl"

#define TEST_STRING_NAME TestBasicStringViewW
#define LITERAL(x) EA_WCHAR(x)
#include "TestStringView.inl"

#define TEST_STRING_NAME TestBasicStringView8
#define LITERAL(x) EA_CHAR8(x)
#include "TestStringView.inl"

#define TEST_STRING_NAME TestBasicStringView16
#define LITERAL(x) EA_CHAR16(x)
#include "TestStringView.inl"

#define TEST_STRING_NAME TestBasicStringView32
#define LITERAL(x) EA_CHAR32(x)
#include "TestStringView.inl"

int TestStringView()
{
	using namespace eastl;
	int nErrorCount = 0;

	nErrorCount += TestBasicStringView<eastl::basic_string_view<char>>();
	nErrorCount += TestBasicStringView<eastl::string_view>();

	nErrorCount += TestBasicStringViewW<eastl::basic_string_view<wchar_t>>();
	nErrorCount += TestBasicStringViewW<eastl::wstring_view>();

#if EA_CHAR8_UNIQUE
	nErrorCount += TestBasicStringView8<eastl::basic_string_view<char8_t>>();
	nErrorCount += TestBasicStringView8<eastl::u8string_view>();
#endif

	nErrorCount += TestBasicStringView16<eastl::basic_string_view<char16_t>>();
	nErrorCount += TestBasicStringView16<eastl::u16string_view>();

#if EA_CHAR32_NATIVE
	nErrorCount += TestBasicStringView32<eastl::basic_string_view<char32_t>>();
	nErrorCount += TestBasicStringView32<eastl::u32string_view>();
#endif

	// constexpr string_view operator "" sv(const char* str, size_t len) noexcept;
	// constexpr u8string_view operator "" sv(const char8_t* str, size_t len) noexcept;
	// constexpr u16string_view operator "" sv(const char16_t* str, size_t len) noexcept;
	// constexpr u32string_view operator "" sv(const char32_t* str, size_t len) noexcept;
	// constexpr wstring_view   operator "" sv(const wchar_t* str, size_t len) noexcept;
	#if EASTL_USER_LITERALS_ENABLED
	{
		VERIFY("cplusplus"_sv.compare("cplusplus") == 0);
		VERIFY(L"cplusplus"_sv.compare(L"cplusplus") == 0);
		VERIFY(u"cplusplus"_sv.compare(u"cplusplus") == 0);
		VERIFY(U"cplusplus"_sv.compare(U"cplusplus") == 0);
		VERIFY(u8"cplusplus"_sv.compare(u8"cplusplus") == 0);

		static_assert(eastl::is_same_v<decltype("abcdef"_sv), eastl::string_view>, "string_view literal type mismatch");
		static_assert(eastl::is_same_v<decltype(u8"abcdef"_sv), eastl::u8string_view>, "string_view literal type mismatch");
		static_assert(eastl::is_same_v<decltype(u"abcdef"_sv), eastl::u16string_view>, "string_view literal type mismatch");
		static_assert(eastl::is_same_v<decltype(U"abcdef"_sv), eastl::u32string_view>, "string_view literal type mismatch");
		static_assert(eastl::is_same_v<decltype(L"abcdef"_sv), eastl::wstring_view>, "string_view literal type mismatch");

		// TODO:  Need to resolve this.  Not sure why on Clang the user literal 'operator ""sv' can't be found.
		// VERIFY("cplusplus"sv.compare("cplusplus") == 0);
		// VERIFY(L"cplusplus"sv.compare(L"cplusplus") == 0);
		// VERIFY(u"cplusplus"sv.compare(u"cplusplus") == 0);
		// VERIFY(U"cplusplus"sv.compare(U"cplusplus") == 0);
		// VERIFY(u8"cplusplus"sv.compare(u8"cplusplus") == 0);
	}
	#endif

	// strlen(char_t) compatibility
	{
		auto* pStr = "Hello, World";
		string_view sw(pStr, strlen(pStr));
		VERIFY(sw.size() == strlen(pStr));
	}

	// strlen(wchar_t) compatibility
	{
		auto* pStr = L"Hello, World";
		wstring_view sw(pStr, wcslen(pStr));
		VERIFY(sw.size() == wcslen(pStr));
	}

	return nErrorCount;
}


text:
(function(){
    Function.prototype.debounce = function debounce(delay) {
        var timer = null, fn = this;
        return function () {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        };
    };
    Function.prototype.throttle = function throttle(threshhold, scope) {
        threshhold || (threshhold = 250);
        var last,
            deferTimer,
            fn = this,
            hasThresholdNotExpired = function(){
                if(last){
                    return new Date() < last + threshhold;
                }
                return false;
            };
        return function () {
            var context = scope || this;
            var now = new Date(),
                args = arguments;
            if (hasThresholdNotExpired()) {
                // hold on to it
                clearTimeout(deferTimer);
                deferTimer = setTimeout(function () {
                    last = now;
                    fn.apply(context, args);
                }, threshhold);
            } else {
                last = now;
                fn.apply(context, args);
            }
        };
    }

}());


text:
from django.contrib.auth import models as auth_models
from infrastructure import views

from . import serializers, filters

class UsersViewSet(views.IndividuallyGuardedModelViewSet):
    queryset = auth_models.User.objects.all()
    serializer_class = serializers.UserSerializer
    filter_class = filters.UserFilter

class GroupsViewSet(views.GuardedModelViewSet):
    queryset = auth_models.Group.objects.all()
    serializer_class = serializers.GroupSerializer
    filter_class = filters.GroupFilter

class PermissionsViewSet(views.GuardedModelViewSet):
    queryset = auth_models.Permission.objects.all()
    serializer_class = serializers.PermissionSerializer
    filter_class = filters.PermissionFilter


text:
import operator

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from model.attachment import Attachment
from model.workitems import WorkItems
from model.queues import Queue

class StatusBubble(webapp.RequestHandler):
    _queues_to_display = [queue for queue in Queue.all() if queue.is_ews()]

    def _build_bubble(self, queue, attachment):
        queue_status = attachment.status_for_queue(queue)
        bubble = {
            "name": queue.short_name().lower(),
            "attachment_id": attachment.id,
            "queue_position": attachment.position_in_queue(queue),
            "state": attachment.state_from_queue_status(queue_status) if queue_status else "none",
            "status": queue_status,
        }
        return bubble

    def get(self, attachment_id):
        attachment = Attachment(int(attachment_id))
        bubbles = [self._build_bubble(queue, attachment) for queue in self._queues_to_display]
        template_values = {
            "bubbles": bubbles,
        }
        self.response.out.write(template.render("templates/statusbubble.html", template_values))


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

<TITLE>
MappingGraphLink
</TITLE>

<META NAME="date" CONTENT="2012-04-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cbiit.cmts.ui.jgraph

Class MappingGraphLink

java.lang.Object
  javax.swing.tree.DefaultMutableTreeNode
      org.jgraph.graph.DefaultGraphCell
          org.jgraph.graph.DefaultEdge
              gov.nih.nci.cbiit.cmts.ui.jgraph.MappingGraphLink

All Implemented Interfaces:
PropertiesProvider, java.io.Serializable, java.lang.Cloneable, javax.swing.tree.MutableTreeNode, javax.swing.tree.TreeNode, org.jgraph.graph.Edge, org.jgraph.graph.GraphCell

public class MappingGraphLink
extends org.jgraph.graph.DefaultEdge
implements java.io.Serializable, PropertiesProvider

See Also:
Serialized Form

Nested Class Summary

Nested classes/interfaces inherited from class org.jgraph.graph.DefaultEdge

org.jgraph.graph.DefaultEdge.DefaultRouting, org.jgraph.graph.DefaultEdge.LoopRouting

Nested classes/interfaces inherited from interface org.jgraph.graph.Edge

org.jgraph.graph.Edge.Routing

Field Summary

Fields inherited from class org.jgraph.graph.DefaultEdge

source, target

Fields inherited from class org.jgraph.graph.DefaultGraphCell

attributes

Fields inherited from class javax.swing.tree.DefaultMutableTreeNode

allowsChildren, children, EMPTY_ENUMERATION, parent, userObject

Constructor Summary

MappingGraphLink()

Method Summary

 PropertiesResult
getPropertyDescriptors()

          This functions will return an array of PropertyDescriptor that would
 help reflection and/or introspection to figure out what information would be
 presented to the user.

 java.lang.String
getSourceNameProperty()

 java.lang.String
getSourcParentProperty()

 java.lang.String
getTargetNameProperty()

 java.lang.String
getTargetParentProperty()

 java.lang.String
getTitle()

          Return the title of this provider that may be used to distinguish from others.

Methods inherited from class org.jgraph.graph.DefaultEdge

clone, getSource, getTarget, setSource, setTarget

Methods inherited from class org.jgraph.graph.DefaultGraphCell

addPort, addPort, addPort, changeAttributes, getAttributes, getChildren, setAttributes

Methods inherited from class javax.swing.tree.DefaultMutableTreeNode

add, breadthFirstEnumeration, children, depthFirstEnumeration, getAllowsChildren, getChildAfter, getChildAt, getChildBefore, getChildCount, getDepth, getFirstChild, getFirstLeaf, getIndex, getLastChild, getLastLeaf, getLeafCount, getLevel, getNextLeaf, getNextNode, getNextSibling, getParent, getPath, getPathToRoot, getPreviousLeaf, getPreviousNode, getPreviousSibling, getRoot, getSharedAncestor, getSiblingCount, getUserObject, getUserObjectPath, insert, isLeaf, isNodeAncestor, isNodeChild, isNodeDescendant, isNodeRelated, isNodeSibling, isRoot, pathFromAncestorEnumeration, postorderEnumeration, preorderEnumeration, remove, remove, removeAllChildren, removeFromParent, setAllowsChildren, setParent, setUserObject, toString

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface org.jgraph.graph.GraphCell

changeAttributes, getAttributes, setAttributes

Constructor Detail

MappingGraphLink

public MappingGraphLink()

Method Detail

getPropertyDescriptors

public PropertiesResult getPropertyDescriptors()
                                        throws java.lang.Exception

Description copied from interface: PropertiesProvider

This functions will return an array of PropertyDescriptor that would
 help reflection and/or introspection to figure out what information would be
 presented to the user.

Specified by:
getPropertyDescriptors in interface PropertiesProvider

Throws:

java.lang.Exception

getSourcParentProperty

public java.lang.String getSourcParentProperty()

getSourceNameProperty

public java.lang.String getSourceNameProperty()

getTargetParentProperty

public java.lang.String getTargetParentProperty()

getTargetNameProperty

public java.lang.String getTargetNameProperty()

getTitle

public java.lang.String getTitle()

Description copied from interface: PropertiesProvider

Return the title of this provider that may be used to distinguish from others.

Specified by:
getTitle in interface PropertiesProvider

Returns:
the title of this provider that may be used to distinguish from others.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
require 'minitest_helper'

module SlideHero
  describe Note do
    it "Properly wraps notes" do
      note = Note.new("Remind them of this")
      assert_equal(note.compile, "<aside class=\"notes\">Remind them of this</aside>")
    end
  end
end


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

#include <zcl/freelist.h>

/* ===========================================================================
 *  PRIVATE Free-List data structures
 */
struct z_free_list_node {
  z_free_list_node_t *next;
  size_t size;
};

/* ===========================================================================
 *  PUBLIC Free-List methods
 */
void z_free_list_add (z_free_list_t *self, void *memory) {
  z_free_list_node_t *node = Z_FREE_LIST_NODE(memory);
  node->next = self->head;
  self->head = node;
}

void z_free_list_add_sized (z_free_list_t *self, void *memory, size_t size) {
  z_free_list_node_t *node = Z_FREE_LIST_NODE(memory);
  node->next = self->head;
  node->size = size;
  self->head = node;
}

void *z_free_list_pop (z_free_list_t *self) {
  z_free_list_node_t *node = self->head;
  if (node != NULL)
    self->head = node->next;
  return(node);
}

void *z_free_list_pop_fit (z_free_list_t *self, size_t required, size_t *size) {
  z_free_list_node_t *prev = self->head;
  z_free_list_node_t *node = self->head;

  while (node != NULL) {
    if (node->size >= required) {
      prev->next = node->next;
      *size = node->size;
      return(node);
    }

    prev = node;
    node = node->next;
  }

  return(NULL);
}

void *z_free_list_pop_best (z_free_list_t *self, size_t required, size_t *size)
{
  z_free_list_node_t *prev = self->head;
  z_free_list_node_t *node = self->head;
  z_free_list_node_t *best_prev = NULL;
  z_free_list_node_t *best = NULL;

  while (node != NULL) {
    if (node->size == required) {
      prev->next = node->next;
      *size = node->size;
      return(node);
    }

    if (node->size > required && best == NULL) {
      best_prev = node;
      best = node;
    }

    prev = node;
    node = node->next;
  }

  if (best != NULL) {
    best_prev->next = best->next;
    *size = best->size;
    return(best);
  }

  return(NULL);
}


text:
typedef enum : NSUInteger {
    setFeedBack = 0,
    setQuestion,
    setServiceDelegate,
    setNewHand,
    setAbout,
} setEnum;

@interface XRPersonSettingViewController ()

@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) NSDictionary * dic;
@property (nonatomic, strong) BackGrayView * grayView;

@end

@implementation XRPersonSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.contentInset = UIEdgeInsetsMake(-36, 0, 0, 0);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 ){
        if (indexPath.row == 0) {
            self.selectIndex = setFeedBack;
            [self performSegueWithIdentifier:@"settingDetail" sender:self];
        }else if (indexPath.row == 1){
            self.selectIndex = setQuestion;
            [self performSegueWithIdentifier:@"settingDetail" sender:self];
        }else if(indexPath.row == 2){
            [self.network postWithParameter:@{} method:queryServiceInfo isHud:YES];
        }else if (indexPath.row == 3){
            self.selectIndex = setServiceDelegate;
            [self performSegueWithIdentifier:@"settingDetail" sender:self];
        }else if (indexPath.row == 4){
            self.selectIndex = setNewHand;
            [self performSegueWithIdentifier:@"settingDetail" sender:self];
        }else if (indexPath.row == 5) {
            self.selectIndex = setAbout;
            [self performSegueWithIdentifier:@"settingDetail" sender:self];
        }
    }else if (indexPath.section == 1) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:COOKIE];
        BOOL result = [RootVCHandle deleteCacheImage];
        NSLog(result ? @"删除头像成功" : @"删除头像失败");
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"nickName"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_ID];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"address"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"area"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"receiveName"];
        [ResponseModel showInfoWithString:@"退出登录成功!"];
        [self login];
    }
}

- (void)complainButtonMethod
{
    self.grayView = [[BackGrayView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT + 64)];
    [[[UIApplication sharedApplication].delegate window] addSubview:_grayView];
    [_grayView.phoneButton setTitle:self.dic[@"serviceTel"] forState:UIControlStateNormal];
    [_grayView.qqButton setTitle:self.dic[@"serviceQQ"] forState:UIControlStateNormal];
    [_grayView.phoneButton addTarget:self action:@selector(callExpressMethod:) forControlEvents:UIControlEventTouchUpInside];
    // 未完待续
    [_grayView.qqButton addTarget:self action:@selector(callQQMethod) forControlEvents:UIControlEventTouchUpInside];
}

- (void)callQQMethod
{
    UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString * str = [NSString stringWithFormat:@"http://wpa.qq.com/msgrd?v=3&uin=%@&site=qq&menu=yes", self.dic[@"serviceQQ"]];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:webView];
}

- (void)callExpressMethod:(UIButton *)btn
{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",self.dic[@"serviceTel"]];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"settingDetail"]) {
        WebViewController * webVC = [segue destinationViewController];
        if (self.selectIndex == setFeedBack) {
            webVC.url = feedback;

            webVC.title = @"反馈与建议";
        }else if (self.selectIndex == setQuestion){
            webVC.url = question;
            webVC.title = @"常见问题";
        }else if(self.selectIndex == setServiceDelegate){
            webVC.url = serviceAgreement;
            webVC.title = @"服务协议";
        }else if(self.selectIndex == setNewHand){
            webVC.url = userGuide;
            webVC.title = @"新手指南";
        }else if(self.selectIndex == setAbout){
            webVC.url = aboutUs;
            webVC.title = @"关于";
        }

    }
}

#pragma mark - BaseNetWorkModelDelegate
- (void)successfulWithDic:(NSDictionary *)dic method:(NSString *)method
{
    if ([self isPostSuccessedWithDic:dic]) {
        self.dic = dic[DIC_DATA];
        [self complainButtonMethod];
    }
}

@end


text:
/**
 * @class featuredCarousel
 * @memberOf lapps.lappsDirectives
 * @description This directive is a template for the carousel displayed on the
 *              welcome page.
 */
(function() {
  angular.module('lappsDirectives').directive('featuredCarousel', function() {
    return {
      scope: true,
      restrict: 'E',
      templateUrl: 'components/featuredCarousel/featuredCarouselView.html',
      controller: 'featuredCarouselCtr'
    };
  });
}).call(this);


text:
/* derivative work from https://github.com/yahoo/pure. Licence: see http://purecss.io/start/ */
.pure-table {
    /* Remove spacing between table cells (from Normalize.css) */
    border-collapse: collapse;
    border-spacing: 0;
    empty-cells: show;
    border: 1px solid red;
}

.pure-table td,
.pure-table th {
    border-left: 1px solid #cbcbcb;/*  inner column border */
    border-right: 1px solid #cbcbcb;/*  inner column border */
    border-width: 1px 1px 1px 1px;
    font-size: inherit;
    margin: 0;
    text-align: left;
    vertical-align: top;
    padding: 0.5em 1em; /* cell padding */
}

.pure-table th{
    max-width: 40em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.pure-table  td>ul>li {
    max-width: 40em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.pure-table thead {
    background-color: #e0e0e0;
    color: #000;
    text-align: left;
    vertical-align: top;
}

.pure-table-odd td {
    background-color: #f2f2f2;
}

/* nth-child selector for modern browsers */
.pure-table tr:nth-child(2n-1) td {
    background-color: #f2f2f2;
}


text:
def test_incorrect_post_redirect(webtest):
    """
    Per issue #8104, we should issue an HTTP-308 for a POST
    in /legacy and point the user to the correct endpoint,
    /legacy/

    See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
    """
    resp = webtest.post("/legacy", status=308)
    assert resp.status == (
        "308 An upload was attempted to /legacy but the expected upload URL is "
        "/legacy/ (with a trailing slash)"
    )

    assert "location" in resp.headers
    assert resp.headers["location"] == "http://localhost/legacy/"


text:
require 'spec_helper'

describe 'mcollective::user::setting' do
  let :facts do
    {
      puppetversion: Puppet.version,
      facterversion: Facter.version,
      macaddress: '00:00:00:26:28:8a',
      osfamily: 'RedHat',
      operatingsystem: 'CentOS',
      mco_version: '2.8.4',
      path: ['/usr/bin', '/usr/sbin']
    }
  end
  context 'nagios:some_setting' do
    let(:title) { 'nagios:some_setting' }
    let(:params) { { 'username' => 'nagios', 'value' => 'pie', :setting => 'some_setting' } }
    it { is_expected.to contain_mcollective__setting('mcollective::user::setting nagios:some_setting') }
    it { is_expected.to contain_mcollective__setting('mcollective::user::setting nagios:some_setting').with_setting('some_setting') }
    it { is_expected.to contain_mcollective__setting('mcollective::user::setting nagios:some_setting').with_value('pie') }
    it { is_expected.to contain_mcollective__setting('mcollective::user::setting nagios:some_setting').with_target('mcollective::user nagios') }
  end
end


text:
using System;

namespace Ns.Common.Filters
{
    public class CharSequenceFilter : BaseStringFilter
    {
        private readonly string _pattern;

        public CharSequenceFilter(string pattern)
        {
            if (pattern == null)
                throw new ArgumentNullException(nameof(pattern));

            _pattern = pattern;
        }

        protected override bool IsMatch(string value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            return _pattern.Equals(value, StringComparison.OrdinalIgnoreCase);
        }
    }
}


text:
from __future__ import absolute_import
from __future__ import unicode_literals

from hal.library import HalLibrary

import unittest

class HalLibTest(unittest.TestCase):
    """
    Base class for testing hal libraries
    """

    def assert_successful_response(self, command):
        a = self.lib(command)
        a.process_input()
        self.assertEqual(a.status, HalLibrary.SUCCESS)

    def assert_failure_response(self, command):
        a = self.lib(command)
        a.process_input()
        self.assertEqual(a.status, HalLibrary.FAILURE)

    def assert_error_response(self, command, message=None):
        a = self.lib(command)
        a.process_input()
        self.assertEqual(a.status, HalLibrary.ERROR)
        if message:
            self.assertEqual(a.get_error(), message)

    def assert_in_response(self, command, string):
        a = self.lib(command)
        a.process_input()
        a.process()

        for s in a.get_response():
            if string.lower() in s.lower():
                return
        raise Exception(string," not in ", a.get_response())

    def assert_response_count(self, command, count):
        a = self.lib(command)
        a.process_input()
        a.process()
        self.assertEqual(count,len(a.get_response()))


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <title>Adivina Cuántos - 88th Oscars Edition</title>
        <link href='https://fonts.googleapis.com/css?family=Indie+Flower|Roboto+Slab:700' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="css/estilos.css"/>

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        Menú Hamburguesa

                    </button>
                    Adivina Cuántos

Qué es

Premio

Normas

 Facebook

 Twitter

 Dudas - Sugerencias

¿Sabes mucho de cine?

Demuéstralo.

Dejanos tu e-mail y te avisamos cuando esté listo el concurso.

                      <input type="text" name="email" id="txtEmail" class="form-control" placeholder="Introduce tu e-mail...">

                        <button class="btn btn-primary" type="button" onclick="enviarEmail()">
                            Enviar
                        </button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

                    ...

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

                    ...

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

                    ...

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>


text:
import React, {Component} from 'react';

import './Chrome.css';

export default class Chrome extends Component {
  render() {
    const assets = this.props.assets;
    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <link rel="shortcut icon" href="favicon.ico" />
          <link rel="stylesheet" href={assets['main.css']} />
          <title>{this.props.title}</title>
        </head>
        <body>
          {this.props.children}
          <script
            dangerouslySetInnerHTML={{
              __html: `assetManifest = ${JSON.stringify(assets)};`,
            }}
          />
          <script src={assets['main.js']} />
        </body>
      </html>
    );
  }
}


text:
package ca.cmput301f13t03.adventure_datetime.model;

import android.test.AndroidTestCase;

import java.util.List;

public class WebStorageCleaner extends AndroidTestCase {

	WebStorage es;

	protected void setUp() throws Exception {
		super.setUp();
		es = new WebStorage();
		es.setIndex("testing");
	}

	public void testCleanUp() throws Exception {
		List<Story> stories = es.getStories(0, 10);

		for (Story s : stories) {
			es.deleteStory(s.getId());
		}
	}

}


text:
"""
Reduced models for segmenting with less memory overhead
"""
from __future__ import unicode_literals

import collections
import logging
import math
import random
import re
import sys

from .categorizationscheme import ByCategory, get_categories, CategorizedMorph
from .categorizationscheme import MorphUsageProperties
from .flatcat import AbstractSegmenter, FlatcatAnnotatedCorpusEncoding
from .utils import LOGPROB_ZERO, zlog

_logger = logging.getLogger(__name__)

class FlatcatSegmenter(AbstractSegmenter):
    def __init__(self, model):
        self._corpus_coding = ReducedEncoding(
            model._corpus_coding, model._morph_usage)
        super(FlatcatSegmenter, self).__init__(self._corpus_coding,
                                               model.nosplit_re)
        self._segment_only = True
        self._initialized = True
        self._corpus_tagging_level = 'full'

        if model.annotations is None:
            self.annotations = None
        else:
            self._supervised = True
            self.annotations = model.annotations
            self._annotations_tagged = True
            for (word, annot) in self.annotations.items():
                if annot.alternatives[0][0].category is None:
                    self._annotations_tagged = False
            self._annot_coding = model._annot_coding
        self._num_compounds = model.num_compounds
        self._num_constructions = model.num_constructions
        self._all_chars = dict(model._lexicon_coding.atoms)

    def __contains__(self, morph):
        return morph in self._corpus_coding._log_emissionprob_cache

    def __setstate__(self, d):
        """Temporary hack to allow loading old reduced models"""
        self.__dict__ = d
        self._initialized = True
        self._corpus_tagging_level = 'full'
        if 'forcesplit' not in self.__dict__:
            self.forcesplit = [':', '-']

    @property
    def num_compounds(self):
        """Compound (word) types"""
        return self._num_compounds

    @property
    def num_constructions(self):
        """Construction (morph) types"""
        return self._num_constructions

class ReducedEncoding(object):
    """Reduced variant of FlatcatEncoding """

    def __init__(self, corpus_encoding, morph_usage):
        # Transition and emission logprobs,
        # The reduced model only stores these
        self._log_transitionprob_cache = self._populate_transitions(
            corpus_encoding)
        self._log_emissionprob_cache = self._populate_emissions(
            corpus_encoding, morph_usage)

        self.weight = corpus_encoding.weight
        self.cost = corpus_encoding.get_cost()
        self.boundaries = corpus_encoding.boundaries

    # Transition count methods

    def _populate_transitions(self, corpus_encoding):
        out = {}
        categories = get_categories(wb=True)
        for prev_cat in categories:
            for next_cat in categories:
                out[(prev_cat, next_cat)] = (
                    corpus_encoding.log_transitionprob(prev_cat, next_cat))
        return out

    def _populate_emissions(self, corpus_encoding, morph_usage):
        out = {}
        categories = get_categories(wb=False)
        for morph in morph_usage.seen_morphs():
            out[morph] = ByCategory(
                *[corpus_encoding.log_emissionprob(cat, morph)
                  for cat in categories])
            corpus_encoding.clear_emission_cache()
        return out

    def log_transitionprob(self, prev_cat, next_cat):
        """-Log of transition probability P(next_cat|prev_cat)"""
        pair = (prev_cat, next_cat)
        return self._log_transitionprob_cache[pair]

    def log_emissionprob(self, category, morph, extrazero=False):
        """-Log of posterior emission probability P(morph|category)"""
        categories = get_categories(wb=False)
        if morph not in self._log_emissionprob_cache:
            # The morph is not present in this reduced model
            return LOGPROB_ZERO
        tmp = self._log_emissionprob_cache[morph][categories.index(category)]
        if extrazero and tmp >= LOGPROB_ZERO:
            return tmp ** 2
        return tmp

    def transit_emit_cost(self, prev_cat, next_cat, morph):
        """Cost of transitioning from prev_cat to next_cat and emitting
        the morph."""
        if (prev_cat, next_cat) in MorphUsageProperties.zero_transitions:
            return LOGPROB_ZERO
        return (self.log_transitionprob(prev_cat, next_cat) +
                self.log_emissionprob(next_cat, morph))

    def get_cost(self):
        """
        This is P( D_W | theta, Y )
        """
        return self.cost


text:
					{{ vm.project.name }}
Public Comment Period

Location
{{ vm.project.location }}

Description

{{ vm.project.description | maxWords:5:toggleProject.desc }}

					 5">

							More ({{ vm.project.description | wordCount }} words)
							Less

Application Main Report

 Document Name

Hide Application Files

View Application Files

Application Appendices

				<map center="{{ vm.project.lat }},{{ vm.project.lon }}" zoom="10" map-type-id="ROADMAP" street-view-control='false' min-zoom=10 max-zoom=10 disable-default-u-i="true">
					<kml-layer url="{{ vm.host }}/map_layers/Ajax_2016Jan7data_Footprint_25Buffer_filled.kml"></kml-layer>
				</map>

				Comment Volume by Date
				<tmpl-public-project-comments-circle-chart ng-if="vm.commentsByDateVis" x-refresh="vm.refreshVisualization" x-data="vm.commentsByDateVis" id="publicCommentsByDate"></tmpl-public-project-comments-circle-chart>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<title>OpenCV: Robust Estimation</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>

OpenCV
    3.2.0

Open Source Computer Vision

Functions

Robust Estimation
Structure From Motion

Functions

double 	cv::sfm::fundamentalFromCorrespondences7PointRobust (InputArray x1, InputArray x2, double max_error, OutputArray F, OutputArray inliers, double outliers_probability=1e-2)

 	Estimate robustly the fundamental matrix between two dataset of 2D point (image coords space).  More...

double 	cv::sfm::fundamentalFromCorrespondences8PointRobust (InputArray x1, InputArray x2, double max_error, OutputArray F, OutputArray inliers, double outliers_probability=1e-2)

 	Estimate robustly the fundamental matrix between two dataset of 2D point (image coords space).  More...

Detailed Description

Function Documentation

§ fundamentalFromCorrespondences7PointRobust()

          double cv::sfm::fundamentalFromCorrespondences7PointRobust
          (
          InputArray
          x1,

          InputArray
          x2,

          double
          max_error,

          OutputArray
          F,

          OutputArray
          inliers,

          double
          outliers_probability = 1e-2

          )

Estimate robustly the fundamental matrix between two dataset of 2D point (image coords space).

Parameters

x1	Input 2xN Array of 2D points in view 1.

x2	Input 2xN Array of 2D points in view 2.

max_error	maximum error (in pixels).

F	Output 3x3 fundamental matrix such that \(x_2^T F x_1=0\).

inliers	Output 1xN vector that contains the indexes of the detected inliers.

outliers_probability	outliers probability (in ]0,1[). The number of iterations is controlled using the following equation: \(k = \frac{log(1-p)}{log(1.0 - w^n )}\) where \(k\), \(w\) and \(n\) are the number of iterations, the inliers ratio and minimun number of selected independent samples. The more this value is high, the less the function selects ramdom samples.

The fundamental solver relies on the 7 point solution. Returns the best error (in pixels), associated to the solution F.

§ fundamentalFromCorrespondences8PointRobust()

          double cv::sfm::fundamentalFromCorrespondences8PointRobust
          (
          InputArray
          x1,

          InputArray
          x2,

          double
          max_error,

          OutputArray
          F,

          OutputArray
          inliers,

          double
          outliers_probability = 1e-2

          )

Estimate robustly the fundamental matrix between two dataset of 2D point (image coords space).

Parameters

x1	Input 2xN Array of 2D points in view 1.

x2	Input 2xN Array of 2D points in view 2.

max_error	maximum error (in pixels).

F	Output 3x3 fundamental matrix such that \(x_2^T F x_1=0\).

inliers	Output 1xN vector that contains the indexes of the detected inliers.

outliers_probability	outliers probability (in ]0,1[). The number of iterations is controlled using the following equation: \(k = \frac{log(1-p)}{log(1.0 - w^n )}\) where \(k\), \(w\) and \(n\) are the number of iterations, the inliers ratio and minimun number of selected independent samples. The more this value is high, the less the function selects ramdom samples.

The fundamental solver relies on the 8 point solution. Returns the best error (in pixels), associated to the solution F.

<address class="footer">
Generated on Fri Dec 23 2016 13:00:26 for OpenCV by

 1.8.12
</address>


text:
if [ "${EE}" = "true" ]; then
    echo "Downloading Camunda ${VERSION} Enterprise Edition for ${DISTRO}"
    REPO="private"
    NEXUS_GROUP="private"
    ARTIFACT="camunda-bpm-ee-${DISTRO}"
    if [ "${DISTRO}" = "run" ]; then
      ARTIFACT="camunda-bpm-run-ee"
    fi
    ARTIFACT_VERSION="${VERSION}-ee"
else
    echo "Downloading Camunda ${VERSION} Community Edition for ${DISTRO}"
    REPO="camunda-bpm"
    NEXUS_GROUP="public"
    ARTIFACT="camunda-bpm-${DISTRO}"
    ARTIFACT_VERSION="${VERSION}"
fi

# Determine if SNAPSHOT repo and version should be used
if [ ${SNAPSHOT} = "true" ]; then
    # CE artefacts are public, EE require forced authentication via virtual repository (private)
    # preemptively sending them in settings.xml would fail CE builds
    if [ "${EE}" = "false" ]; then
        REPO="${REPO}-snapshots"
    fi
    ARTIFACT_VERSION="${VERSION}-SNAPSHOT"
fi

# Determine artifact group, all wildfly version have the same group
case ${DISTRO} in
    wildfly*) GROUP="wildfly" ;;
    *) GROUP="${DISTRO}" ;;
esac
ARTIFACT_GROUP="org.camunda.bpm.${GROUP}"

# Download distro from nexus

PROXY=""
if [ -n "$MAVEN_PROXY_HOST" ] ; then
	PROXY="-DproxySet=true"
	PROXY="$PROXY -Dhttp.proxyHost=$MAVEN_PROXY_HOST"
	PROXY="$PROXY -Dhttps.proxyHost=$MAVEN_PROXY_HOST"
	if [ -z "$MAVEN_PROXY_PORT" ] ; then
		echo "ERROR: MAVEN_PROXY_PORT must be set when MAVEN_PROXY_HOST is set"
		exit 1
	fi
	PROXY="$PROXY -Dhttp.proxyPort=$MAVEN_PROXY_PORT"
	PROXY="$PROXY -Dhttps.proxyPort=$MAVEN_PROXY_PORT"
	echo "PROXY set Maven proxyHost and proxyPort"
	if [ -n "$MAVEN_PROXY_USER" ] ; then
		PROXY="$PROXY -Dhttp.proxyUser=$MAVEN_PROXY_USER"
		PROXY="$PROXY -Dhttps.proxyUser=$MAVEN_PROXY_USER"
		echo "PROXY set Maven proxyUser"
	fi
	if [ -n  "$MAVEN_PROXY_PASSWORD" ] ; then
		PROXY="$PROXY -Dhttp.proxyPassword=$MAVEN_PROXY_PASSWORD"
		PROXY="$PROXY -Dhttps.proxyPassword=$MAVEN_PROXY_PASSWORD"
		echo "PROXY set Maven proxyPassword"
	fi
fi

mvn dependency:get -U -B --global-settings /tmp/settings.xml \
    $PROXY \
    -DremoteRepositories="camunda-nexus::::https://artifacts.camunda.com/artifactory/${REPO}/" \
    -DgroupId="${ARTIFACT_GROUP}" -DartifactId="${ARTIFACT}" \
    -Dversion="${ARTIFACT_VERSION}" -Dpackaging="tar.gz" -Dtransitive=false
cambpm_distro_file=$(find /m2-repository -name "${ARTIFACT}-${ARTIFACT_VERSION}.tar.gz" -print | head -n 1)
# Unpack distro to /camunda directory
mkdir -p /camunda
case ${DISTRO} in
    run*) tar xzf "$cambpm_distro_file" -C /camunda;;
    *)    tar xzf "$cambpm_distro_file" -C /camunda server --strip 2;;
esac
cp /tmp/camunda-${GROUP}.sh /camunda/camunda.sh

# download and register database drivers
mvn dependency:get -U -B --global-settings /tmp/settings.xml \
    $PROXY \
    -DremoteRepositories="camunda-nexus::::https://artifacts.camunda.com/artifactory/${NEXUS_GROUP}/" \
    -DgroupId="org.camunda.bpm" -DartifactId="camunda-database-settings" \
    -Dversion="${ARTIFACT_VERSION}" -Dpackaging="pom" -Dtransitive=false
cambpmdbsettings_pom_file=$(find /m2-repository -name "camunda-database-settings-${ARTIFACT_VERSION}.pom" -print | head -n 1)
MYSQL_VERSION=$(xmlstarlet sel -t -v //_:version.mysql $cambpmdbsettings_pom_file)
POSTGRESQL_VERSION=$(xmlstarlet sel -t -v //_:version.postgresql $cambpmdbsettings_pom_file)

mvn dependency:copy -B \
    $PROXY \
    -Dartifact="mysql:mysql-connector-java:${MYSQL_VERSION}:jar" \
    -DoutputDirectory=/tmp/
mvn dependency:copy -B \
    $PROXY \
    -Dartifact="org.postgresql:postgresql:${POSTGRESQL_VERSION}:jar" \
    -DoutputDirectory=/tmp/

case ${DISTRO} in
    wildfly*)
        cat <<-EOF > batch.cli
batch
embed-server --std-out=echo

module add --name=mysql.mysql-connector-java --slot=main --resources=/tmp/mysql-connector-java-${MYSQL_VERSION}.jar --dependencies=javax.api,javax.transaction.api
/subsystem=datasources/jdbc-driver=mysql:add(driver-name="mysql",driver-module-name="mysql.mysql-connector-java",driver-xa-datasource-class-name=com.mysql.cj.jdbc.MysqlXADataSource)

module add --name=org.postgresql.postgresql --slot=main --resources=/tmp/postgresql-${POSTGRESQL_VERSION}.jar --dependencies=javax.api,javax.transaction.api
/subsystem=datasources/jdbc-driver=postgresql:add(driver-name="postgresql",driver-module-name="org.postgresql.postgresql",driver-xa-datasource-class-name=org.postgresql.xa.PGXADataSource)

run-batch
EOF
        /camunda/bin/jboss-cli.sh --file=batch.cli
        rm -rf /camunda/standalone/configuration/standalone_xml_history/current/*
        ;;
    run*)
        cp /tmp/mysql-connector-java-${MYSQL_VERSION}.jar /camunda/configuration/userlib
        cp /tmp/postgresql-${POSTGRESQL_VERSION}.jar /camunda/configuration/userlib
        ;;
    tomcat*)
        cp /tmp/mysql-connector-java-${MYSQL_VERSION}.jar /camunda/lib
        cp /tmp/postgresql-${POSTGRESQL_VERSION}.jar /camunda/lib
        # remove default CATALINA_OPTS from environment settings
        echo "" > /camunda/bin/setenv.sh
        ;;
esac

# download Prometheus JMX Exporter.
# Details on https://blog.camunda.com/post/2019/06/camunda-bpm-on-kubernetes/
mvn dependency:copy -B \
    $PROXY \
    -Dartifact="io.prometheus.jmx:jmx_prometheus_javaagent:${JMX_PROMETHEUS_VERSION}:jar" \
    -DoutputDirectory=/tmp/

mkdir -p /camunda/javaagent
cp /tmp/jmx_prometheus_javaagent-${JMX_PROMETHEUS_VERSION}.jar /camunda/javaagent/jmx_prometheus_javaagent.jar


text:
# ifndef DIPOLE_H
# define DIPOLE_H

# include "PDForces_BaseClass.hpp"

/*
   This is an implementation of the 'PDForces_BaseClass' base class.
   It calculates an inter-particle force based on the Dipole contact model.
   */

class Dipole : public PDForces_BaseClass {

    // -------------------------------------------------------------------------
    // Private class members:
    // -------------------------------------------------------------------------

    private:

        double eps,n;
        double Ex,Ey,Ez;
        double eqEx,eqEy,eqEz;
        double edir[3];
        double Emag;
        double radComp;
        double avgRad;
        double theta;
        double thetaComp;
        double EdotRij;
        double ScaleFactor;
        double normal[3];
        double thetaHat[3];
        double thetaMag;
        double rij[3];
        double rijMag;
        double rij2;
        double pradii;
        double rcut,rcut2;
        double box[3];
        bool thinFilm;
        vector<double>& r;
        vector<double>& v;
        vector<double>& f;
        vector<double>& rad;

    public:

        // -------------------------------------------------------------------------
        // Public class methods:
        // -------------------------------------------------------------------------

    public:

        Dipole(const GetPot&, vector<double>&,
                vector<double>&,
                vector<double>&,
                vector<double>&);
        ~Dipole();
        void fijFunc(int,int);
        void cross(double (&a)[3], double(&b)[3],double (&crs)[3]);
        void equilOn();
        void equilOff();

};

# endif  // DIPOLE_H