text:
namespace dux {

Value::Value(Type type) : type_(type) {
  switch (type_) {
    case Type::NONE:
      return;
    case Type::BOOLEAN:
      bool_value_ = false;
      return;
    case Type::INT64:
      int64_value_ = 0;
      return;
    case Type::STRING:
      new (&string_value_) std::string();
      return;
    case Type::DICTIONARY:
      new (&dictionary_) DictionaryStorage();
      return;
    case Type::LIST:
      new (&list_) ListStorage();
      return;
  }
}

Value::Value(bool in_bool) : type_(Type::BOOLEAN), bool_value_(in_bool) {}

Value::Value(int32_t in_int) : type_(Type::INT64), int64_value_(in_int) {}

Value::Value(int64_t in_int) : type_(Type::INT64), int64_value_(in_int) {}

Value::Value(std::string const& in_string)
    : type_(Type::STRING), string_value_(in_string) {}

Value::Value(char const* in_string)
    : type_(Type::STRING), string_value_(in_string) {}

Value::Value(Value&& other) noexcept {
  type_ = other.type_;

  switch (type_) {
    case Type::NONE:
      return;
    case Type::BOOLEAN:
      bool_value_ = other.bool_value_;
      return;
    case Type::INT64:
      int64_value_ = other.int64_value_;
      return;
    case Type::STRING:
      new (&string_value_) std::string(std::move(other.string_value_));
      return;
    case Type::DICTIONARY:
      new (&dictionary_) DictionaryStorage(std::move(other.dictionary_));
      return;
    case Type::LIST:
      new (&list_) ListStorage(std::move(other.list_));
      return;
  }
}

Value::~Value(){
  switch (type_) {
    case Type::NONE:
    case Type::BOOLEAN:
    case Type::INT64:
      break;
    case Type::STRING:
      string_value_.~StringStorage();
      break;
    case Type::DICTIONARY:
      dictionary_.~DictionaryStorage();
      break;
    case Type::LIST:
      list_.~ListStorage();
      break;
  }
};

bool Value::GetBool() const {
  assert(IsBool());
  return bool_value_;
}

int64_t Value::GetInt64() const {
  if (IsInt64()) {
    return int64_value_;
  }
  assert(false);
  return 0;
}

const std::string& Value::GetString() const {
  assert(IsString());
  return string_value_;
}

Value::ListStorage& Value::GetList() {
  assert(IsList());
  return list_;
}

const Value::ListStorage& Value::GetList() const {
  assert(IsList());
  return list_;
}

Value::DictionaryStorage& Value::GetDictionary() {
  assert(IsDictionary());
  return dictionary_;
}

const Value::DictionaryStorage& Value::GetDictionary() const {
  assert(IsDictionary());
  return dictionary_;
}

Value* Value::FindKeyOfType(std::string const& key, Type type) {
  return const_cast<Value*>(
      static_cast<const Value*>(this)->FindKeyOfType(key, type));
}

const Value* Value::FindKeyOfType(std::string const& key, Type type) const {
  const Value* result = FindKey(key);
  if (!result || result->GetType() != type) {
    return nullptr;
  }
  return result;
}

const Value* Value::FindKey(std::string const& key) const {
  assert(IsDictionary());
  auto it = dictionary_.find(key);
  if (it == dictionary_.end()) {
    return nullptr;
  }
  return it->second.get();
}

void Value::AssignValueFromKeyIfAvailable(std::string const& key,
                                          std::string& value) const {
  assert(IsDictionary());
  auto val = FindKeyOfType(key, Type::STRING);
  if (val) {
    value = val->GetString();
  }
}

void Value::AssignValueFromKeyIfAvailable(std::string const& key,
                                          int64_t& value) const {
  assert(IsDictionary());
  auto val = FindKeyOfType(key, Type::INT64);
  if (val) {
    value = val->GetInt64();
  }
}

void Value::SetKey(std::string const& key, std::unique_ptr<Value> value) {
  assert(IsDictionary());
  dictionary_[key] = std::move(value);
}

bool Value::RemoveKey(std::string const& key) {
  assert(IsDictionary());
  return dictionary_.erase(key) > 0;
}

}  // namespace dux


text:
<?php
use Kafoso\Questful\Exception\BadRequestException;
use Kafoso\Questful\Factory\Model\QueryParser\QueryParserFactory;
use Kafoso\Questful\Model\Mapping;
use Kafoso\Questful\Model\Mapping\Allowable;
use Kafoso\Questful\Model\Bridge\PdoSqlite\PdoSqlite3;

require_once(__DIR__ . "/../vendor/autoload.php");

/**
 * Requires the sqlite3 extension for PHP.
 *
 * Usage: php 008-sqlite3.php <URL>
 * Where <URL> is any URL containing a query (i.e. content after "?").
 *
 * Sample URLs:
 *  - "?filter[]=id=1"
 *  - "?filter[]=name!=\"fOO\"/i"
 *  - "?filter[]=name=%\"f\"%/i"
 *  - "?filter[]=timeCreated>\"2015-01-01\""
 *  - "?sort[]=name"
 */

if (false == class_exists('SQLite3')) {
    echo "Class 'SQLite3' not found." . PHP_EOL;
    exit(1);
}

if (false == isset($argv[1])) {
    echo "Please provide a URL as the 2nd argument. E.g.: php 008-sqlite3.php '?filter[]=id=1'" . PHP_EOL;
    return false;
}

$databaseFilePathAbsolute = __DIR__ . "/resources/__generated/008-sqlite3.db";

if (file_exists($databaseFilePathAbsolute)) {
    unlink($databaseFilePathAbsolute);
}

$db = new SQLite3($databaseFilePathAbsolute);
$db->query("CREATE TABLE User (id INT(11), name VARCHAR(255), timeCreated DATETIME DEFAULT CURRENT_TIMESTAMP);");
$db->query("INSERT INTO User VALUES (1, \"Foo\", \"2015-01-01\")");
$db->query("INSERT INTO User VALUES (2, \"Bar\", \"2016-01-01\")");
$db->query("INSERT INTO User VALUES (3, \"Baz\", \"2016-02-02\")");

$url = $argv[1];

$queryParserFactory = new QueryParserFactory;
$queryParser = $queryParserFactory->createFromUri($url);

try {
    $queryParser->parse();

    $mapping = new Mapping($queryParser);
    $mapping
        ->relate('id', 'u.id')
        ->relate('timeCreated', 'u.timeCreated')
        ->relate('name', 'u.name')
        ->allow(new Allowable\Filter\AllowedIntegerFilter("id"))
        ->allow(new Allowable\Filter\AllowedStringFilter("timeCreated"))
        ->allow(new Allowable\Filter\AllowedStringFilter("name"))
        ->allow(new Allowable\Filter\AllowedLikeFilter("name"))
        ->allow(new Allowable\AllowedSort("name"))
        ->validate();

    $pdoSqlite = new PdoSqlite3($mapping);
    $pdoSqlite->generate();

    $sql = "SELECT u.* FROM User u";
    if ($pdoSqlite->getWhere()) {
        $sql .= " WHERE {$pdoSqlite->getWhere()}";
    }
    if ($pdoSqlite->getOrderBy()) {
        $sql .= " ORDER BY {$pdoSqlite->getOrderBy()}";
    }
    $stmt = $db->prepare($sql);
    $parameters = $pdoSqlite->getParameters();
    foreach ($parameters as $k => $v) {
        $stmt->bindParam(":{$k}", $parameters[$k]); // Because SQLite calls this by reference; derp?
    }
    $result = $stmt->execute();
    $users = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $users[] = $row;
    }
    echo json_encode($users, JSON_PRETTY_PRINT);
} catch (BadRequestException $e) {
    header("HTTP/1.0 400 Bad Request");
    throw $e;
} catch (\Exception $e) {
    header("HTTP/1.0 500 Internal Server Error");
    throw $e;
} finally {
    $db->close();
    if (file_exists($databaseFilePathAbsolute)) {
        unlink($databaseFilePathAbsolute);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <tomcrypt.h>

/**
   @file pkcs_5_1.c
   PKCS #5, Algorithm #1, Tom St Denis
*/
#ifdef LTC_PKCS_5
/**
   Execute PKCS #5 v1
   @param password         The password (or key)
   @param password_len     The length of the password (octet)
   @param salt             The salt (or nonce) which is 8 octets long
   @param iteration_count  The PKCS #5 v1 iteration count
   @param hash_idx         The index of the hash desired
   @param out              [out] The destination for this algorithm
   @param outlen           [in/out] The max size and resulting size of the algorithm output
   @return CRYPT_OK if successful
*/
int pkcs_5_alg1(const unsigned char *password, unsigned long password_len,
                const unsigned char *salt,
                int iteration_count,  int hash_idx,
                unsigned char *out,   unsigned long *outlen)
{
   int err;
   unsigned long x;
   hash_state    *md;
   unsigned char *buf;

   LTC_ARGCHK(password != NULL);
   LTC_ARGCHK(salt     != NULL);
   LTC_ARGCHK(out      != NULL);
   LTC_ARGCHK(outlen   != NULL);

   /* test hash IDX */
   if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
      return err;
   }

   /* allocate memory */
   md  = XMALLOC(sizeof(hash_state));
   buf = XMALLOC(MAXBLOCKSIZE);
   if (md == NULL || buf == NULL) {
      if (md != NULL) {
         XFREE(md);
      }
      if (buf != NULL) {
         XFREE(buf);
      }
      return CRYPT_MEM;
   }

   /* hash initial password + salt */
   if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) {
       goto LBL_ERR;
   }
   if ((err = hash_descriptor[hash_idx].process(md, password, password_len)) != CRYPT_OK) {
       goto LBL_ERR;
   }
   if ((err = hash_descriptor[hash_idx].process(md, salt, 8)) != CRYPT_OK) {
       goto LBL_ERR;
   }
   if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) {
       goto LBL_ERR;
   }

   while (--iteration_count) {
      /* code goes here. */
      x = MAXBLOCKSIZE;
      if ((err = hash_memory(hash_idx, buf, hash_descriptor[hash_idx].hashsize, buf, &x)) != CRYPT_OK) {
         goto LBL_ERR;
      }
   }

   /* copy upto outlen bytes */
   for (x = 0; x < hash_descriptor[hash_idx].hashsize && x < *outlen; x++) {
       out[x] = buf[x];
   }
   *outlen = x;
   err = CRYPT_OK;
LBL_ERR:
#ifdef LTC_CLEAN_STACK
   zeromem(buf, MAXBLOCKSIZE);
   zeromem(md, sizeof(hash_state));
#endif

   XFREE(buf);
   XFREE(md);

   return err;
}

#endif

/* $Source$ */
/* $Revision$ */
/* $Date$ */


text:
/*
 * OANDA v20 REST API
 *
 * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
 *
 * OpenAPI spec version: 3.0.15
 * Contact: api@oanda.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;

namespace Oanda.RestV20.Model
{
    /// <summary>
    /// The financing mode of an Account
    /// </summary>
    /// <value>The financing mode of an Account</value>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum AccountFinancingMode
    {

        /// <summary>
        /// Enum NOFINANCING for "NO_FINANCING"
        /// </summary>
        [EnumMember(Value = "NO_FINANCING")]
        NOFINANCING,

        /// <summary>
        /// Enum SECONDBYSECOND for "SECOND_BY_SECOND"
        /// </summary>
        [EnumMember(Value = "SECOND_BY_SECOND")]
        SECONDBYSECOND,

        /// <summary>
        /// Enum DAILY for "DAILY"
        /// </summary>
        [EnumMember(Value = "DAILY")]
        DAILY
    }

}


text:
<?php

namespace Doctrine\Tests\Common\Annotations\Fixtures;

use Doctrine\Tests\Common\Annotations\Fixtures\AnnotationTargetAll;
use Doctrine\Tests\Common\Annotations\Fixtures\AnnotationTargetAnnotation;

/**
 * @AnnotationTargetAll("Foo")
 */
final class ClassWithClosure
{
    /**
     * @AnnotationTargetAll(@AnnotationTargetAnnotation)
     * @var string
     */
    public $value;

    /**
     * @return  \Closure
     *
     * @AnnotationTargetAll(@AnnotationTargetAnnotation)
     */
    public function methodName(\Closure $callback)
    {
        return static function () use ($callback) {
            return $callback;
        };
    }

    /**
     * @param   integer $year
     * @param   integer $month
     * @param   integer $day
     *
     * @return  \Doctrine\Common\Collections\ArrayCollection
     */
    public function getEventsForDate($year, $month, $day)
    {
        $extractEvents = null; // check if date of item is inside day given
        $extractEvents = $this->events->filter(static function ($item) use ($year, $month, $day) {
            $leftDate  = new \DateTime($year . '-' . $month . '-' . $day . ' 00:00');
            $rigthDate = new \DateTime($year . '-' . $month . '-' . $day . ' +1 day 00:00');

            return ( $leftDate <= $item->getDateStart() ) && ( $item->getDateStart() < $rigthDate );
        });

        return $extractEvents;
    }
}


text:
namespace StryfeEditor
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.scriptEditorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.dialogEditorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.itemEditorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // menuStrip1
            //
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.scriptEditorToolStripMenuItem,
            this.dialogEditorToolStripMenuItem,
            this.itemEditorToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(280, 24);
            this.menuStrip1.TabIndex = 0;
            this.menuStrip1.Text = "menuStrip1";
            //
            // scriptEditorToolStripMenuItem
            //
            this.scriptEditorToolStripMenuItem.Name = "scriptEditorToolStripMenuItem";
            this.scriptEditorToolStripMenuItem.Size = new System.Drawing.Size(83, 20);
            this.scriptEditorToolStripMenuItem.Text = "Script Editor";
            //
            // dialogEditorToolStripMenuItem
            //
            this.dialogEditorToolStripMenuItem.Name = "dialogEditorToolStripMenuItem";
            this.dialogEditorToolStripMenuItem.Size = new System.Drawing.Size(87, 20);
            this.dialogEditorToolStripMenuItem.Text = "Dialog Editor";
            //
            // itemEditorToolStripMenuItem
            //
            this.itemEditorToolStripMenuItem.Name = "itemEditorToolStripMenuItem";
            this.itemEditorToolStripMenuItem.Size = new System.Drawing.Size(77, 20);
            this.itemEditorToolStripMenuItem.Text = "Item Editor";
            this.itemEditorToolStripMenuItem.Click += new System.EventHandler(this.itemEditorToolStripMenuItem_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(280, 29);
            this.Controls.Add(this.menuStrip1);
            this.MainMenuStrip = this.menuStrip1;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Form1";
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem scriptEditorToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem dialogEditorToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem itemEditorToolStripMenuItem;
    }
}


text:
package ninchat

import (
	"errors"
)

const (
	protocolPath = "/v2"
	endpointPath = protocolPath + "/endpoint"
	socketPath   = protocolPath + "/socket"
	pollPath     = protocolPath + "/poll"
	callPath     = protocolPath + "/call"
)

var (
	errNoActionID = errors.New("no action_id")
)

// getAddress
func getAddress(address string) string {
	if address == "" {
		return defaultAddress
	} else {
		return address
	}
}

// getEndpointHosts
func getEndpointHosts(object map[string]interface{}) (hosts []string, err error) {
	x := object["hosts"]
	if x == nil {
		err = errors.New("invalid endpoint document")
		return
	}

	xHosts, ok := x.([]interface{})
	if !ok {
		err = errors.New("invalid endpoint hosts type")
		return
	}

	if len(xHosts) == 0 {
		err = errors.New("no endpoint hosts")
		return
	}

	for _, x := range xHosts {
		if s, ok := x.(string); ok {
			hosts = append(hosts, s)
		} else {
			err = errors.New("invalid endpoint host value type")
		}
	}

	if len(hosts) > 0 {
		err = nil
	}

	return
}

// String returns the action's name.
func (a *Action) String() (s string) {
	if x, ok := a.Params["action"]; ok {
		s, _ = x.(string)
	}
	return
}

// GetID returns the action_id if Send has been called and it generated one.
func (a *Action) GetID() (id int64, err error) {
	id = a.id
	if id == 0 {
		err = errNoActionID
	}
	return
}

// Bool looks up a boolean parameter.  A boolean parameter is considered false
// when it is nil or not set.
func (e *Event) Bool(param string) (v bool) {
	if x := e.Params[param]; x != nil {
		v, _ = x.(bool)
	}
	return
}

// Int looks up a numeric parameter and converts it to an integer.
func (e *Event) Int(param string) (v int, ok bool) {
	if x := e.Params[param]; x != nil {
		var f float64
		if f, ok = x.(float64); ok {
			v = int(f)
		}
	}
	return
}

// Int64 looks up a numeric parameter and converts it to a 64-bit integer.
func (e *Event) Int64(param string) (v int64, ok bool) {
	if x := e.Params[param]; x != nil {
		var f float64
		if f, ok = x.(float64); ok {
			v = int64(f)
		}
	}
	return
}

// Float64 looks up a numeric parameter.
func (e *Event) Float64(param string) (v float64, ok bool) {
	if x := e.Params[param]; x != nil {
		v, ok = x.(float64)
	}
	return
}

// Str looks up a string parameter.
func (e *Event) Str(param string) (v string, ok bool) {
	if x := e.Params[param]; x != nil {
		v, ok = x.(string)
	}
	return
}

// Array looks up an array parameter.
func (e *Event) Array(param string) (v []interface{}, ok bool) {
	if x := e.Params[param]; x != nil {
		v, ok = x.([]interface{})
	}
	return
}

// Map looks up an object parameter.
func (e *Event) Map(param string) (v map[string]interface{}, ok bool) {
	if x := e.Params[param]; x != nil {
		v, ok = x.(map[string]interface{})
	}
	return
}

// String returns the event's name.
func (e *Event) String() (s string) {
	s, _ = e.Str("event")
	return
}

func (e *Event) initLastReply(action *Action) {
	if n, _ := e.Int("history_length"); n > 0 {
		return
	}

	if e.String() == "search_results" {
		if e.Params["users"] != nil || e.Params["channels"] != nil {
			return
		}
	}

	e.LastReply = true
}

func (event *Event) getError() (errorType, errorReason string, userAuthLost, sessionLost bool, err error) {
	if x, found := event.Params["event"]; !found || x.(string) != "error" {
		return
	}

	errorType = event.Params["error_type"].(string)

	if x := event.Params["error_reason"]; x != nil {
		errorReason = x.(string)
	}

	// Request malformed is not serious, unless it's a connection error (no
	// action id).
	if errorType == "request_malformed" {
		if _, found := event.Params["action_id"]; found {
			return
		}
	}

	switch errorType {
	case "session_not_found":
		sessionLost = true
		if x := event.Params["user_auth_deleted"]; x != nil {
			userAuthLost = x.(bool)
		}
		fallthrough

	case "connection_superseded", "message_has_too_many_parts", "message_part_too_long", "message_too_long", "payload_has_too_many_parts", "payload_part_too_long", "request_malformed":
		if errorReason != "" {
			err = errors.New("error: " + errorType + " (" + errorReason + ")")
		} else {
			err = errors.New("error: " + errorType)
		}
	}

	return
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Javier Spagnoletti <phansys@gmail.com>
 */
final class LogicalNotOperatorsWithSuccessorSpaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            if ($tokens->isUnaryPredecessorOperator($index) && $token->equals('!')) {
                if (!$tokens[$index + 1]->isWhitespace()) {
                    $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
                } else {
                    $tokens[$index + 1]->setContent(' ');
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Logical NOT operators (!) should have one trailing whitespace.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the UnaryOperatorsSpacesFixer
        return -10;
    }
}


text:
package worker

import (
	"fmt"

	"golang.org/x/net/context"

	"github.com/youtube/vitess/go/sqltypes"
	"github.com/youtube/vitess/go/vt/topo/topoproto"
	"github.com/youtube/vitess/go/vt/wrangler"

	tabletmanagerdatapb "github.com/youtube/vitess/go/vt/proto/tabletmanagerdata"
	topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)

var (
	completeChunk       = chunk{sqltypes.NULL, sqltypes.NULL, 1, 1}
	singleCompleteChunk = []chunk{completeChunk}
)

// chunk holds the information which subset of the table should be worked on.
// The subset is the range of rows in the range [start, end) where start and end
// both refer to the first column of the primary key.
// If the column is not numeric, both start and end will be sqltypes.NULL.
type chunk struct {
	start sqltypes.Value
	end   sqltypes.Value
	// number records the position of this chunk among all "total" chunks.
	// The lowest value is 1.
	number int
	// total is the total number of chunks this chunk belongs to.
	total int
}

// String returns a human-readable presentation of the chunk range.
func (c chunk) String() string {
	// Pad the chunk number such that all log messages align nicely.
	digits := digits(c.total)
	return fmt.Sprintf("%*d/%d", digits, c.number, c.total)
}

func digits(i int) int {
	digits := 1
	for {
		i /= 10
		if i == 0 {
			break
		}
		digits++
	}
	return digits
}

// generateChunks returns an array of chunks to use for splitting up a table
// into multiple data chunks. It only works for tables with a primary key
// whose first column is a numeric type.
func generateChunks(ctx context.Context, wr *wrangler.Wrangler, tablet *topodatapb.Tablet, td *tabletmanagerdatapb.TableDefinition, chunkCount, minRowsPerChunk int) ([]chunk, error) {
	if len(td.PrimaryKeyColumns) == 0 {
		// No explicit primary key. Cannot chunk the rows then.
		wr.Logger().Infof("table=%v: Not splitting the table into multiple chunks because it has no primary key columns. This will reduce the performance of the clone.", td.Name)
		return singleCompleteChunk, nil
	}
	if td.RowCount < 2*uint64(minRowsPerChunk) {
		// The automatic adjustment of "chunkCount" based on "minRowsPerChunk"
		// below would set "chunkCount" to less than 2 i.e. 1 or 0 chunks.
		// In practice in this case there should be exactly one chunk.
		// Return early in this case and notice the user about this.
		wr.Logger().Infof("table=%v: Not splitting the table into multiple chunks because it has only %d rows.", td.Name, td.RowCount)
		return singleCompleteChunk, nil
	}
	if chunkCount == 1 {
		return singleCompleteChunk, nil
	}

	// Get the MIN and MAX of the leading column of the primary key.
	query := fmt.Sprintf("SELECT MIN(%v), MAX(%v) FROM %v.%v", escape(td.PrimaryKeyColumns[0]), escape(td.PrimaryKeyColumns[0]), escape(topoproto.TabletDbName(tablet)), escape(td.Name))
	shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
	qr, err := wr.TabletManagerClient().ExecuteFetchAsApp(shortCtx, tablet, true, []byte(query), 1)
	cancel()
	if err != nil {
		return nil, fmt.Errorf("Cannot determine MIN and MAX of the first primary key column. ExecuteFetchAsApp: %v", err)
	}
	if len(qr.Rows) != 1 {
		return nil, fmt.Errorf("Cannot determine MIN and MAX of the first primary key column. Zero rows were returned for the following query: %v", query)
	}

	result := sqltypes.Proto3ToResult(qr)
	min, _ := sqltypes.ToNative(result.Rows[0][0])
	max, _ := sqltypes.ToNative(result.Rows[0][1])

	if min == nil || max == nil {
		wr.Logger().Infof("table=%v: Not splitting the table into multiple chunks, min or max is NULL: %v", td.Name, qr.Rows[0])
		return singleCompleteChunk, nil
	}

	// Determine the average number of rows per chunk for the given chunkCount.
	avgRowsPerChunk := td.RowCount / uint64(chunkCount)
	if avgRowsPerChunk < uint64(minRowsPerChunk) {
		// Reduce the chunkCount to fulfill minRowsPerChunk.
		newChunkCount := td.RowCount / uint64(minRowsPerChunk)
		wr.Logger().Infof("table=%v: Reducing the number of chunks from the default %d to %d to make sure that each chunk has at least %d rows.", td.Name, chunkCount, newChunkCount, minRowsPerChunk)
		chunkCount = int(newChunkCount)
	}

	// TODO(mberlin): Write a unit test for this part of the function.
	var interval interface{}
	chunks := make([]chunk, chunkCount)
	switch min := min.(type) {
	case int64:
		max := max.(int64)
		interval = (max - min) / int64(chunkCount)
		if interval == 0 {
			wr.Logger().Infof("table=%v: Not splitting the table into multiple chunks, interval=0: %v to %v", td.Name, min, max)
			return singleCompleteChunk, nil
		}
	case uint64:
		max := max.(uint64)
		interval = (max - min) / uint64(chunkCount)
		if interval == 0 {
			wr.Logger().Infof("table=%v: Not splitting the table into multiple chunks, interval=0: %v to %v", td.Name, min, max)
			return singleCompleteChunk, nil
		}
	case float64:
		max := max.(float64)
		interval = (max - min) / float64(chunkCount)
		if interval == 0 {
			wr.Logger().Infof("table=%v: Not splitting the table into multiple chunks, interval=0: %v to %v", td.Name, min, max)
			return singleCompleteChunk, nil
		}
	default:
		wr.Logger().Infof("table=%v: Not splitting the table into multiple chunks, primary key not numeric.", td.Name)
		return singleCompleteChunk, nil
	}

	// Create chunks.
	start := min
	for i := 0; i < chunkCount; i++ {
		end := add(start, interval)
		chunk, err := toChunk(start, end, i+1, chunkCount)
		if err != nil {
			return nil, err
		}
		chunks[i] = chunk
		start = end
	}

	// Clear out the MIN and MAX on the first and last chunk respectively
	// because other shards might have smaller or higher values than the one we
	// looked at.
	chunks[0].start = sqltypes.NULL
	chunks[chunkCount-1].end = sqltypes.NULL
	return chunks, nil
}

func add(start, interval interface{}) interface{} {
	switch start := start.(type) {
	case int64:
		return start + interval.(int64)
	case uint64:
		return start + interval.(uint64)
	case float64:
		return start + interval.(float64)
	default:
		panic(fmt.Sprintf("unsupported type %T for interval start: %v", start, start))
	}
}

func toChunk(start, end interface{}, number, total int) (chunk, error) {
	startValue, err := sqltypes.InterfaceToValue(start)
	if err != nil {
		return chunk{}, fmt.Errorf("Failed to convert calculated start value (%v) into internal sqltypes.Value: %v", start, err)
	}
	endValue, err := sqltypes.InterfaceToValue(end)
	if err != nil {
		return chunk{}, fmt.Errorf("Failed to convert calculated end value (%v) into internal sqltypes.Value: %v", end, err)
	}
	return chunk{startValue, endValue, number, total}, nil
}


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">
    <meta name="description" content="Tropps HTML5 Weather App">
    <meta name="author" content="Dan Fairaizl">

    <title>Tropos</title>

    <link href="assets/stylesheets/bootstrap.css" rel="stylesheet">
    <link href="assets/stylesheets/weather-icons.css" rel="stylesheet">
    <link href="assets/stylesheets/tropos.css" rel="stylesheet">

°

{{ currentWeather.name }}

S

M

T

W

T

F

S


text:
package ftcbootstrap.demos.beginner.opmodes;

import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;

import ftcbootstrap.ActiveOpMode;
import ftcbootstrap.components.operations.servos.GamePadServo;
import ftcbootstrap.demos.beginner.MyFirstBot;

/**
 * Note: This Exercise assumes that you have used your Robot Controller App to "scan" your hardware and
 * saved the configuration named: "MyFirstBot" and creating a class by the same name: {@link MyFirstBot}.
 * <p/>
 * Summary: Use an Operation class to control servo with the gamepad buttons
 * See: {@link GamePadServo}
 */

@TeleOp
@Disabled
public class OpMode7ServoWithGamepad extends ActiveOpMode {

    private MyFirstBot robot;
    private GamePadServo gamePadServo;

    /**
     * Implement this method to define the code to run when the Init button is pressed on the Driver station.
     */
    @Override
    protected void onInit() {

        robot = MyFirstBot.newConfig(hardwareMap, getTelemetryUtil());

        //Note The Telemetry Utility is designed to let you organize all telemetry data before sending it to
        //the Driver station via the sendTelemetry command
        getTelemetryUtil().addData("Init", getClass().getSimpleName() + " initialized.");
        getTelemetryUtil().sendTelemetry();

    }

    @Override
    protected void onStart() throws InterruptedException  {
        super.onStart();

        // GamePadServo.Control use the Y and A buttons for up and down and the  X and B buttons for left and right
        // Set initial position of server to 0.5
        gamePadServo = new GamePadServo(this, gamepad1, robot.servo,GamePadServo.Control.Y_A, 0.5);
        gamePadServo.setOpModeLogLevel(1);
    }

    /**
     * Implement this method to define the code to run when the Start button is pressed on the Driver station.
     * This method will be called on each hardware cycle just as the loop() method is called for event based Opmodes
     *
     * @throws InterruptedException
     */
    @Override
    protected void activeLoop() throws InterruptedException {

        //update the servo from the gamepad button events
        gamePadServo.update();

        //send any telemetry that may have been added in the above operations
        getTelemetryUtil().sendTelemetry();

    }

}


text:
iOS App Development with Swift Essential Training with Edward Chiang

![simulator screen shot 2015 11 3 8 25 12](https://cloud.githubusercontent.com/assets/8311884/10908010/64dcfafa-8269-11e5-8c1d-9e3b27e5810a.png)


text:
function ComponentProgressBar( id ) {
	var self = new Component(id);

	self.setState('width', 200);
	self.setState('percent', 0);
	self.setState('transitional', false);

	var previousUpdateVisual = self.updateVisual;
	self.updateVisual = function() {
		var width = self.getState('width');
		self.applyLowlightColouring(self.node());

		if( self.getState('percent') > 0 ) {
			// Create the progress node
			var content = document.createElement('div');
			content.innerHTML = '<b>' + self.getState('percent') + '%</b>';
			content.style.width = '' + (self.getState('percent') * (width / 100)) + 'px';
			content.style.padding = '2px';
			self.applyHighlightColouring(content);
			// Add the progress node
			self.node().innerHTML = '';
			self.node().style.padding = '0px';
			self.node().style.width = '' + (width + 4) + 'px';
			self.node().appendChild(content);
		} else {
			self.node().style.width = '' + width + 'px';
			self.node().style.padding = '2px';
			self.node().innerHTML = '0%';
		}

		self.node().style.border = '1px solid #333';
		previousUpdateVisual();
	};
	return self;
}


text:
<?php

namespace PdbRestFul\Model;

use Zend\Db\Sql\Select;
use Zend\Db\TableGateway\TableGateway;

class AuthorYearJournalCountTable
{

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    /**
     * @param $author_id
     * @return \Zend\Db\ResultSet\ResultSet
     */
    public function fetch($author_id)
    {
        $author_id = (int)$author_id;
        $select = new Select();
        $select->from($this->tableGateway->getTable())
            ->join(
                'author',
                $this->tableGateway->getTable() . '.id=author.id',
                ['author_id' => 'id', 'author_name' => 'name']
            )
            ->join(
                'journal',
                $this->tableGateway->getTable() . '.jnl_id=journal.id',
                ['journal_id' => 'id', 'journal_name' => 'name']
            )
            ->columns(['year', 'count', 'paperlist'])
            ->where([$this->tableGateway->getTable() . '.id' => $author_id]);
        $resultSet = $this->tableGateway->selectWith($select);
        $res = [];
        foreach ($resultSet as $s) {
            $res[] = $s;
        }

        return $res;
    }

}


text:
BOARD ?= arduino_zero
ifeq ($(wildcard boards/$(BOARD)/.),)
$(error Invalid BOARD specified)
endif

# local mod:
BOARD = metro_m0_express

# If the build directory is not given, make it reflect the board name.
BUILD ?= build-$(BOARD)

include ../py/mkenv.mk
-include mpconfigport.mk
include boards/$(BOARD)/mpconfigboard.mk

# qstr definitions (must come before including py.mk)
# TODO(tannewt): Support friendly pin names like the stmhal implementations do.
# Add $(BUILD)/pins_qstr.h $(BUILD)/modstm_qstr.h
QSTR_DEFS = qstrdefsport.h

# include py core make definitions
include ../py/py.mk

CROSS_COMPILE = arm-none-eabi-

BOSSAC := tools/bossac_osx

HAL_DIR=hal/$(MCU_SERIES)

INC += -I.
INC += -I..
INC += -I../lib/mp-readline
INC += -I../lib/timeutils
INC += -Iasf_conf/
INC += -Iasf/common/boards/
INC += -Iasf/common/services/sleepmgr/
INC += -Iasf/common/services/storage/ctrl_access/
INC += -Iasf/common/services/usb/
INC += -Iasf/common/services/usb/class/cdc/
INC += -Iasf/common/services/usb/class/cdc/device/
INC += -Iasf/common/services/usb/class/hid/
INC += -Iasf/common/services/usb/class/hid/device/
INC += -Iasf/common/services/usb/class/hid/device/kbd/
INC += -Iasf/common/services/usb/class/hid/device/mouse/
INC += -Iasf/common/services/usb/class/msc/
INC += -Iasf/common/services/usb/class/msc/device/
INC += -Iasf/common/services/usb/udc/
INC += -Iasf/common/utils
INC += -Iasf/common2/services/delay/
INC +=  $(addprefix -Iasf/sam0/,\
	drivers/events \
	drivers/extint \
	drivers/port \
	drivers/system \
	drivers/adc/adc_sam_d_r \
	drivers/dac \
	drivers/dac/dac_sam_d_c \
	drivers/sercom \
	drivers/sercom/i2c \
	drivers/system/clock \
	drivers/system/clock/clock_samd21_r21_da \
	drivers/system/interrupt \
	drivers/system/interrupt/system_interrupt_samd21 \
	drivers/system/pinmux \
	drivers/system/power/power_sam_d_r \
	drivers/system/reset/reset_sam_d_r \
	drivers/tc \
	drivers/usb \
	utils \
	utils/cmsis/samd21/include \
	utils/cmsis/samd21/source \
	utils/header_files \
	utils/preprocessor \
	)
INC += -Iasf/thirdparty/CMSIS/Include
INC += -Iboards
INC += -Iboards/$(BOARD)/
INC += -Ifreetouch/
INC += -I$(BUILD)

CFLAGS_CORTEX_M0 = \
	-mthumb \
	-mabi=aapcs-linux \
	-mcpu=cortex-m0plus \
	-msoft-float \
	-mfloat-abi=soft \
	-fsingle-precision-constant \
	-fno-strict-aliasing \
	-Wdouble-promotion \
	-Wno-endif-labels \
	-Wstrict-prototypes \
	-Werror-implicit-function-declaration \
	-Wpointer-arith \
	-Wfloat-equal \
	-Wundef \
	-Wshadow \
	-Wwrite-strings \
	-Wsign-compare \
	-Wmissing-format-attribute \
	-Wno-deprecated-declarations \
	-Wpacked \
	-Wnested-externs \
	-Wunreachable-code \
	-Wcast-align \
	-D__$(CHIP_VARIANT)__ \
	-DUSB_DEVICE_PRODUCT_ID=$(USB_PID) \
	-DUSB_DEVICE_VENDOR_ID=$(USB_VID) \
	-DBOARD=USER_BOARD \
	-ffunction-sections \
	-fdata-sections \
	-fshort-enums \
	-D ARM_MATH_CM0PLUS=true \
	-DSYSTICK_MODE \
	-DEXTINT_CALLBACK_MODE=true \
	-DUDD_ENABLE \
	-DUSART_CALLBACK_MODE=false \
	-DSPI_CALLBACK_MODE=false \
	-DI2C_MASTER_CALLBACK_MODE=false \
	-DDAC_CALLBACK_MODE=false \
	-DTCC_ASYNC=false \
	-DADC_CALLBACK_MODE=false \
	-DEVENTS_INTERRUPT_HOOKS_MODE=false \
	-DTC_ASYNC=true \
	-DUSB_DEVICE_LPM_SUPPORT \
	-DCIRCUITPY_CANARY_WORD=0xADAF00 \
	-DCIRCUITPY_SAFE_RESTART_WORD=0xDEADBEEF \
	--param max-inline-insns-single=500
CFLAGS = $(INC) -Wall -Werror -std=gnu11 -nostdlib $(CFLAGS_CORTEX_M0) $(CFLAGS_MOD) $(COPT)

#Debugging/Optimization
# TODO(tannewt): Figure out what NDEBUG does. Adding it to the debug build
# reduces code size pretty dramatically.
ifeq ($(DEBUG), 1)
CFLAGS += -Os -ggdb -DNDEBUG -DENABLE_MICRO_TRACE_BUFFER
else
CFLAGS += -Os -DNDEBUG -flto
endif

ifneq ($(FROZEN_DIR),)
# To use frozen source modules, put your .py files in a subdirectory (eg scripts/)
# and then invoke make with FROZEN_DIR=scripts (be sure to build from scratch).
CFLAGS += -DMICROPY_MODULE_FROZEN_STR
endif

ifneq ($(FROZEN_MPY_DIR),)
# To use frozen bytecode, put your .py files in a subdirectory (eg frozen/) and
# then invoke make with FROZEN_MPY_DIR=frozen (be sure to build from scratch).
CFLAGS += -DMICROPY_QSTR_EXTRA_POOL=mp_qstr_frozen_const_pool
CFLAGS += -DMICROPY_MODULE_FROZEN_MPY
endif

#LIBM_FILE_NAME   = $(shell $(CC) $(CFLAGS) -print-file-name=libm.a)
LDFLAGS = $(CFLAGS) -nostartfiles -fshort-enums -mthumb -mcpu=cortex-m0plus -Lasf/thirdparty/CMSIS/Lib/GCC/ -Wl,-nostdlib -Wl,-T,$(LD_FILE) -Wl,-Map=$@.map -Wl,-cref -Wl,-gc-sections -specs=nano.specs
LIBS = -larm_cortexM0l_math -lm -lgcc -lc

SRC_ASF = $(addprefix asf/sam0/,\
	drivers/adc/adc_sam_d_r/adc.c \
	drivers/dac/dac_sam_d_c/dac.c \
	drivers/dma/dma.c \
	drivers/events/events_sam_d_r/events.c \
	drivers/extint/extint_callback.c \
	drivers/extint/extint_sam_d_r/extint.c \
	drivers/nvm/nvm.c \
	drivers/port/port.c \
	drivers/sercom/i2c/i2c_sam0/i2c_master.c \
	drivers/sercom/sercom.c \
	drivers/sercom/sercom_interrupt.c \
	drivers/sercom/spi/spi.c \
	drivers/sercom/usart/usart.c \
	drivers/system/clock/clock_samd21_r21_da/clock.c \
	drivers/system/clock/clock_samd21_r21_da/gclk.c \
	drivers/system/interrupt/system_interrupt.c   \
	drivers/system/pinmux/pinmux.c \
	drivers/system/system.c \
	drivers/tc/tc_interrupt.c \
	drivers/tc/tc_sam_d_r/tc.c \
	drivers/tcc/tcc.c \
	drivers/usb/stack_interface/usb_device_udd.c \
	drivers/usb/stack_interface/usb_dual.c \
	drivers/usb/usb_sam_d_r/usb.c \
	)

SRC_C = \
	access_vfs.c \
	autoreload.c \
	background.c \
	fatfs_port.c \
	flash_api.c \
	main.c \
	mphalport.c \
	samd21_pins.c \
	shared_dma.c \
	rgb_led_status.c \
	tick.c \
	$(FLASH_IMPL) \
	bindings/samd/__init__.c \
	asf/common/services/sleepmgr/samd/sleepmgr.c \
	asf/common/services/storage/ctrl_access/ctrl_access.c  \
	asf/common/services/usb/class/cdc/device/udi_cdc.c \
	asf/common/services/usb/class/composite/device/udi_composite_desc.c \
	asf/common/services/usb/class/hid/device/udi_hid.c \
	asf/common/services/usb/class/hid/device/mouse/udi_hid_mouse.c \
	asf/common/services/usb/class/hid/device/kbd/udi_hid_kbd.c \
	asf/common/services/usb/class/msc/device/udi_msc.c     \
	asf/common/services/usb/udc/udc.c \
	asf/common/utils/interrupt/interrupt_sam_nvic.c \
	asf/common2/services/delay/sam0/systick_counter.c \
	asf/sam0/utils/cmsis/samd21/source/gcc/startup_samd21.c \
	asf/sam0/utils/cmsis/samd21/source/system_samd21.c \
	asf/sam0/utils/syscalls/gcc/syscalls.c \
	boards/$(BOARD)/board.c \
	boards/$(BOARD)/pins.c \
	freetouch/adafruit_ptc.c \
	lib/oofatfs/ff.c \
	lib/oofatfs/option/ccsbcs.c \
	lib/timeutils/timeutils.c \
	lib/utils/buffer_helper.c \
	lib/utils/context_manager_helpers.c \
	lib/utils/interrupt_char.c \
	lib/utils/pyexec.c \
	lib/utils/stdout_helpers.c \
	lib/libc/string0.c \
	lib/mp-readline/readline.c

STM_SRC_C = $(addprefix stmhal/,\
	pybstdio.c \
	)

SRC_COMMON_HAL = \
	analogio/__init__.c \
	analogio/AnalogIn.c \
	analogio/AnalogOut.c \
	audioio/__init__.c \
	audioio/AudioOut.c \
	board/__init__.c \
	busio/__init__.c \
	busio/I2C.c \
	busio/SPI.c \
	busio/UART.c \
	digitalio/__init__.c \
	digitalio/DigitalInOut.c \
	microcontroller/__init__.c \
	microcontroller/Pin.c \
	neopixel_write/__init__.c \
	os/__init__.c \
	pulseio/__init__.c \
	pulseio/PulseIn.c \
	pulseio/PulseOut.c \
	pulseio/PWMOut.c \
	storage/__init__.c \
	time/__init__.c \
	touchio/__init__.c \
	touchio/TouchIn.c \
	usb_hid/__init__.c \
	usb_hid/Device.c

# These don't have corresponding files in each port but are still located in
# shared-bindings to make it clear what the contents of the modules are.
SRC_BINDINGS_ENUMS = \
	digitalio/Direction.c \
	digitalio/DriveMode.c \
	digitalio/Pull.c \
	help.c

SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \
                          $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \
                          $(addprefix common-hal/, $(SRC_COMMON_HAL))

SRC_SHARED_MODULE = \
	bitbangio/__init__.c \
	bitbangio/I2C.c \
	bitbangio/OneWire.c \
	bitbangio/SPI.c \
	busio/OneWire.c \
	os/__init__.c \
	random/__init__.c \
	storage/__init__.c \
	uheap/__init__.c \

SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \
                             $(addprefix shared-module/, $(SRC_SHARED_MODULE))

OBJ = $(PY_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(SRC_ASF:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(STM_SRC_C:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_EXPANDED:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(SRC_SHARED_MODULE_EXPANDED:.c=.o))

SRC_QSTR += $(SRC_C) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(STM_SRC_C)

install: $(BUILD)/firmware.uf2
	cp -p ./build-metro_m0_express/firmware.uf2 /vagrant/
	md5sum  /vagrant/firmware.uf2

nclean:
	@rm -rf ./build-metro_m0_express
	@rm -rf ./VERSION.h

version:
#       @echo -n "AINSU_REPORT(\"ainsuSPI  "    > VERSION.h  # delimit for quoted string
	@echo -n "AINSU_REPORT(ainsuSPI  "      > VERSION.h
	@echo -n `date | md5sum | cut -b1-6`   >> VERSION.h
	@echo -n "   "                         >> VERSION.h
	@echo -n `date | cut -b1-24`           >> VERSION.h
	@echo -n "   "                         >> VERSION.h
	@echo -n " TERRAPA CIONGA "            >> VERSION.h
	@echo -n " SAMD21G18A"                 >> VERSION.h
#	@echo -n "\")"                         >> VERSION.h  # delimit for quoted string
	@echo -n ")"                           >> VERSION.h

all: version $(BUILD)/firmware.bin $(BUILD)/firmware.uf2

$(BUILD)/firmware.elf: $(OBJ)
	$(STEPECHO) "LINK $@"
	$(Q)$(CC) -o $@ $(LDFLAGS) $^ -Wl,--start-group $(LIBS) -Wl,--end-group
	$(Q)$(SIZE) $@ | python3 ../tools/build_memory_info.py $(LD_FILE)

$(BUILD)/firmware.bin: $(BUILD)/firmware.elf
	$(ECHO) "Create $@"
	$(Q)$(OBJCOPY) -O binary -j .vectors -j .text -j .data $^ $@

$(BUILD)/firmware.uf2: $(BUILD)/firmware.bin
	$(ECHO) "Create $@"
	python2 ../tools/uf2/utils/uf2conv.py -c -o $@ $^

deploy: $(BUILD)/firmware.bin
	$(ECHO) "Writing $< to the board"
	$(BOSSAC) -u $<

# Run emulation build on a POSIX system with suitable terminal settings
run:
	stty raw opost -echo
	build/firmware.elf
	@echo Resetting terminal...
# This sleep is useful to spot segfaults
	sleep 1
	reset

test: $(BUILD)/firmware.elf
	$(Q)/bin/echo -e "print('hello world!', list(x+1 for x in range(10)), end='eol\\\\n')\\r\\n\\x04" | $(BUILD)/firmware.elf | tail -n2 | grep "^hello world! \\[1, 2, 3, 4, 5, 6, 7, 8, 9, 10\\]eol"

include ../py/mkrules.mk


text:
local skynet = require "skynet"
require "skynet.manager"	-- import skynet.register
local snax = require "skynet.snax"

local cmd = {}
local service = {}

local function request(name, func, ...)
	local ok, handle = pcall(func, ...)
	local s = service[name]
	assert(type(s) == "table")
	if ok then
		service[name] = handle
	else
		service[name] = tostring(handle)
	end

	for _,v in ipairs(s) do
		skynet.wakeup(v.co)
	end

	if ok then
		return handle
	else
		error(tostring(handle))
	end
end

local function waitfor(name , func, ...)
	local s = service[name]
	if type(s) == "number" then
		return s
	end
	local co = coroutine.running()

	if s == nil then
		s = {}
		service[name] = s
	elseif type(s) == "string" then
		error(s)
	end

	assert(type(s) == "table")

	if not s.launch and func then
		s.launch = true
		return request(name, func, ...)
	end

	local session, source = skynet.context()
	table.insert(s, {
		co = co,
		session = session,
		source = source,
	})
	skynet.wait()
	s = service[name]
	if type(s) == "string" then
		error(s)
	end
	assert(type(s) == "number")
	return s
end

local function read_name(service_name)
	if string.byte(service_name) == 64 then -- '@'
		return string.sub(service_name , 2)
	else
		return service_name
	end
end

function cmd.LAUNCH(service_name, subname, ...)
	local realname = read_name(service_name)

	if realname == "snaxd" then
		return waitfor(service_name.."."..subname, snax.rawnewservice, subname, ...)
	else
		return waitfor(service_name, skynet.newservice, realname, subname, ...)
	end
end

function cmd.QUERY(service_name, subname)
	local realname = read_name(service_name)

	if realname == "snaxd" then
		return waitfor(service_name.."."..subname)
	else
		return waitfor(service_name)
	end
end

local function list_service()
	local result = {}
	for k,v in pairs(service) do
		if type(v) == "string" then
			v = "Error: " .. v
		elseif type(v) == "table" then
			local querying = { "Querying:" }
			for _, detail in ipairs(v) do
				table.insert(querying, skynet.address(detail.source) .. " " .. tostring(skynet.call(detail.source, "debug", "TASK", detail.session)))
			end
			v = table.concat(querying, "\n")
		else
			v = skynet.address(v)
		end

		result[k] = v
	end

	return result
end

local function register_global()
	function cmd.GLAUNCH(name, ...)
		local global_name = "@" .. name
		return cmd.LAUNCH(global_name, ...)
	end

	function cmd.GQUERY(name, ...)
		local global_name = "@" .. name
		return cmd.QUERY(global_name, ...)
	end

	local mgr = {}

	function cmd.REPORT(m)
		mgr[m] = true
	end

	local function add_list(all, m)
		local harbor = "@" .. skynet.harbor(m)
		local result = skynet.call(m, "lua", "LIST")
		for k,v in pairs(result) do
			all[k .. harbor] = v
		end
	end

	function cmd.LIST()
		local result = {}
		for k in pairs(mgr) do
			pcall(add_list, result, k)
		end
		local l = list_service()
		for k, v in pairs(l) do
			result[k] = v
		end
		return result
	end
end

local function register_local()
	local function waitfor_remote(cmd, name, ...)
		local global_name = "@" .. name
		local local_name
		if name == "snaxd" then
			local_name = global_name .. "." .. (...)
		else
			local_name = global_name
		end
		return waitfor(local_name, skynet.call, "SERVICE", "lua", cmd, global_name, ...)
	end

	function cmd.GLAUNCH(...)
		return waitfor_remote("LAUNCH", ...)
	end

	function cmd.GQUERY(...)
		return waitfor_remote("QUERY", ...)
	end

	function cmd.LIST()
		return list_service()
	end

	skynet.call("SERVICE", "lua", "REPORT", skynet.self())
end

skynet.start(function()
	skynet.dispatch("lua", function(session, address, command, ...)
		local f = cmd[command]
		if f == nil then
			skynet.ret(skynet.pack(nil, "Invalid command " .. command))
			return
		end

		local ok, r = pcall(f, ...)

		if ok then
			skynet.ret(skynet.pack(r))
		else
			skynet.ret(skynet.pack(nil, r))
		end
	end)
	local handle = skynet.localname ".service"
	if  handle then
		skynet.error(".service is already register by ", skynet.address(handle))
		skynet.exit()
	else
		skynet.register(".service")
	end
	if skynet.getenv "standalone" then
		skynet.register("SERVICE")
		register_global()
	else
		register_local()
	end
end)


text:
<?php   /*
	defined('C5_EXECUTE') or die(_("Access Denied."));
	$aBlocks = $controller->generateNav();
	global $c;
	foreach($aBlocks as $ni) {
		$_c = $ni->getCollectionObject();
		if (!$_c->getCollectionAttributeValue('exclude_nav')) {
			if ($c->getCollectionID() == $_c->getCollectionID()) {
				echo($ni->getName());
			} else {
				echo('getURL() . '">' . $ni->getName() . ' > ');
			}
			$lastLevel = $thisLevel;
			$i++;
		}
	}
	$thisLevel = 0;
	*/
?>

<?php
    defined('C5_EXECUTE') or die(_("Access Denied."));
    $aBlocks = $controller->generateNav();
    global $c;
    //output

show_breadcrumb($c);

function show_breadcrumb($c){
	$nh=Loader::helper('navigation');
	$breadcrumb=$nh->getTrailToCollection($c);
	krsort($breadcrumb);
	foreach($breadcrumb as $bcpage){
		echo'getCollectionPath().'/">'.$bcpage->getCollectionName().' – ';
	}
	//echo '' . $c->getCollectionName() . '';
	echo $c->getCollectionName();
}

?>


text:
class PageLoad < ActiveRecord::Base
  after_initialize :set_default_value

  def set_default_value
    self.datetime_stamp ||= Time.zone.now
  end
end


text:
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>{% block title %}<%= package.name %>{% endblock %}</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        {% assets "css_all" %}
            <link rel="stylesheet" type="text/css" href="{{ ASSET_URL }}">
        {% endassets %}

        {% block css %}{% endblock %}
    </head>
    <body>
        <div class="container main-window {% block extra_class %}{% endblock %}">
            {% block content %}{% endblock %}
        </div>
        {% assets "js_all" %}
            <script type="text/javascript" src="{{ ASSET_URL }}"></script>
        {% endassets %}
    </body>
</html>


text:
<?php namespace Modulework\Modules\File\Stubs;
/*
 * (c) Christian Gärtner <christiangaertner.film@googlemail.com>
 * This file is part of the Modulework Framework Tests
 * License: View distributed LICENSE file
 *
 *
 * This file is meant to be used in PHPUnit Tests as a stub
 */

use Modulework\Modules\File\FileSystemInterface;

/**
* PHPUnit Test
*/
class VFileSystemTrue implements FileSystemInterface
{
	public static function glob($path, $flags = 0)
	{
		return true;
	}
	public static function files($path)
	{
		return true;
	}
	public static function all($path)
	{
		return true;
	}
	public static function directories($path)
	{
		return true;
	}
	public static function makeDirectory($path, $mode, $recursive = false)
	{
		return true;
	}
	public static function copyDirectory($path, $dest)
	{
		return true;
	}
	public static function deleteDirectory($path, $preserve = false)
	{
		return true;
	}
	public static function emptyDirectory($path)
	{
		return true;
	}

	public static function exists($path)
	{
		return true;
	}
	public static function create($path)
	{
		return true;
	}
	public static function extension($path)
	{
		return true;
	}
	public static function get($path)
	{
		return true;
	}
	public static function getRemote($path)
	{
		return true;
	}
	public static function size($path)
	{
		return true;
	}
	public static function put($path, $data)
	{
		return true;
	}
	public static function append($path, $data)
	{
		return true;
	}
	public static function delete($path)
	{
		return true;
	}
	public static function move($org, $dest)
	{
		return true;
	}
	public static function copy($org, $dest)
	{
		return true;
	}
	public static function symLink($org, $dest)
	{
		return true;
	}
	public static function isWritable($path)
	{
		return true;
	}
	public static function isReadable($path)
	{
		return true;
	}
	public static function isDirectory($path)
	{
		return true;
	}
	public static function isFile($path)
	{
		return true;
	}
	public static function type($path)
	{
		return true;
	}
	public static function accessTime($path)
	{
		return true;
	}
	public static function modifiedTime($path)
	{
		return true;
	}
	public static function creationTime($path)
	{
		return true;
	}
	public static function chmod($path, $permissions)
	{
		return true;
	}
	public static function chown($path, $owner)
	{
		return true;
	}
	public static function setPermissions($path, $permissions)
	{
		return true;
	}
	public static function getPermissions($path)
	{
		return true;
	}
}


text:
package com.github.badoualy.telegram.tl.api.payments;

import com.github.badoualy.telegram.tl.TLContext;
import com.github.badoualy.telegram.tl.api.TLPaymentRequestedInfo;
import com.github.badoualy.telegram.tl.core.TLObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.github.badoualy.telegram.tl.StreamUtils.readInt;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLObject;
import static com.github.badoualy.telegram.tl.StreamUtils.writeInt;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLObject;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32;

/**
 * @author Yannick Badoual yann.badoual@gmail.com
 * @see http://github.com/badoualy/kotlogram
 */
public class TLSavedInfo extends TLObject {

    public static final int CONSTRUCTOR_ID = 0xfb8fe43c;

    protected int flags;

    protected boolean hasSavedCredentials;

    protected TLPaymentRequestedInfo savedInfo;

    private final String _constructor = "payments.savedInfo#fb8fe43c";

    public TLSavedInfo() {
    }

    public TLSavedInfo(boolean hasSavedCredentials, TLPaymentRequestedInfo savedInfo) {
        this.hasSavedCredentials = hasSavedCredentials;
        this.savedInfo = savedInfo;
    }

    private void computeFlags() {
        flags = 0;
        flags = hasSavedCredentials ? (flags | 2) : (flags & ~2);
        flags = savedInfo != null ? (flags | 1) : (flags & ~1);
    }

    @Override
    public void serializeBody(OutputStream stream) throws IOException {
        computeFlags();

        writeInt(flags, stream);
        if ((flags & 1) != 0) {
            if (savedInfo == null) throwNullFieldException("savedInfo", flags);
            writeTLObject(savedInfo, stream);
        }
    }

    @Override
    @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
    public void deserializeBody(InputStream stream, TLContext context) throws IOException {
        flags = readInt(stream);
        hasSavedCredentials = (flags & 2) != 0;
        savedInfo = (flags & 1) != 0 ? readTLObject(stream, context, TLPaymentRequestedInfo.class,
                                                    TLPaymentRequestedInfo.CONSTRUCTOR_ID) : null;
    }

    @Override
    public int computeSerializedSize() {
        computeFlags();

        int size = SIZE_CONSTRUCTOR_ID;
        size += SIZE_INT32;
        if ((flags & 1) != 0) {
            if (savedInfo == null) throwNullFieldException("savedInfo", flags);
            size += savedInfo.computeSerializedSize();
        }
        return size;
    }

    @Override
    public String toString() {
        return _constructor;
    }

    @Override
    public int getConstructorId() {
        return CONSTRUCTOR_ID;
    }

    public boolean getHasSavedCredentials() {
        return hasSavedCredentials;
    }

    public void setHasSavedCredentials(boolean hasSavedCredentials) {
        this.hasSavedCredentials = hasSavedCredentials;
    }

    public TLPaymentRequestedInfo getSavedInfo() {
        return savedInfo;
    }

    public void setSavedInfo(TLPaymentRequestedInfo savedInfo) {
        this.savedInfo = savedInfo;
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Hainania trichosperma Merr.

### Remarks
null


text:
package org.vagabond.benchmark.explgen;

import java.sql.Connection;

import org.vagabond.xmlmodel.explanderror.ExplanationAndErrorsDocument;

import smark.support.MappingScenario;
import tresc.benchmark.Configuration;

public class TargetSkeletonGen implements ExplanationGenerator {

	@Override
	public void generateExpl(MappingScenario scenario, Connection dbCon,
			ExplanationAndErrorsDocument eDoc, Configuration conf) {
		// TODO Auto-generated method stub

	}

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProcessManagerMock = void 0;
var ProcessManagerMock = /** @class */ (function () {
    function ProcessManagerMock(enabledProcesses) {
        this.enabledProcesses = enabledProcesses;
    }
    ProcessManagerMock.prototype.addOnPreProcessStatusChange = function (handler) {
        throw new Error("Method not implemented.");
    };
    ProcessManagerMock.prototype.addOnPreStageChange = function (handler) {
        throw new Error("Method not implemented.");
    };
    ProcessManagerMock.prototype.removeOnPreProcessStatusChange = function (handler) {
        throw new Error("Method not implemented.");
    };
    ProcessManagerMock.prototype.removeOnPreStageChange = function (handler) {
        throw new Error("Method not implemented.");
    };
    ProcessManagerMock.prototype.getActiveProcess = function () {
        return this.enabledProcesses.filter(function (p) {
            return p.isRendered();
        })[0] || undefined;
    };
    ProcessManagerMock.prototype.setActiveProcess = function (processId, callbackFunction) {
        var activeProcess = this.getActiveProcess();
        if (activeProcess) {
            var newProcess = this.enabledProcesses.filter(function (p) {
                return p.getId() === processId;
            })[0] || undefined;
            if (newProcess) {
                activeProcess.isRendered = function () { return false; };
                newProcess.isRendered = function () { return true; };
            }
        }
    };
    ProcessManagerMock.prototype.setActiveProcessInstance = function (processInstanceId, callbackFunction) {
        throw new Error("set active process instance not implemented.");
    };
    ProcessManagerMock.prototype.getProcessInstances = function (callbackFunction) {
        throw new Error("get process instances not implemented.");
    };
    ProcessManagerMock.prototype.addOnProcessStatusChange = function (handler) {
        throw new Error("add on process status change not implemented.");
    };
    ProcessManagerMock.prototype.removeOnProcessStatusChange = function (handler) {
        throw new Error("remove on process status change not implemented.");
    };
    ProcessManagerMock.prototype.getInstanceId = function () {
        var activeProcess = this.getActiveProcess();
        var instanceId = activeProcess.getId() || "";
        return instanceId;
    };
    ProcessManagerMock.prototype.getInstanceName = function () {
        var activeProcess = this.getActiveProcess();
        var instanceName = activeProcess.getName();
        return instanceName;
    };
    ProcessManagerMock.prototype.getStatus = function () {
        throw new Error("get status not implemented.");
    };
    ProcessManagerMock.prototype.setStatus = function (status, callbackFunction) {
        throw new Error("set status not implemented.");
    };
    ProcessManagerMock.prototype.getActiveStage = function () {
        var activeProcess = this.getActiveProcess();
        var stages = activeProcess.getStages();
        var activeStages = [];
        stages.forEach(function (s) {
            if (s.getStatus() === "active") {
                activeStages.push(s);
            }
        });
        return activeStages[0] || undefined;
    };
    ProcessManagerMock.prototype.setActiveStage = function (stageId, callbackFunction) {
        var activeProcess = this.getActiveProcess();
        var stages = activeProcess.getStages();
        var setStatus = "";
        stages.forEach(function (s) {
            if (s.getId() === stageId) {
                s._setStatus("active");
                setStatus = "active";
            }
            else {
                s._setStatus("inactive");
            }
        });
        if (callbackFunction) {
            callbackFunction(setStatus);
        }
    };
    ProcessManagerMock.prototype.getActivePath = function () {
        throw new Error("get active path not implemented");
    };
    ProcessManagerMock.prototype.getEnabledProcesses = function (callbackFunction) {
        callbackFunction(this.enabledProcesses);
    };
    ProcessManagerMock.prototype.getSelectedStage = function () {
        throw new Error("get selected not implemented");
    };
    ProcessManagerMock.prototype.addOnStageChange = function (handler) {
        throw new Error("add on stage change not implemented");
    };
    ProcessManagerMock.prototype.addOnStageSelected = function (handler) {
        throw new Error("add on stage selected not implemented");
    };
    ProcessManagerMock.prototype.removeOnStageChange = function (handler) {
        throw new Error("remove on stage change not implemented");
    };
    ProcessManagerMock.prototype.removeOnStageSelected = function (handler) {
        throw new Error("remove on stage selected not implemented");
    };
    ProcessManagerMock.prototype.moveNext = function (callbackFunction) {
        throw new Error("move next not implemented");
    };
    ProcessManagerMock.prototype.movePrevious = function (callbackFunction) {
        throw new Error("move previous not implemented");
    };
    return ProcessManagerMock;
}());
exports.ProcessManagerMock = ProcessManagerMock;
//# sourceMappingURL=processmanager.mock.js.map


text:
export declare class Log {
    static debug(...args: any[]): void;
    static info(...args: any[]): void;
    static error(...args: any[]): void;
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Course',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('no', models.CharField(max_length=15)),
                ('title', models.CharField(max_length=256)),
                ('credit', models.IntegerField()),
                ('room', models.CharField(max_length=256)),
                ('capacity', models.IntegerField()),
                ('teacher', models.CharField(max_length=256)),
                ('size_limit', models.IntegerField()),
                ('note', models.TextField()),
                ('enrollment', models.IntegerField()),
                ('object', models.CharField(max_length=256)),
                ('syllabus_text', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='Department',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('abbr', models.CharField(max_length=4)),
                ('name_zh', models.CharField(max_length=256)),
                ('name_en', models.CharField(max_length=256)),
            ],
        ),
        migrations.CreateModel(
            name='Semester',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('value', models.CharField(max_length=5)),
                ('year', models.IntegerField()),
                ('section', models.IntegerField()),
                ('name', models.CharField(max_length=256)),
                ('ready', models.BooleanField(default=False)),
            ],
        ),
    ]


text:
using System.Windows;

using FlintSharp.Behaviours;
using FlintSharp.Activities;
using FlintSharp.Counters;
using FlintSharp.Easing;
using FlintSharp.Emitters;
using FlintSharp.EnergyEasing;
using FlintSharp.Initializers;
using FlintSharp.Particles;
using FlintSharp.Zones;

namespace FlintSharp.Behaviours
{
    ///
    /// The DeathOffStage action marks the particle as dead if it is outside the stage.
    /// This action is only reliable when the display region for the swf is exactly the
    /// same size as the swf itself, so that no scaling occurs.
    ///
    ///
Warning: The DeathOffStage action is very slow. A DeathZone action with an appropriate
    /// RectangleZone is more efficient.

    ///
    ///
This renderer uses properties of the stage object. It throws an exception if it is
    /// not in the same security sandbox as the Stage owner (the main SWF file). To avoid
    /// this, the Stage owner can grant permission to the domain containing this renderer
    /// by calling the Security.allowDomain() method or the Security.allowInsecureDomain()
    /// method.

    ///
    public class DeathOffScreen : Behaviour
    {
        private double m_padding;
        private double m_left = double.NaN;
        private double m_right = double.NaN;
        private double m_top = double.NaN;
        private double m_bottom = double.NaN;

        public DeathOffScreen()
        {
            m_padding = 10;
        }

        ///
        /// The constructor creates a DeathOffStage action for use by
        /// an emitter. To add a DeathOffStage to all particles created by an emitter, use the
        /// emitter's addAction method.
        ///
        /// @see org.flintparticles.emitters.Emitter#addAction()
        ///
        /// <param name="padding">An additional distance, in pixels, to add around the stage
        /// to allow for the size of the particles.</param>
        public DeathOffScreen(double padding)
        {
            m_padding = padding;
        }

        ///
        /// An additional distance, in pixels, to add around the stage
        /// to allow for the size of the particles.
        ///
        public double Padding
        {
            get { return m_padding; }
            set { m_padding = value; }
        }

        ///
        /// The getDefaultPriority method is used to order the execution of actions.
        /// It is called within the emitter's addAction method when the user doesn't
        /// manually set a priority. It need not be called directly by the user.
        ///
        /// @see org.flintparticles.common.actions.Action#getDefaultPriority()
        ///
        /// <returns>
Returns a value of -20, so that the DeathOffStage executes after all movement has occured.
</returns>
        public override int GetDefaultPriority()
        {
            return -20;
        }

        ///
        /// The update method is used by the emitter to apply the action
        /// to every particle. It is called within the emitter's update
        /// loop and need not be called by the user.
        ///
        /// <param name="emitter">The Emitter that created the particle.</param>
        /// <param name="particle">The particle to be updated.</param>
        /// <param name="elapsedTime">The duration of the frame - used for time based updates.</param>
        public override void Update(Emitter emitter, Particle particle, double elapsedTime)
        {
            if (emitter == null)
            {
                return;
            }

            if (particle == null)
            {
                return;
            }

            if (double.IsNaN(m_top))
            {
                Point tl = new Point(0, 0);
                Point br = new Point(Utils.ScreenSize.Width, Utils.ScreenSize.Height);
                m_left = tl.X - m_padding;
                m_right = br.X + m_padding;
                m_top = tl.Y - m_padding;
                m_bottom = br.Y + m_padding;
            }

            if (particle.X < m_left || particle.X > m_right || particle.Y < m_top || particle.Y > m_bottom)
                particle.IsDead = true;
        }
    }
}


text:
function toggleCheckboxCell(instance, row, prop, cellProperties) {
  if (Handsontable.helper.stringify(instance.getDataAtCell(row, prop)) === Handsontable.helper.stringify(cellProperties.checkedTemplate)) {
    instance.setDataAtCell(row, prop, cellProperties.uncheckedTemplate);
  }
  else {
    instance.setDataAtCell(row, prop, cellProperties.checkedTemplate);
  }
}

/**
 * Checkbox editor
 * @param {Object} instance Handsontable instance
 * @param {Element} td Table cell where to render
 * @param {Number} row
 * @param {Number} col
 * @param {String|Number} prop Row object property name
 * @param {Object} keyboardProxy jQuery element of keyboard proxy that contains current editing value
 * @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
 */
Handsontable.CheckboxEditor = function (instance, td, row, col, prop, keyboardProxy, cellProperties) {
  if (typeof cellProperties === "undefined") {
    cellProperties = {};
  }
  if (typeof cellProperties.checkedTemplate === "undefined") {
    cellProperties.checkedTemplate = true;
  }
  if (typeof cellProperties.uncheckedTemplate === "undefined") {
    cellProperties.uncheckedTemplate = false;
  }

  keyboardProxy.on("keydown.editor", function (event) {
    var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
    if (!ctrlDown && Handsontable.helper.isPrintableChar(event.keyCode)) {
      toggleCheckboxCell(instance, row, prop, cellProperties);
      event.stopPropagation();
    }
  });

  function onDblClick() {
    toggleCheckboxCell(instance, row, prop, cellProperties);
  }

  var $td = $(td);
  $td.on('dblclick.editor', onDblClick);
  instance.container.find('.htBorder.current').on('dblclick.editor', onDblClick);

  return function () {
    keyboardProxy.off(".editor");
    $td.off(".editor");
    instance.container.find('.htBorder.current').off(".editor");
  }
};


text:
layout: post
title:  "Provisioning Tenant Networks(310-11)"
categories: Linux
tags: RHCA 310
---


text:
String.escape = function strescape(str) {
  return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
// ###expand
// placed this on the String Object as a class method
// designed to be used with the "${}" placeholders like the upcoming
// native string interpolation (ES6).
// Uses the sudo.expandExpression
//
// `param` {string} `str`
// `param` {object} `data`
// `returns` {string}
String.expand = function expand(str, data) {
  return str.replace(window._stringExpandExpression_,
    function(match, key) {return data[key];});
};
// ###_stringExpandExpression_
// The Regular Expression to use to search for delimiters in a String.expand operation.
// Placed on the window object this way so that you can override to taste.
if(!window._stringExpandExpression_) window._stringExpandExpression_ = /\$\{(.+?)\}/g;


text:
include_recipe "python::pip"

python_pip "google-api-python-client" do
  action :upgrade
  version node['python']['google-api-python-client_version']
end


text:
<!DOCTYPE HTML>

        <meta charset="UTF-8">
        <meta http-equiv="refresh" content="1;url=https://docs.google.com/presentation/d/1nwf4R4yJMkmy1GarxHatMAtbVTWdvOwG9OOHEGf4kiI/edit?usp=sharing">

        <title>Opening Ceremony</title>

        If you are not redirected automatically, follow the link to example


text:
package at.arz.ngs.resources.exceptionMapper;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import at.arz.ngs.api.exception.ServiceInstanceNotFound;
import at.arz.ngs.resources.NgsApiError;

@Provider
public class ServiceInstanceNotFoundMapper
		implements ExceptionMapper<ServiceInstanceNotFound> {

	@Override
	public Response toResponse(ServiceInstanceNotFound e) {
		NgsApiError error = new NgsApiError(e.getClass().getSimpleName(), e.getMessage());
		return Response	.status(Response.Status.CONFLICT)
						.type(MediaType.APPLICATION_JSON)
						.type(MediaType.APPLICATION_XML)
						.entity(error)
						.build();
	}

}


text:
<?php

namespace Doctrine\Tests\ORM\Query;

use Doctrine\DBAL\Types\Type as DBALType;

require_once __DIR__ . '/../../TestInit.php';

/**
 * Test case for testing the saving and referencing of query identifiers.
 *
 * @author      Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author      Janne Vanhala <jpvanhal@cc.hut.fi>
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        http://www.phpdoctrine.org
 * @since       2.0
 * @version     $Revision: 13 $
 * @todo        1) [romanb] We  might want to split the SQL generation tests into multiple
 *              testcases later since we'll have a lot of them and we might want to have special SQL
 *              generation tests for some dbms specific SQL syntaxes.
 */
class UpdateSqlGenerationTest extends \Doctrine\Tests\OrmTestCase
{
    private $_em;

    protected function setUp() {
        if (DBALType::hasType('negative_to_positive')) {
            DBALType::overrideType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType');
        } else {
            DBALType::addType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType');
        }

        $this->_em = $this->_getTestEntityManager();
    }

    public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed)
    {
        try {
            $query = $this->_em->createQuery($dqlToBeTested);
            parent::assertEquals($sqlToBeConfirmed, $query->getSql());
            $query->free();
        } catch (\Exception $e) {
            $this->fail($e->getMessage());
        }
    }

    public function testSupportsQueriesWithoutWhere()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1',
            'UPDATE cms_users SET name = ?'
        );
    }

    public function testSupportsMultipleFieldsWithoutWhere()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1, u.username = ?2',
            'UPDATE cms_users SET name = ?, username = ?'
        );
    }

    public function testSupportsWhereClauses()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id = ?2',
            'UPDATE cms_users SET name = ? WHERE id = ?'
        );
    }

    public function testSupportsWhereClausesOnTheUpdatedField()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.name = ?2',
            'UPDATE cms_users SET name = ? WHERE name = ?'
        );
    }

    public function testSupportsMultipleWhereClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.name = ?2 AND u.status = ?3',
            'UPDATE cms_users SET name = ? WHERE name = ? AND status = ?'
        );
    }

    public function testSupportsInClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id IN (1, 3, 4)',
            'UPDATE cms_users SET name = ? WHERE id IN (1, 3, 4)'
        );
    }

    public function testSupportsParametrizedInClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id IN (?2, ?3, ?4)',
            'UPDATE cms_users SET name = ? WHERE id IN (?, ?, ?)'
        );
    }

    public function testSupportsNotInClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.name = ?1 WHERE u.id NOT IN (1, 3, 4)',
            'UPDATE cms_users SET name = ? WHERE id NOT IN (1, 3, 4)'
        );
    }

    public function testSupportsGreatherThanClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id > ?2',
            'UPDATE cms_users SET status = ? WHERE id > ?'
        );
    }

    public function testSupportsGreatherThanOrEqualToClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id >= ?2',
            'UPDATE cms_users SET status = ? WHERE id >= ?'
        );
    }

    public function testSupportsLessThanClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id < ?2',
            'UPDATE cms_users SET status = ? WHERE id < ?'
        );
    }

    public function testSupportsLessThanOrEqualToClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id <= ?2',
            'UPDATE cms_users SET status = ? WHERE id <= ?'
        );
    }

    public function testSupportsBetweenClause()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = ?1 WHERE u.id BETWEEN :from AND :to',
            'UPDATE cms_users SET status = ? WHERE id BETWEEN ? AND ?'
        );
    }

    public function testSingleValuedAssociationFieldInWhere()
    {
        $this->assertSqlGeneration(
            "UPDATE Doctrine\Tests\Models\CMS\CmsPhonenumber p SET p.phonenumber = 1234 WHERE p.user = ?1",
            "UPDATE cms_phonenumbers SET phonenumber = 1234 WHERE user_id = ?"
        );
    }

    public function testSingleValuedAssociationFieldInSetClause()
    {
        $this->assertSqlGeneration(
            "update Doctrine\Tests\Models\CMS\CmsComment c set c.article = null where c.article=?1",
            "UPDATE cms_comments SET article_id = NULL WHERE article_id = ?"
        );
    }

    /**
     * @group DDC-980
     */
    public function testSubselectTableAliasReferencing()
    {
        $this->assertSqlGeneration(
            "UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = 'inactive' WHERE SIZE(u.groups) = 10",
            "UPDATE cms_users SET status = 'inactive' WHERE (SELECT COUNT(*) FROM cms_users_groups c0_ WHERE c0_.user_id = cms_users.id) = 10"
        );
    }

    public function testCustomTypeValueSqlCompletelyIgnoredInUpdateStatements()
    {
        $this->assertSqlGeneration(
            'UPDATE Doctrine\Tests\Models\CustomType\CustomTypeParent p SET p.customInteger = 1 WHERE p.id = 1',
            'UPDATE customtype_parents SET customInteger = 1 WHERE id = 1'
        );
    }
}


text:
using System.Linq.Expressions;
using System.Reflection;
using Veil.Parser;
using Veil.Parser.Nodes;

namespace Veil.Compiler
{
    internal partial class VeilTemplateCompiler<T>
    {
        private static readonly MethodInfo runtimeBindFunction = typeof(Helpers).GetMethod("RuntimeBind");

        private Expression ParseExpression(ExpressionNode node)
        {
            if (node is PropertyExpressionNode) return EvaluateProperty((PropertyExpressionNode)node);
            if (node is FieldExpressionNode) return EvaluateField((FieldExpressionNode)node);
            if (node is SubModelExpressionNode) return EvaluateSubModel((SubModelExpressionNode)node);
            if (node is SelfExpressionNode) return EvaluateSelfExpressionNode((SelfExpressionNode)node);
            if (node is LateBoundExpressionNode) return EvaluateLateBoundExpression((LateBoundExpressionNode)node);
            if (node is CollectionHasItemsExpressionNode) return EvaluateHasItemsNode((CollectionHasItemsExpressionNode)node);
            if (node is FunctionCallExpressionNode) return EvaluateFunctionCall((FunctionCallExpressionNode)node);

            throw new VeilCompilerException("Unknown expression type '{0}'".FormatInvariant(node.GetType().Name));
        }

        private Expression EvaluateFunctionCall(FunctionCallExpressionNode node)
        {
            var model = EvaluateScope(node.Scope);
            return Expression.Call(model, node.MethodInfo);
        }

        private Expression EvaluateHasItemsNode(CollectionHasItemsExpressionNode node)
        {
            var collection = this.ParseExpression(node.CollectionExpression);
            var count = node.CollectionExpression.ResultType.GetCollectionInterface().GetProperty("Count");
            return Expression.NotEqual(Expression.Property(collection, count), Expression.Constant(0));
        }

        private Expression EvaluateLateBoundExpression(LateBoundExpressionNode node)
        {
            var model = EvaluateScope(node.Scope);
            return Expression.Call(null, runtimeBindFunction, new[] {
                model,
                Expression.Constant(node.ItemName),
                Expression.Constant(node.IsCaseSensitive)
            });
        }

        private Expression EvaluateSelfExpressionNode(SelfExpressionNode node)
        {
            return EvaluateScope(node.Scope);
        }

        private Expression EvaluateSubModel(SubModelExpressionNode node)
        {
            var model = ParseExpression(node.ModelExpression);
            PushScope(model);
            var subModel = ParseExpression(node.SubModelExpression);
            PopScope();
            return subModel;
        }

        private Expression EvaluateField(FieldExpressionNode node)
        {
            var model = EvaluateScope(node.Scope);
            return Expression.Field(model, node.FieldInfo);
        }

        private Expression EvaluateProperty(PropertyExpressionNode node)
        {
            var model = EvaluateScope(node.Scope);
            return Expression.Property(model, node.PropertyInfo);
        }

        private Expression EvaluateScope(ExpressionScope scope)
        {
            switch (scope)
            {
                case ExpressionScope.CurrentModelOnStack: return this.modelStack.First.Value;
                case ExpressionScope.RootModel: return this.modelStack.Last.Value;
                case ExpressionScope.ModelOfParentScope: return this.modelStack.First.Next.Value;
                default:
                    throw new VeilCompilerException("Unknown expression scope '{0}'".FormatInvariant(scope));
            }
        }
    }
}


text:
'use strict';

angular.module('myApp.view2', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view2', {
    templateUrl: 'view2/view2.html',
    controller: 'View2Ctrl'
  });
}])

.controller('View2Ctrl', ["$scope", function($scope) {

$scope.bike = {};

$scope.bikes =   JSON.parse(localStorage.getItem('bikes'))
if (!$scope.bikes) {
	$scope.bikes = [];
}

$scope.addBike = function (max){
	$scope.bikes.push(max);
	localStorage.setItem('bikes', JSON.stringify($scope.bikes));
	$scope.bike = {};
}

}]);


text:
package org.apache.solr.search.facet;

import java.io.IOException;
import java.util.Arrays;
import java.util.function.IntFunction;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.solr.common.SolrException;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.function.FieldNameValueSource;

/** {@link AggValueSource} to count values for given {@link ValueSource} */
public class CountValsAgg extends SimpleAggValueSource {

  public CountValsAgg(ValueSource vs) {
    super("countvals", vs);
  }

  @Override
  public SlotAcc createSlotAcc(FacetContext fcontext, long numDocs, int numSlots)
      throws IOException {
    ValueSource vs = getArg();
    if (vs instanceof FieldNameValueSource) {
      String field = ((FieldNameValueSource) vs).getFieldName();
      SchemaField sf = fcontext.qcontext.searcher().getSchema().getField(field);
      if (sf.multiValued() || sf.getType().multiValuedFieldCache()) {
        if (sf.hasDocValues()) {
          if (sf.getType().isPointField()) {
            return new CountSortedNumericDVAcc(fcontext, sf, numSlots);
          }
          return new CountSortedSetDVAcc(fcontext, sf, numSlots);
        }
        if (sf.getType().isPointField()) {
          throw new SolrException(
              SolrException.ErrorCode.BAD_REQUEST,
              "'countvals' aggregation not supported for PointField without docValues");
        }
        return new CountMultiValuedAcc(fcontext, sf, numSlots);
      } else {
        vs = sf.getType().getValueSource(sf, null);
      }
    }
    return new CountValSlotAcc(vs, fcontext, numSlots);
  }

  @Override
  public FacetMerger createFacetMerger(Object prototype) {
    return new FacetModule.FacetLongMerger();
  }

  static class CountValSlotAcc extends SlotAcc.LongFuncSlotAcc {

    public CountValSlotAcc(ValueSource values, FacetContext fcontext, int numSlots) {
      super(values, fcontext, numSlots, 0);
    }

    @Override
    public void collect(int doc, int slot, IntFunction<SlotContext> slotContext)
        throws IOException {
      if (values.exists(doc)) {
        result[slot]++;
      }
    }
  }

  static class CountSortedNumericDVAcc extends DocValuesAcc.LongSortedNumericDVAcc {

    public CountSortedNumericDVAcc(FacetContext fcontext, SchemaField sf, int numSlots)
        throws IOException {
      super(fcontext, sf, numSlots, 0);
    }

    @Override
    protected void collectValues(int doc, int slot) throws IOException {
      result[slot] += values.docValueCount();
    }
  }

  static class CountSortedSetDVAcc extends DocValuesAcc.LongSortedSetDVAcc {

    public CountSortedSetDVAcc(FacetContext fcontext, SchemaField sf, int numSlots)
        throws IOException {
      super(fcontext, sf, numSlots, 0);
    }

    @Override
    protected void collectValues(int doc, int slot) throws IOException {
      while (values.nextOrd() != SortedSetDocValues.NO_MORE_ORDS) {
        result[slot]++;
      }
    }
  }

  static class CountMultiValuedAcc extends UnInvertedFieldAcc {
    private int currentSlot;
    long[] result;

    public CountMultiValuedAcc(FacetContext fcontext, SchemaField sf, int numSlots)
        throws IOException {
      super(fcontext, sf, numSlots);
      result = new long[numSlots];
    }

    @Override
    public void collect(int doc, int slot, IntFunction<SlotContext> slotContext)
        throws IOException {
      this.currentSlot = slot;
      docToTerm.getBigTerms(doc + currentDocBase, this);
      docToTerm.getSmallTerms(doc + currentDocBase, this);
    }

    @Override
    public int compare(int slotA, int slotB) {
      return Long.compare(result[slotA], result[slotB]);
    }

    @Override
    public Object getValue(int slotNum) throws IOException {
      return result[slotNum];
    }

    @Override
    public void reset() throws IOException {
      Arrays.fill(result, 0);
    }

    @Override
    public void resize(Resizer resizer) {
      this.result = resizer.resize(result, 0);
    }

    @Override
    public void call(int termNum) {
      result[currentSlot]++;
    }
  }
}