text:
Poky is using apt version 1.2.24.
Debian 10 apt (1.8.2) does not provide option  `--force-yes` which is required by
_meta/lib/oe/package_manager.py_.

## prelink-native
Poky has its own [prelink-cross](http://git.yoctoproject.org/cgit.cgi/prelink-cross) package.
Debian 10 prelink (0.0.20131005-1+b10) does not support changing root directory
which is required by _meta/classes/image-prelink.bbclass_.

# PACKAGECONFIG variation support

For now, to keep meta-debian minimal and reduce effort of maintenance,
meta-debian only provides recipes to support PACKAGECONFIG features which are enabled by default.
More recipes may be added in future if there are any requests.


text:
"""
The main configuration of the OBSI
"""
import os.path
import socket
from configuration_builder.click_configuration_builder import ClickConfigurationBuilder
import runner.config as runner_config
import control.config as control_config

# The base directory for all OBSI related code
BASE_PATH = os.path.dirname(os.path.realpath(__file__))

OPENBOX_VERSION = '1.0'

class Manager:
    # The number of attempts for checking if a remote REST server is listening
    CONNECTION_RETRIES = 5

    # The interval in seconds between tries for a check if a remote REST server is listening
    INTERVAL_BETWEEN_CONNECTION_TRIES = 1

    # Http client request timeout in seconds
    REQUEST_TIMEOUT = 10

class KeepAlive:
    # The interval in milliseconds between KeepAlive messages
    INTERVAL = 30 * 1000

class OpenBoxController:
    HOSTNAME = "127.0.0.1"
    PORT = 3637
    BASE_URI = "http://{host}:{port}".format(host=HOSTNAME, port=PORT)
    MESSAGE_ENDPOINT_PATTERN = BASE_URI + "/message/{message}"

class Watchdog:
    CHECK_INTERVAL = 1000  # milliseconds

class RestServer:
    DEBUG = False
    PORT = 3636
    BASE_URI = 'http://127.0.0.1:{port}'.format(port=PORT)
    LOG_RECEIVED_MESSAGES = False

    class Endpoints:
        RUNNER_ALERT = '/obsi/runner_alert'
        MESSAGE = '/message/(.*)'

class Engine:
    NAME = 'click'
    CONFIGURATION_BUILDER = ClickConfigurationBuilder
    CONTROL_SOCKET_TYPE = 'TCP'
    CONTROL_SOCKET_ENDPOINT = 10001
    PUSH_MESSAGES_SOCKET_TYPE = 'TCP'
    PUSH_MESSAGES_SOCKET_ENDPOINT = 10002
    PUSH_MESSAGES_CHANNEL = 'openbox'
    NTHREADS = 2
    REQUIREMENTS = ['openbox']
    BASE_EMPTY_CONFIG = r'''{requirements}
ChatterSocket("{push_type}", {push_endpoint}, RETRIES 3, RETRY_WARNINGS false, CHANNEL {channel});
ControlSocket("{control_type}", {control_endpoint}, RETRIES 3, RETRY_WARNINGS false);
alert::ChatterMessage("ALERT", "{test_alert_message}", CHANNEL {channel});
log::ChatterMessage("LOG", "{test_log_message}", CHANNEL {channel});
timed_source::TimedSource(10, "base");
discard::Discard();
timed_source -> alert -> log -> discard;'''.format(
        requirements='\n'.join('require(package "%s")' % package for package in REQUIREMENTS),
        push_type=PUSH_MESSAGES_SOCKET_TYPE,
        push_endpoint=PUSH_MESSAGES_SOCKET_ENDPOINT,
        channel=PUSH_MESSAGES_CHANNEL,
        control_type=CONTROL_SOCKET_TYPE,
        control_endpoint=CONTROL_SOCKET_ENDPOINT,
        test_alert_message=r'{\"message\": \"This is a test alert\",'
                           r' \"origin_block\": \"alert\",'
                           r' \"packet\": \"00 00 00 00\"}',
        test_log_message=r'{\"message\": \"This is a test log\",'
                         r' \"origin_block\": \"log\",'
                         r' \"packet\": \"00 00 00 00\"}'
    )

    class Capabilities:
        MODULE_INSTALLATION = True
        MODULE_REMOVAL = False

class Runner:
    class Rest:
        BIN = os.path.join(BASE_PATH, 'runner', 'rest_server.py')
        DEBUG = True
        PORT = 9001
        BASE_URI = 'http://127.0.0.1:{port}'.format(port=PORT)
        Endpoints = runner_config.RestServer.Endpoints

class Control:
    class Rest:
        BIN = os.path.join(BASE_PATH, 'control', 'rest_server.py')
        DEBUG = True
        PORT = 9002
        BASE_URI = 'http://127.0.0.1:{port}'.format(port=PORT)
        Endpoints = control_config.RestServer.Endpoints

    SOCKET_TYPE = Engine.CONTROL_SOCKET_TYPE
    SOCKET_ADDRESS = (
        '127.0.0.1', Engine.CONTROL_SOCKET_ENDPOINT) if SOCKET_TYPE == 'TCP' else Engine.CONTROL_SOCKET_ENDPOINT

class PushMessages:
    SOCKET_FAMILY = socket.AF_INET if Engine.PUSH_MESSAGES_SOCKET_TYPE == 'TCP' else socket.AF_UNIX
    SOCKET_ADDRESS = (
        '127.0.0.1',
        Engine.PUSH_MESSAGES_SOCKET_ENDPOINT) if Engine.PUSH_MESSAGES_SOCKET_TYPE == 'TCP' else Engine.PUSH_MESSAGES_SOCKET_ENDPOINT
    RETRY_INTERVAL = 1

    class Alert:
        BUFFER_SIZE = 1
        BUFFER_TIMEOUT = 1  # in seconds

    class Log:
        SERVER_ADDRESS = None
        SERVER_PORT = None
        BUFFER_SIZE = 1
        BUFFER_TIMEOUT = 1
        _SERVER_CHANGED = False  # an ugly hack to help with updating

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.2.3.6-3-165-1
description: >
    Object.defineProperty - 'Attributes' is a Function object which
    implements its own [[Get]] method to access the 'writable'
    property of prototype object (8.10.5 step 6.b)
includes: [runTestCase.js]
---*/

function testcase() {
        var obj = {};

        try {
            Function.prototype.writable = true;
            var funObj = function (a, b) {
                return a + b;
            };

            Object.defineProperty(obj, "property", funObj);

            var beforeWrite = obj.hasOwnProperty("property");

            obj.property = "isWritable";

            var afterWrite = (obj.property === "isWritable");

            return beforeWrite === true && afterWrite === true;
        } finally {
            delete Function.prototype.writable;
        }
    }
runTestCase(testcase);


text:
package base.controllers

import base.models.{PermissionBase, UserBase, UserRoleBase, UserSessionBase}
import play.api.Logger
import play.api.mvc.Security.{AuthenticatedBuilder, AuthenticatedRequest}
import play.api.mvc.{ActionBuilder, _}

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.{implicitConversions, postfixOps}
import scala.reflect.ClassTag

trait Secure[S<:UserSessionBase[U], U<:UserBase, R<: UserRoleBase, P<:PermissionBase] extends ControllerBase{

  /***
    *  Constants
    */

  val notAuthorizedPageRedirect: String = "/login"
  val userCachingDuration: Duration  = 5 minutes
  private val idInSession = "id"
  private val logMarkerStart =
    """
      |
      |
      |
      |
      |
    """.stripMargin
  @inline
  private def logStart() = Logger.debug(logMarkerStart)

  /****
    * Secure Actions
    */

  type MRQ[A] = MayBeSecureRequest[A,U]
  type SRQ[A] = SecureRequest[A,U]

  def actionMayBeSecure(action: => MRQ[AnyContent] => Result)(implicit cS: ClassTag[S], cU: ClassTag[U]):EssentialAction ={
    val ab = new ActionBuilder[MRQ,AnyContent] with ActionTransformer[Request, MRQ] {
      override protected def executionContext: ExecutionContext = controllerComponents.executionContext
      override def parser: BodyParser[AnyContent] = controllerComponents.parsers.defaultBodyParser
      def transform[A](request: Request[A]): Future[MayBeSecureRequest[A, U]] = Future.successful {
        logStart()
        new MayBeSecureRequest(getUser(request), request)
      }
    }
    ab(controllerComponents.parsers.defaultBodyParser)(action)
  }
  def actionSecure(action: => SRQ[AnyContent] => Result)(implicit cS: ClassTag[S], cU: ClassTag[U]):EssentialAction = {
    val ab = new ActionBuilder[SRQ,AnyContent] {
      override protected def executionContext: ExecutionContext = controllerComponents.executionContext
      override def parser: BodyParser[AnyContent] = controllerComponents.parsers.defaultBodyParser
      def invokeBlock[A](request: Request[A], block: (SRQ[A]) => Future[Result]): Future[Result] = {
        AuthenticatedBuilder(
          getUser,
          controllerComponents.parsers.defaultBodyParser,
          _ => Redirect(notAuthorizedPageRedirect))(controllerComponents.executionContext)

          .authenticate(request, { authRequest: AuthenticatedRequest[A, U] =>
            logStart()
            block( new SecureRequest[A,U](authRequest.user, request))
          })
      }
    }
    ab(controllerComponents.parsers.defaultBodyParser)(action)
  }

  def actionSecureByRole(roles: Long*)(action: => SRQ[AnyContent] => Result)(implicit cS: ClassTag[S], cU: ClassTag[U]): EssentialAction = {
    actionSecureByPermissions(roles: _*)()(action)
  }

  def actionSecureByPermissions(roles: Long*)(permissions: Long*)(action: => SRQ[AnyContent] => Result)(implicit cS: ClassTag[S], cU: ClassTag[U]): EssentialAction = {
    val ab = new ActionBuilder[SRQ,AnyContent] {
      override protected def executionContext: ExecutionContext = controllerComponents.executionContext
      override def parser: BodyParser[AnyContent] = controllerComponents.parsers.defaultBodyParser
      def invokeBlock[A](request: Request[A], block: (SRQ[A]) => Future[Result]): Future[Result] = {
        AuthenticatedBuilder(getUser(roles: _*)(permissions: _*),
          controllerComponents.parsers.defaultBodyParser,
          _ => Redirect(notAuthorizedPageRedirect))(controllerComponents.executionContext)

          .authenticate(request, { authRequest: AuthenticatedRequest[A, U] =>
            logStart()
            block( new SecureRequest[A,U](authRequest.user, request))
          })
      }
    }
    ab(controllerComponents.parsers.defaultBodyParser)(action)
  }

  def actionSecureWithUser(action: => U => Request[AnyContent] => Result)(implicit cS: ClassTag[S], cU: ClassTag[U]): EssentialAction =
    Security.Authenticated(getUser,  _ => Redirect(notAuthorizedPageRedirect))
    { user => actionMayBeSecure(request => action(user)(request)) }

  /***
    *
    * Helpers
    */
  def initSession(user: U)(implicit cS: ClassTag[S], cU: ClassTag[U]):(String,String) = {
    val sessionClass = cS.runtimeClass
    val userClass = cU.runtimeClass
    val sessionConstructor = sessionClass.getDeclaredConstructor(userClass)
    val us = sessionConstructor.newInstance(user)
    val session:S = us match {
      case s:S => s
      case _ => throw new RuntimeException("unexpected")
    }
    env.userCache.set(session.getIdString,session,userCachingDuration)
    (idInSession,session.getIdString)
  }

  def getSession(request: RequestHeader)(implicit cS: ClassTag[S]): Option[S] = request.session.get(idInSession).flatMap{ id:String =>
    val s:Option[S] = env.userCache.get(id)
    val s2:Option[S]  = s.fold{
      val m = cS.runtimeClass.getDeclaredMethod("restore",classOf[String])
      val resS: Option[S] = m.invoke(null,id) match{case s: S=> Some(s); case _ => None}//= UserSession.restore(id)
      resS.foreach(x=>env.userCache.set(x.getIdString,resS,userCachingDuration))
      resS
    } (x=>Some(x))
    s2
  }

  def getUser(requiredRole: Long*)(requiredPermission: Long*)(request: RequestHeader)(implicit cS: ClassTag[S], cU: ClassTag[U]):Option[U] = {
    val user = getUser(request)
    val userWithRolePass = user.filter {user => requiredRole.exists(user.getRoles.contains(_))}
    val userWithRoleAndPermissionsPass = userWithRolePass.filter{user => user.getPermissions.containsAll(scala.collection.JavaConverters.seqAsJavaList(requiredPermission))}
    userWithRoleAndPermissionsPass
  }

  def getUser(request: RequestHeader)(implicit cS: ClassTag[S]):Option[U] = {
    getSession(request).flatMap{s2 => Option(s2.getUser)}
  }

}

class SecureRequest[A, U<:UserBase](val user: U, request: Request[A]) extends WrappedRequest[A](request)

class MayBeSecureRequest[A, U<:UserBase](val user: Option[U], request: Request[A]) extends WrappedRequest[A](request)

object RequestWrapperForTemplates{
  class GenericRequest[A](request: Request[A]){
    def getUser:Option[UserBase] = request match {
      case sr:SecureRequest[A,_] => Some(sr.user)
      case mr:MayBeSecureRequest[A,_] => mr.user
      case _ => None
    }
  }
  implicit def requestToGenericRequest[A](request: Request[A]):GenericRequest[A] = new GenericRequest[A](request)
}


text:
import gtk
import gobject

from .. import gui
from ..lib import contrast
from ..helper import color as hcolor
from ..typecheck import types

class ColorDialog(object):

	""" show the available contrast colors as colored buttons
		and show a textfield with text foreground colored in
		the selected color.
	"""

	def __init__(self):
		self.builder = gui.builder.load_dialog("contrast")

		self._setup_text_tag()

		self.builder.connect_signals(self)

		self._colors = (None,None)

	def __getattr__(self, attr):
		if attr in ("builder", "color_tag", "_colors"
					"_setup_text_tag", "set_example_color",
					"get_current_color", "show_all",
					"set_current_rgb_color",
					"set_current_contrast_color",
					"contrast_color_table_color_changed",
					"colorselection_color_changed"):
			# public attributes of this object
			return super(ColorDialog,self).__getattr__(attr)
		else:
			return getattr(self.builder.get_object("contrast_dialog"), attr)

	def show_all(self):
		# FIXME:  for a reason i don't know yet, show_all() does not
		# FIXME:: apply show for the contrast_color_table, so this fixes it
		self.builder.get_object("contrast_dialog").show_all()
		self.builder.get_object("contrast_color_table").show_all()

	def _setup_text_tag(self):
		buffer = self.builder.get_object("example_text_view").get_buffer()

		self.color_tag = buffer.create_tag()

		buffer.apply_tag(self.color_tag, buffer.get_start_iter(),
			buffer.get_end_iter())

	def set_example_color(self, color):
		self.color_tag.set_property("foreground", color)

	def set_current_rgb_color(self, color):
		self.builder.get_object("colorselection").set_current_color(color)

	@types(color_code=int)
	def set_current_contrast_color(self, color_code):
		""" take a contrast color number and behave as if the specific
			color is selected.
		"""
		table = self.builder.get_object("contrast_color_table")

		button = table.get_button_by_code(color_code)
		button.clicked()

	def get_current_color(self):
		""" return a tuple with two values like this:
				(<gtk.gdk.Color()>,<contrast color code>).

			If a color is set by the colorselection, no contrast color
			is set:
				(<gtk.gdk.Color(...)>, None).

			If a contrast color is used, the first value is the RGB
			representation of the contrast color and the second value
			is the contrast color code:
				(<gtk.gdk.Color(...), <contrast color code>).

			Default is (None, None).
		"""
		return self._colors

	def contrast_color_table_color_changed(self, table, color_code):
		color = contrast.contrast_render_foreground_color(
					hcolor._get_output_bg_color(), color_code)

		# set the colorselection to the contrast color
		self.builder.get_object("colorselection").set_current_color(color)

		self._colors = (color, color_code)

		self.set_example_color(color)

	def colorselection_color_changed(self, selection):
		color = selection.get_current_color()

		self._colors = (color, None)

		self.set_example_color(color)

def setup():pass

def run(parent=None):
	d = ColorDialog()

	if parent:
		d.set_transient_for(parent)

	d.show_all()
	return d


text:
/**
 * mui.init pulldownRefresh
 * @param {type} $
 * @returns {undefined}
 */
(function($) {
	$.registerInit({
		name: 'pullrefresh',
		index: 1000,
		handle: function() {
			var options = $.options;
			var pullRefreshOptions = options.pullRefresh || {};
			var hasPulldown = pullRefreshOptions.down && pullRefreshOptions.down.hasOwnProperty('callback');
			var hasPullup = pullRefreshOptions.up && pullRefreshOptions.up.hasOwnProperty('callback');
			if (hasPulldown || hasPullup) {
				var container = pullRefreshOptions.container;
				if (container) {
					var $container = $(container);
					if ($container.length === 1) {
						if ($.os.plus && $.os.android) { //android 5+
							$.plusReady(function() {
								var webview = plus.webview.currentWebview();
								if (hasPullup) {
									//当前页面初始化pullup
									var upOptions = {};
									upOptions.up = pullRefreshOptions.up;
									upOptions.webviewId = webview.id || webview.getURL();
									$container.pullRefresh(upOptions);
								}
								if (hasPulldown) {
									var parent = webview.parent();
									var id = webview.id || webview.getURL();
									if (parent) {
										if (!hasPullup) { //如果没有上拉加载,需要手动初始化一个默认的pullRefresh,以便当前页面容器可以调用endPulldownToRefresh等方法
											$container.pullRefresh({
												webviewId: id
											});
										}
										var downOptions = {
											webviewId: id
										};
										downOptions.down = $.extend({}, pullRefreshOptions.down);
										downOptions.down.callback = '_CALLBACK';
										//父页面初始化pulldown
										parent.evalJS("mui&&mui(document.querySelector('.mui-content')).pullRefresh('" + JSON.stringify(downOptions) + "')");
									}
								}
							});
						} else {
							$container.pullRefresh(pullRefreshOptions);
						}
					}
				}
			}
		}
	});
})(mui);


text:
using Fidget.Commander;
using Fidget.Extensions.Reflection;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Fidget.Validation.Addresses.Metadata.Commands
{
    public class CountryMetadataQueryTests
    {
        FakeContext FakeContext = new FakeContext();

        IMetadataQueryContext context => FakeContext;
        ICommandHandler<CountryMetadataQuery,CountryMetadata> instance => new CountryMetadataQuery.Handler( context );

        public class For
        {
            AddressData address;
            CountryMetadataQuery invoke() => CountryMetadataQuery.For( address );

            static string random() => Convert.ToBase64String( Guid.NewGuid().ToByteArray() );

            [Fact]
            public void Requires_address()
            {
                address = null;
                Assert.Throws<ArgumentNullException>( nameof(address), ()=>invoke() );
            }

            public static IEnumerable<object[]> QueryCases()
            {
                var countries = new string[] { null, random() };
                var provinces = new string[] { null, random() };
                var localities = new string[] { null, random() };
                var sublocalities = new string[] { null, random() };
                var languages = new string[] { null, random() };

                return
                    from country in countries
                    from province in provinces
                    from locality in localities
                    from sublocality in sublocalities
                    from language in languages
                    select new object[] { new AddressData
                    {
                        Country = country,
                        Province = province,
                        Locality = locality,
                        Sublocality = sublocality,
                        Language = language
                    }};
            }

            [Theory]
            [MemberData(nameof(QueryCases))]
            public void Returns_query( AddressData address )
            {
                var expected = new CountryMetadataQuery
                {
                    Country = address.Country,
                    Language = address.Language,
                };

                this.address = address;
                var actual = invoke();
                Assert.Equal( expected, actual );
            }
        }

        public class Constructor : CountryMetadataQueryTests
        {
            [Fact]
            public void Requires_context()
            {
                FakeContext = null;
                Assert.Throws<ArgumentNullException>( nameof(context), ()=>instance );
            }

            [Fact]
            public void IsRegistered()
            {
                var actual = DependencyInjection.Container.GetInstance<ICommandHandler<CountryMetadataQuery, CountryMetadata>>();
                Assert.IsType<CountryMetadataQuery.Handler>( actual );
            }
        }

        public class Handle : CountryMetadataQueryTests
        {
            CountryMetadataQuery command = new CountryMetadataQuery { Country = "XW", Language = "en" };
            CancellationToken cancellationToken = CancellationToken.None;

            Task<CountryMetadata> invoke() => instance.Handle( command, cancellationToken );

            /// <summary>
            /// Cases where the country should not be matched.
            /// </summary>

            public static IEnumerable<object[]> NotMatchedCases()
            {
                var global = new GlobalMetadata();
                var key = "XW";

                // no global metadata
                yield return new object[] { null, null, null };

                // no key returned
                yield return new object[] { global, null, null };

                // no identifier returned
                yield return new object[] { global, key, null };
            }

            [Theory]
            [MemberData(nameof(NotMatchedCases))]
            public async Task WhenNotMatched_returns_null( GlobalMetadata global, string key, string id )
            {
                FakeContext.MockDispatcher.Setup( _=> _.Execute( GlobalMetadataQuery.Default, cancellationToken ) ).ReturnsAsync( global );
                FakeContext.MockBuilder.Setup( _=> _.GetChildKey( global, command.Country ) ).Returns( key );
                FakeContext.MockBuilder.Setup( _=> _.BuildIdentifier( global, key, command.Language ) ).Returns( id );

                var actual = await invoke();
                Assert.Null( actual );

                var getChildKeyTimes = global != null ? Times.Once() : Times.Never();
                var buildIdentifierTimes = key != null ? Times.Once() : Times.Never();
                FakeContext.MockDispatcher.Verify( _ => _.Execute( GlobalMetadataQuery.Default, cancellationToken ), Times.Once );
                FakeContext.MockBuilder.Verify( _ => _.GetChildKey( global, command.Country ), getChildKeyTimes );
                FakeContext.MockBuilder.Verify( _=> _.BuildIdentifier( global, key, command.Language ), buildIdentifierTimes );

                FakeContext.MockClient.Verify( _=> _.Query<CountryMetadata>( It.IsAny<string>() ), Times.Never );
            }

            /// <summary>
            /// Cases where the country is matched.
            /// </summary>

            public static IEnumerable<object[]> MatchedCases()
            {
                var global = new GlobalMetadata();
                var key = "XW";
                var id = "data/XW--en";

                yield return new object[] { global, key, id, null };
                yield return new object[] { global, key, id, new CountryMetadata() };
            }

            [Theory]
            [MemberData(nameof(MatchedCases))]
            public async Task WhenMatched_returns_clientResponse( GlobalMetadata global, string key, string id, CountryMetadata response )
            {
                FakeContext.MockDispatcher.Setup( _ => _.Execute( GlobalMetadataQuery.Default, cancellationToken ) ).ReturnsAsync( global ).Verifiable();
                FakeContext.MockBuilder.Setup( _ => _.GetChildKey( global, command.Country ) ).Returns( key ).Verifiable();
                FakeContext.MockBuilder.Setup( _ => _.BuildIdentifier( global, key, command.Language ) ).Returns( id ).Verifiable();
                FakeContext.MockClient.Setup( _ => _.Query<CountryMetadata>( id ) ).ReturnsAsync( response ).Verifiable();

                var actual = await invoke();
                Assert.Equal( response, actual );

                FakeContext.MockDispatcher.VerifyAll();
                FakeContext.MockBuilder.VerifyAll();
                FakeContext.MockClient.VerifyAll();
            }
        }
    }
}


text:
/*
* (C) 2015 Key Zhang
* @btree.h
* @Created on 2015/10/19
*/
#ifndef _BTREE_H
#define _BTREE_H

#include "global.h"
#include "MiniSQL.h"
//offset in head block
#define BLOCKCOUNT      0 // 4byte: block number in index
#define NODESIZE        4 // 4byte: the size of one node
#define ROOTPTR         8 // 4byte: Root block
#define HEADPTR         12// 4byte: head block
#define DATATYPE        16// 1byte: datatype 0:int 2:float 1:char
#define TABLENAME       17// 256byte: table name
//offset in block
#define ENTRYCOUNT      0 // 4byte: count the number of entries in one block 0xFFFFFFFF >> empty block
#define PARENTBLOCK     4 // 4byte: the parent block number (0xFFFFFFFF for root)
#define NEXTBLOCK       8 // 4byte: the next block number (0xFFFFFFFE for non leaf 0xFFFFFFFF for leaf without next block)
#define DATAHEAD        12// begin of node data

#define ROOTMARK 0xFFFFFFFF
#define NONLEAFMARK 0xFFFFFFFE
#define NONEXT 0xFFFFFFFF
#define EMPTYBLOCK 0x0
#include <set>
#include <io.h>
using namespace std;
/********************/
/* Public Functions */
/********************/

/* create index on table */
bool btree_create(
    const char* tablename,  // table name
    const char *,           // index name
    column *col             // column to build index
    );
/* insert data into index */
bool btree_insert(
    const char *,        // index name
    Data* i,             // Data to insert
    u32 value            // value(blocknum)
    );
/* get tablename from index name */
const char* btree_getTable( // NULL: index not exist
    const char* idxname     // index name
);
/* delete a data entry in index */
u32 btree_delete_node(      // 0: not deleted 1:deleted
    const char *,           // index name
    Data *                  // data to delete (for once)
    );
set<u32> btree_select(
    const char *,   // index name
    Rule *        // Filter
    );

/***********/
/* Private */
class node
{
public:
    u32 parent;   // 4 byte
    /* The first 2 block is to store block info */
    Data *datas;
    u32 *childs;
    u32 N;
    u32 nodeNo;     // 4 byte
    u32 next;
    node()
    {
        datas = NULL;
        childs = NULL;
    }
};
//typedef struct node node;
//static node *allocNode(u32 N);
struct btree
{
    Buffer buf;
    dataType type;
    u8 nodeSize;
    u16 capacity;
    u32 root;
    u32 blockcount;
    u32 head;
};
typedef struct btree btree;

static bool getBtree(btree*, const char *);                 // get btree from index name
static void saveBtree(btree*);                              // save btree info

static void getNode(btree*,node * ,u32 block);              // get node from blocknum
static void newNode(btree*, node *);                        // alloc new node
static void freeNode(btree*, node *);                       // recycle mem
static void saveNode(btree*, node *);                       // save node info

static void findNode(btree*, node*, Data*);                 // find node through btree by data
static void splitNode(btree*, node*source,node*dst);        // split node into 2 by half

static i8 cmp(dataType type, Data sourse,Data target);      // compare 2 data in 3type
static void datacpy(btree* bt, Data *dst, Data *source);    // copy data

// insert data into node by index
static void insertData(btree*,node *nd, u32 index, Data* target, u32 value);
// insert node into nonleaf node
static void insertNonleaf(btree*, node*, u32 parent);

static void deleteData(btree*, node *nd, u32 index);        // delete data in node
static void deleteNonleaf(btree*,Data*, u32 parent);        // delete node in nonleaf
static void refreshBlock(btree*);                           // refresh the linked list to remove empty leaf nodes
static void refreshParents(btree* bt,Data *data,u32 parent,u32 offset); // refresh keys in parent nodes after change

#endif // _BTREE_H


text: * https://www.howtoforge.com/how-to-install-sonarqube-on-ubuntu-1804/


text:
'use strict';

/**
* While a test condition is true, invoke a function once for each element in a collection.
*
* @module @stdlib/utils/do-while-each
*
* @example
* var doWhileEach = require( '@stdlib/utils/do-while-each' );
*
* function predicate( v, index, collection ) {
*     return ( v === v );
* }
*
* function log( v, index, collection ) {
*     console.log( '%s: %d', index, v );
* }
*
* var arr = [ 1, 2, 3, 4, NaN, 5 ];
*
* doWhileEach( arr, log, predicate );
*/

// MODULES //

var main = require( './main.js' );

// EXPORTS //

module.exports = main;


text:
require 'active_model_serializers'

module Api
  class BalancesController < ApplicationController
    before_action :authenticate_user!

    def index
      balances = current_user.balances
      render json: ActiveModel::Serializer::CollectionSerializer.new(
        balances, serializer: BalanceSerializer
      )
    end
  end
end


text:
<?php
use PHPUnit\Framework\TestCase;

/**
 * @covers Email
 */
final class EmailTest extends TestCase
{
    public function testCreateModel(): void
    {
        $client = new Client();
        foreach (Client::FIELDS as $key => $value) {
            $client->$key = 'a@b.com';
        }
        $client->save();
        $this->assertInstanceOf(
            Email::class,
            Email::fromString('user@example.com')
        );
    }

    public function testCannotBeCreatedFromInvalidEmailAddress(): void
    {
        $this->expectException(InvalidArgumentException::class);

        Email::fromString('invalid');
    }

    public function testCanBeUsedAsString(): void
    {
        $this->assertEquals(
            'user@example.com',
            Email::fromString('user@example.com')
        );
    }
}


text:
extern crate lzf;
use std::io::{self, Read, Write};

fn main() {
    let mut contents: Vec<u8> = Vec::new();
    let _ = io::stdin().read_to_end(&mut contents).unwrap();

    let compressed = lzf::compress(&contents[..]).unwrap();
    let _ = io::stdout().write_all(&compressed[..]).unwrap();
}


text:
std::vector<int> stringToDigits (std::string stringDigits) {
    // Converts a string of digits (e.g. "2,0,2,3,4") to a array of integers

    std::vector<int> numbers;

    std::stringstream ss(stringDigits);

    int digit;
    // while each character is insert as a digit from the string
    while(ss >> digit) {
        numbers.push_back(digit);

        if(ss.peek() == ',') {
            ss.ignore();
        }
    }

    return numbers;
}

struct node * buildTree(std::vector<int> numbers) {

    // Initialize tree root
    struct node *root = new struct node();
    int index = 0;

    // Build the tree
    build(numbers, index, root);

    return root;
}

void build(std::vector<int> numbers, int index,
        struct node *currentNode) {

    currentNode->value = numbers[index];
    int size = numbers.size();

    // If left child exists, build it
    int newIndex = 2 * index + 1;
    if (newIndex < size) {
        currentNode->leftChild = new struct node();

        build(numbers, newIndex, currentNode->leftChild);
    } else {
        currentNode->leftChild = NULL;
    }

    newIndex++;
    // If right child exists, build it
    if (newIndex < size) {
        currentNode->rightChild = new struct node();

        build(numbers, newIndex, currentNode->rightChild);
    } else {
        currentNode->rightChild = NULL;
    }

}

void invertTree(struct node *currentNode) {
    // Inverts any given binary tree
    if(currentNode != NULL) {
        struct node *temp;
        temp = currentNode->leftChild;
        currentNode->leftChild = currentNode->rightChild;
        currentNode->rightChild = temp;
        invertTree(currentNode->leftChild);
        invertTree(currentNode->rightChild);
    }

}

void print(struct node *node) {
    // Pre Order Traversal of any binary tree
    std::cout << node->value << std::endl;

    if(node->leftChild != NULL) {
        print(node->leftChild);
    }

    if(node->rightChild != NULL) {
        print(node->rightChild);
    }
}


text:
using UnityEngine;
using System.Collections;

public class Gauge : MonoBehaviour {

	[SerializeField]
	private tk2dSprite m_gaugeBack;

	[SerializeField]
	private tk2dSprite m_gauge;

	[SerializeField]
	private float m_animLengthSec = 1.0f;

	[SerializeField]
	private float m_prePostAnimIntervalSec = .5f;

	[SerializeField]
	private bool m_animating = false;

	public bool IsAnimating {
		get { return m_animating; }
	}

	void Start() {
		m_gaugeBack.renderer.enabled = false;
		m_gauge.renderer.enabled = false;
		SetGaugeValue(1.0f);
	}

	// gauge value: [0.0-1.0]
	// set value immediately
	public void SetGaugeValue(float v) {
		m_gauge.transform.localScale = new Vector3(v, 1.0f,1.0f);
	}

	// gauge value: [0.0-1.0]
	public void ApplyGaugeValueTo(float from, float to) {
		m_animating = true;
		StartCoroutine(_ApplyGaugeAnim(from, to));
	}

	private static float _easeOut(float v) {
		float sv = 1.0f - Mathf.Sin (Mathf.PI/2.0f * v);
		return 1.0f - (sv*sv);
	}

	private IEnumerator _ApplyGaugeAnim(float fromValue, float toValue) {

		toValue = Mathf.Clamp01(toValue);

		m_gauge.transform.localScale = new Vector3(fromValue, 1.0f,1.0f);
		m_gaugeBack.renderer.enabled = true;
		m_gauge.renderer.enabled = true;

		yield return new WaitForSeconds(m_prePostAnimIntervalSec);

		float tNow = Time.time;

		while( Time.time - tNow < m_animLengthSec ) {
			float rate = Time.time - tNow;
			float easedRate = _easeOut(rate);
			float curValue = Mathf.Lerp (fromValue, toValue, easedRate);
			m_gauge.transform.localScale = new Vector3(curValue, 1.0f, 1.0f);
			yield return new WaitForEndOfFrame();
		}

		m_gauge.transform.localScale = new Vector3(toValue, 1.0f,1.0f);

		yield return new WaitForSeconds(m_prePostAnimIntervalSec);

		m_gaugeBack.renderer.enabled = false;
		m_gauge.renderer.enabled = false;
		m_animating = false;
	}
}


text:
'use strict';

app.controller('AuthCtrl', function($scope, $location, Auth, currentAuth){

  if(currentAuth){
    $location.path('/');
  }

  $scope.login = function(email, pass){
    Auth.$authWithPassword({
      email: email,
      password: pass
    })
      .then(function(){
        $location.path('/');
      })
      .catch(function(err){
        console.log(err);
      });
  };

  $scope.register = function(username, email, pass){

    Auth.$createUser({
      email: email,
      password: pass
    })
      // Build user profile
      .then(function(authData){
        Auth.createProfile(username, authData);
      })
      // Login
      .then(function(){
        $scope.login(email, pass);
      })
      .catch(function(err){
        console.log(err);
      });
  };

});


text:
namespace MoreLinq.Test
{
    using NUnit.Framework;

    [TestFixture]
    public class ConsumeTest
    {
        [Test]
        public void ConsumeReallyConsumes()
        {
            var counter = 0;
            var sequence = Enumerable.Range(0, 10).Pipe(x => counter++);
            sequence.Consume();
            Assert.AreEqual(10, counter);
        }
    }
}


text:
> Run grunt tasks concurrently

---

🔥 Want to strengthen your core JavaScript skills and master ES6?
I would personally recommend this awesome ES6 course by Wes Bos.

---

Running slow tasks like Coffee and Sass concurrently can potentially improve your build time significantly. This task is also useful if you need to run [multiple blocking tasks](#logconcurrentoutput) like `nodemon` and `watch` at once.

## Install

```
$ npm install --save-dev grunt-concurrent
```

## Usage

```js
require('load-grunt-tasks')(grunt); // npm install --save-dev load-grunt-tasks

grunt.initConfig({
	concurrent: {
		target1: ['coffee', 'sass'],
		target2: ['jshint', 'mocha']
	}
});

// tasks of target1 run concurrently, after they all finished, tasks of target2 run concurrently,
// instead of target1 and target2 run concurrently.
grunt.registerTask('default', ['concurrent:target1', 'concurrent:target2']);
```

## Sequential tasks in concurrent target

```js
grunt.initConfig({
	concurrent: {
		target: [['jshint', 'coffee'], 'sass']
	}
});
```
Now `jshint` will always be done before `coffee` and `sass` runs independent of both of them.

## Options

### limit

Type: `number`

Default: Twice the number of CPU cores with a minimum of 2

Limit how many tasks that are run concurrently.

### logConcurrentOutput

Type: `boolean`

Default: `false`

You can optionally log the output of your concurrent tasks by specifying the `logConcurrentOutput` option. Here is an example config which runs [grunt-nodemon](https://github.com/ChrisWren/grunt-nodemon) to launch and monitor a node server and [grunt-contrib-watch](https://github.com/gruntjs/grunt-contrib-watch) to watch for asset changes all in one terminal tab:

```js
grunt.initConfig({
	concurrent: {
		target: {
			tasks: ['nodemon', 'watch'],
			options: {
				logConcurrentOutput: true
			}
		}
	}
});

grunt.loadNpmTasks('grunt-concurrent');
grunt.registerTask('default', ['concurrent:target']);
```

*The output will be messy when combining certain tasks. This option is best used with tasks that don't exit like `watch` and `nodemon` to monitor the output of long-running concurrent tasks.*

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.Glue.SaveClasses;

namespace FlatRedBall.Glue
{
    /// <summary>
    /// Stores information about actions to perform - such as reloading the project, saving out .csproj files, and regenerating code files.
    /// </summary>
    public class QueuedActionManager
    {
        QueuedActionManager mSelf;

        public QueuedActionManager Self
        {
            get
            {
                if (mSelf == null)
                {
                    mSelf = new QueuedActionManager();
                }
                return mSelf;
            }
        }

        bool ShouldSaveCodeProjects
        {
            get;
            set;
        }

        bool ShouldSaveGlux
        {
            get;
            set;
        }

        bool ShouldReloadGlux
        {
            get;
            set;
        }

        List<IElement> ElementsToGenerate
        {
            get;
            set;
        }

        List<ReferencedFileSave> CsvsToRegenerate
        {
            get;
            set;
        }

        List<ReferencedFileSave> FilesToUpdateProjectMembershipOn
        {
            get;
            set;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="lt.lemonlabs.android.samples.expandablebuttonmenu"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="21"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/app_theme">
        <activity
            android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.HomeActivity"
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <activity
            android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.ExpandableActivity"/>
        <activity android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.ZKLActivity" />
        <activity android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.ZoneActivity" />
        <activity android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.AddDreamActivity" />
        <activity android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.LoginActivity" />
        <activity android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.EditTimeActivity"
            android:theme="@android:style/Theme.Translucent"/>
        <activity android:name="lt.lemonlabs.android.samples.expandablebuttonmenu.CalendarActivity"
          android:theme="@style/Theme.AppCompat.NoActionBar"
            />
    </application>

</manifest>


text:
cask 'shotcut' do
  version '18.03.06'
  sha256 'ee30e49bd6ef83c9fda20b194641d45aee5ba728edc742ca2935fe5f89ceec25'

  # github.com/mltframework/shotcut was verified as official when first introduced to the cask
  url "https://github.com/mltframework/shotcut/releases/download/v#{version.major_minor}/shotcut-osx-x86_64-#{version.no_dots}.dmg"
  appcast 'https://github.com/mltframework/shotcut/releases.atom',
          checkpoint: '30ad666d17c17c714d28555d84b9ef7f3c7250809a46542b805a1213b79ac292'
  name 'Shotcut'
  homepage 'https://www.shotcut.org/'

  app 'Shotcut.app'
end


text:
package looli

import (
	"net/http"
	"os"
	"path"
	"strings"
)

var (
	default404Body = "404 page not found\n"
	default405Body = "405 method not allowed\n"
)

// RouterPrefix is used internally to configure router, a RouterPrefix is associated with a basePath
// and an array of handlers (middleware)
type RouterPrefix struct {
	basePath    string
	router      *Router
	Middlewares []HandlerFunc
	engine      *Engine
	allNoRoute  []HandlerFunc
	allNoMethod []HandlerFunc
	isPrefix    bool
}

// Use adds middleware to the router.
func (p *RouterPrefix) Use(middleware ...HandlerFunc) {
	if len(middleware) == 0 {
		panic("there must be at least one middleware")
	}

	p.Middlewares = append(p.Middlewares, middleware...)
}

// Use adds handlers as middleware to the router.
func (p *RouterPrefix) UseHandler(handlers ...Handler) {
	var middlwares []HandlerFunc
	for _, handler := range handlers {
		middlwares = append(middlwares, handler.Handle)
	}
	p.Use(middlwares...)
}

// Get is a shortcut for router.Handle("GET", path, handle)
func (p *RouterPrefix) Get(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodGet, pattern, handlers...)
}

// Post is a shortcut for router.Handle("Post", path, handle)
func (p *RouterPrefix) Post(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodPost, pattern, handlers...)
}

// Put is a shortcut for router.Handle("Put", path, handle)
func (p *RouterPrefix) Put(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodPut, pattern, handlers...)
}

// Delete is a shortcut for router.Handle("DELETE", path, handle)
func (p *RouterPrefix) Delete(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodDelete, pattern, handlers...)
}

// Head is a shortcut for router.Handle("HEAD", path, handle)
func (p *RouterPrefix) Head(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodHead, pattern, handlers...)
}

// Options is a shortcut for router.Handle("OPTIONS", path, handle)
func (p *RouterPrefix) Options(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodOptions, pattern, handlers...)
}

// Patch is a shortcut for router.Handle("PATCH", path, handle)
func (p *RouterPrefix) Patch(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodPatch, pattern, handlers...)
}

// Any registers a route that matches all the HTTP methods.
// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE
func (p *RouterPrefix) Any(pattern string, handlers ...HandlerFunc) {
	p.Handle(http.MethodGet, pattern, handlers...)
	p.Handle(http.MethodPost, pattern, handlers...)
	p.Handle(http.MethodPut, pattern, handlers...)
	p.Handle(http.MethodDelete, pattern, handlers...)
	p.Handle(http.MethodHead, pattern, handlers...)
	p.Handle(http.MethodOptions, pattern, handlers...)
	p.Handle(http.MethodPatch, pattern, handlers...)
	p.Handle(http.MethodTrace, pattern, handlers...)
	p.Handle(http.MethodConnect, pattern, handlers...)
}

// Handle registers a new request handle and middleware with the given path and method.
func (p *RouterPrefix) Handle(method, pattern string, handlers ...HandlerFunc) {
	if len(handlers) == 0 {
		panic("there must be at least one handler")
	}

	if p.basePath != "" {
		pattern = p.basePath + pattern
	}

	if p.isPrefix {
		handlers = p.combineHandlers(handlers)
	}

	p.router.Handle(method, pattern, handlers)
}

// StaticFile register router pattern and response file in path
func (p *RouterPrefix) StaticFile(pattern, filepath string) {
	if strings.Contains(pattern, ":") || strings.Contains(pattern, "*") {
		panic("URL parameters can not be used when serving a static folder")
	}

	handler := func(c *Context) {
		c.ServeFile(filepath)
		if _, err := os.Stat(filepath); os.IsNotExist(err) {
			c.statusCode = http.StatusNotFound
		}
	}

	p.Head(pattern, handler)
	p.Get(pattern, handler)
}

// Static register router pattern and response file in the request url
func (p *RouterPrefix) Static(pattern, dir string) {
	if strings.Contains(pattern, ":") || strings.Contains(pattern, "*") {
		panic("URL parameters can not be used when serving a static folder")
	}

	fileServer := http.StripPrefix(pattern, http.FileServer(http.Dir(dir)))
	handler := func(c *Context) {
		fileServer.ServeHTTP(c.ResponseWriter, c.Request)
		if _, err := os.Stat(path.Join(dir, c.Param("filepath"))); os.IsNotExist(err) {
			c.statusCode = http.StatusNotFound
		}
	}

	urlPattern := path.Join(pattern, "/*filepath")
	p.Head(urlPattern, handler)
	p.Get(urlPattern, handler)
}

// combine middleware and handlers for specific route
func (p *RouterPrefix) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
	finalSize := len(p.Middlewares) + len(handlers)
	if finalSize >= int(abortIndex) {
		panic("too many handlers")
	}
	mergedHandlers := make([]HandlerFunc, finalSize)
	copyHandlers(mergedHandlers, p.Middlewares)
	copyHandlers(mergedHandlers[len(p.Middlewares):], handlers)
	return mergedHandlers
}

// copy handlers
func copyHandlers(dst, src []HandlerFunc) {
	for index, val := range src {
		dst[index] = val
	}
}

// compose global middleware for all request
func (p *RouterPrefix) composeMiddlewares() func(http.ResponseWriter, *http.Request) {
	return func(rw http.ResponseWriter, req *http.Request) {
		context := NewContext(p, rw, req)
		httpHandler := func(c *Context) {
			p.router.handleRequest(c)
		}

		handlers := p.combineHandlers([]HandlerFunc{httpHandler})
		context.handlers = handlers
		context.Next()
	}
}

// Prefix creates a new router prefix. You should add all the routes that have common
// middlwares or the same path prefix. For example, all the routes that use a common
// middlware could be grouped.
func (p *RouterPrefix) Prefix(basePath string) *RouterPrefix {
	return &RouterPrefix{
		basePath: basePath,
		router:   p.router,
		engine:   p.engine,
		isPrefix: true,
	}
}

func (p *RouterPrefix) handleRequest(rw http.ResponseWriter, req *http.Request) {
	handler := p.composeMiddlewares()
	handler(rw, req)
}


text:
package main

import (
	"errors"
	"fmt"
	"net/http"
	"regexp"
	"strconv"
	"strings"
)

var (
	urlRegex         = regexp.MustCompile("^/([0-9]{1,2})(/(.+))?(/(ttl|type))?")
	querystringRegex = regexp.MustCompile(`(\?.*)$`)
)

func startHttp(listenAddr string) {
	// URL-to-handler func mappings
	//
	http.HandleFunc("/info", GetInformation)
	http.HandleFunc("/favicon.ico", Favicon)
	http.HandleFunc("/", DispatchRequest)

	// Start listening for requests
	//
	println("Scarlet HTTP listening on", listenAddr)
	panic(http.ListenAndServe(listenAddr, nil))
	return
}

func GetInformation(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Set("Content-Type", "application/json")
	var response R
	config, _ := LoadConfig(*configPath)
	if config.Redis.InfoDisabled() {
		e := "Retrieving node information has been disabled."
		response = R{"result": nil, "error": e}
		fmt.Fprint(rw, response)
		return
	}
	println("INFO")
	redisClient, err := Database.DB(0)
	info, err := GetHostInfo(redisClient)
	response = R{"result": info, "error": err}
	fmt.Fprint(rw, response)
	return
}

type RequestInfo struct {
	DbNum int
	Key   string
}

func GetRequestInfo(r *http.Request) (ri *RequestInfo, err error) {
	url := querystringRegex.ReplaceAllString(r.URL.String(), "")
	m := urlRegex.FindStringSubmatch(url)
	if m == nil {
		err = errors.New("Malformed URL")
		return
	}
	dbnum, e := strconv.Atoi(strings.TrimLeft(m[1], "/"))
	if err != nil {
		err = e
		return
	}
	ri = &RequestInfo{DbNum: dbnum, Key: m[3]}
	return
}

func RootHandler() (response R) {
	response = R{"result": R{"databases": Database.NConnections()},
		"error": nil}
	return
}

// Dispatches the incoming request to the proper action handler, depending on
// the HTTP method that was used.
//
func DispatchRequest(rw http.ResponseWriter, req *http.Request) {
	var response R
	if req.URL.String() == "/" {
		response = RootHandler()
	} else if info, err := GetRequestInfo(req); err == nil {
		switch req.Method {
		case "GET":
			response = HandleReadOperation(req, info)

		case "POST":
			response = HandleCreateOperation(req, info)

		case "PUT":
			response = HandleUpdateOperation(req, info)

		case "DELETE":
			response = HandleDeleteOperation(req, info)
		}
	} else {
		response = R{"result": nil, "error": err}
	}
	rw.Header().Set("Content-Type", "application/json")
	fmt.Fprint(rw, response)
	return
}

func Favicon(rw http.ResponseWriter, req *http.Request) {
	rw.WriteHeader(http.StatusOK)
	return
}


text:
function DIRT_Inspect_AllReg(allReg, varargin)
% DIRT_Inspect_AllReg(allReg, varargin)
%
% Do something with the structure containing the computed registrations
% through the iterations.
%
% Mandatory inputs:
%  - allReg [structure]
%   The structure containing the registrations, as returned by
%   DIRT_Registration in reg.allReg
%
% Optional inputs (properties):
%  - BackupD [string]
%   Backup the difference images using the format string -- an fprintf with
%   the iteration number is used, and the image extension, e.g. png must be
%   included
%  - BackupW [string]
%   Backup the warped images using the format string -- an fprintf with
%   the iteration number is used, and the image extension, e.g. png must be
%   included
%
% This function goes with the DIRT Matlab image registration package.
% Please cite my paper on this topic that you shall find on my web page if
% you use this package. Adrien Bartoli.

z = 1;
while z <= length(varargin)
    switch(varargin{z})
        case 'BackupD'
            fmtfn = varargin{z+1};
            for t = 1:length(allReg)
                imwrite(uint8(allReg{t}.D), sprintf(fmtfn, t));
            end;
            z = z + 2;
        case 'BackupW'
            fmtfn = varargin{z+1};
            for t = 1:length(allReg)
                imwrite(uint8(allReg{t}.W), sprintf(fmtfn, t));
            end;
            z = z + 2;
        otherwise
            error(['unknown property' varargin{z}]);
    end;
end;


text:
package gunstar.api;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Date;

public class DetailedDate implements Comparable<DetailedDate> {

    public static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

    public final Date date;
    public final long extra;

    public DetailedDate(Date date, long extra) {
        this.date = date;
        this.extra = extra;
    }

    public long getDetailedTime() {
        return (date.getTime()*1000000) + extra;
    }

    @Override
    public int compareTo(DetailedDate o) {
        int m = Long.compare(this.date.getTime(), o.date.getTime());
        return m == 0 ? Long.compare(this.extra, o.extra) : m;
    }

    public boolean before(DetailedDate when) {
        return this.compareTo(when) == -1;
    }

    public boolean after(DetailedDate when) {
        return this.compareTo(when) == 1;
    }

    public static DetailedDate parse(String date) {
        if(date == null) {
            return null;
        }
        if(date.length() < 23 || date.charAt(19) != '.') {
            throw new IllegalArgumentException();
        }
        Date d = dateTimeFormatter.parseDateTime(date.substring(0,23)+"Z").toDate();

        int limit = 30;
        int padding = 0;
        if(date.length() < limit) {
            padding = limit-date.length();
            limit = date.length();
        }
        String extraString = date.substring(23, limit-1);
        Long extra = Long.parseLong(extraString);
        if(padding > 0) {
            extra = extra*((long)Math.pow(10, padding));
        }
        return new DetailedDate(d, extra);
    }
}


text:
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric      #-}

module Data.Track.Commitment where

import           Control.DeepSeq
import           Data.Aeson
import           Data.Data
import           Data.Text
import           Data.Time
import           Data.Track.Rules
import           GHC.Generics

data Commitment
    = Commitment
        { commIssueTime            :: UTCTime
        , commEstimatedResolveTime :: UTCTime
        , commResolveTime          :: Maybe UTCTime
        , commCreditor             :: Text
        , commDebtor               :: Text
        , commDescription          :: Text
        }
    deriving (Eq, Show, Read, Data, Typeable, Generic)

instance NFData Commitment
instance ToJSON Commitment where toJSON = trackToJSON
instance FromJSON Commitment where parseJSON = trackParseJSON


text:
import Action from "../../../src/model/js/Action.js";
import Reducer from "../../../src/model/js/Reducer.js";
import ScenarioDeckBuilder from "../../../src/model/js/ScenarioDeckBuilder.js";
import TransferReducer from "../../../src/model/js/TransferReducer.js";

QUnit.module("TransferReducer");

QUnit.test("drawEncounterCard()", function(assert)
{
   // Setup.
   var store = Redux.createStore(Reducer.root);
   var scenarioDeck = ScenarioDeckBuilder.PassageThroughMirkwoodDeckBuilder.buildDeck(store);
   var encounterInstance = scenarioDeck.encounterInstances[0];
   store.dispatch(Action.setEncounterDeck(scenarioDeck.encounterInstances));
   assert.equal(store.getState().encounterDeck.length, 36);
   assert.equal(store.getState().stagingArea.length, 0);

   // Run.
   var result = TransferReducer.reduce(store.getState(), "encounterDeck", undefined, encounterInstance.id(), "stagingArea");

   // Verify.
   assert.ok(result);
   assert.equal(result.encounterDeck.length, 35);
   assert.equal(result.stagingArea.length, 1);
});

var TransferReducerTest = {};
export default TransferReducerTest;


text:
/*******************************************************************************
  PCACHE Peripheral Library Template Implementation

  File Name:
    pcache_CacheEnable_Unsupported.h

  Summary:
    PCACHE PLIB Template Implementation

  Description:
    This header file contains template implementations
    For Feature : CacheEnable
    and its Variant : Unsupported
    For following APIs :
        PLIB_PCACHE_ExistsCacheEnable
        PLIB_PCACHE_CacheEnable
        PLIB_PCACHE_CacheDisable
		PLIB_PCACHE_CacheIsEnabled

*******************************************************************************/

//DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2012 released Microchip Technology Inc.  All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/

//DOM-IGNORE-END

#ifndef _PCACHE_CACHEENABLE_UNSUPPORTED_H
#define _PCACHE_CACHEENABLE_UNSUPPORTED_H

//******************************************************************************
/* Function :  PCACHE_ExistsCacheEnable_Unsupported

  Summary:
    Implements Unsupported variant of PLIB_PCACHE_ExistsCacheEnable

  Description:
    This template implements the Unsupported variant of the PLIB_PCACHE_ExistsCacheEnable function.
*/

PLIB_TEMPLATE bool PCACHE_ExistsCacheEnable_Unsupported( PCACHE_MODULE_ID index )
{
    return false;
}

//******************************************************************************
/* Function :  PCACHE_CacheEnable_Unsupported

  Summary:
    Implements Unsupported variant of PLIB_PCACHE_CacheEnable

  Description:
    This template implements the Unsupported variant of the PLIB_PCACHE_CacheEnable function.
*/

PLIB_TEMPLATE void PCACHE_CacheEnable_Unsupported( PCACHE_MODULE_ID index, PCACHE_CACHE_TYPE cache_type)
{
    PLIB_ASSERT(false, "The device selected does not implement PLIB_PCACHE_CacheEnable");
}

//******************************************************************************
/* Function :  PCACHE_CacheDisable_Unsupported

  Summary:
    Implements Unsupported variant of PLIB_PCACHE_CacheDisable

  Description:
    This template implements the Unsupported variant of the PLIB_PCACHE_CacheDisable function.
*/

PLIB_TEMPLATE void PCACHE_CacheDisable_Unsupported( PCACHE_MODULE_ID index, PCACHE_CACHE_TYPE cache_type )
{
    PLIB_ASSERT(false, "The device selected does not implement PLIB_PCACHE_CacheDisable");
}

//******************************************************************************
/* Function :  PCACHE_CacheIsEnabled_Unsupported

  Summary:
    Implements Unsupported variant of PLIB_PCACHE_CacheIsEnabled

  Description:
    This template implements the Unsupported variant of the PLIB_PCACHE_CacheIsEnabled function.
*/

PLIB_TEMPLATE bool PCACHE_CacheIsEnabled_Unsupported( PCACHE_MODULE_ID index, PCACHE_CACHE_TYPE cache_type)
{
    PLIB_ASSERT(false, "The device selected does not implement PLIB_PCACHE_CacheIsEnabled");
	return false;
}

#endif /*_PCACHE_CACHEENABLE_UNSUPPORTED_H*/

/******************************************************************************
 End of File
*/


text:
<!DOCTYPE html>
<html lang="pt-BR">
	<head>
		<meta charset="utf-8">
		<title>Untitled Document</title>
	</head>
	<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">

	</body>
</html>


text:
import re, sys

def read_points():
    points = []
    f = sys.stdin
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    count = int(f.readline().strip())
    reg = re.compile('\(?([\.\dE-]+),?\s*([\.\dE-]+)\)?')
    for i in range(count):
        line = f.readline()
        x, y = reg.search(line).groups()
        x, y = float(x), float(y)
        points.append( (x,y) )

    if len(sys.argv) > 1:
        f.close()

    return points

def dist(pt1, pt2):
    x1, y1 = pt1
    x2, y2 = pt2
    dx = x1 - x2
    dy = y1 - y2
    d = dx * dx + dy * dy
    return d

def calculate_min_center(points, left_index, right_index, max_dist):
    # Calculate min distance for points up to max_dist away from middle point
    middle_index = (right_index + left_index) // 2
    left_points = []
    for i in range(len(points)): # Only up to 6 points due to geometry magic, but use len(points) for completeness
        left_i = middle_index - i - 1
        if left_i >= left_index and points[middle_index][0] - points[left_i][0] < max_dist:
            left_points.append(points[left_i])
        else:
            break

    right_points = []
    for i in range(len(points)): # Only up to 6 points due to geometry magic, but use len(points) for completeness
        right_i = middle_index + i
        if right_i < right_index and points[right_i][0] - points[middle_index][0] < max_dist:
            right_points.append(points[right_i])
        else:
            break

    if not (left_points and right_points):
        return None
    min_pair = left_points[0], right_points[0]
    min_dist = dist(*min_pair)
    for left_pt in left_points:
        for right_pt in right_points:
            if dist(left_pt, right_pt) < min_dist:
                min_pair = left_pt, right_pt
                min_dist = dist(*min_pair)

    return min_pair

def divide_conquer(points, left_index, right_index):
    assert right_index - left_index > 1
    if right_index - left_index == 2:
        # Just two, answer is obvious
        return points[left_index], points[left_index+1]
    if right_index - left_index == 3:
        # Just compare them!
        pt1, pt2, pt3 = points[left_index:right_index]
        pair_dists = [
            (dist(pt1, pt2), (pt1, pt2)),
            (dist(pt2, pt3), (pt2, pt3)),
            (dist(pt1, pt3), (pt1, pt3)),
        ]
        return min(pair_dists)[1]

    # Other cases can be recursive!
    middle_index = (right_index + left_index) // 2

    min_pair_left = divide_conquer(points, left_index, middle_index)
    min_pair_right = divide_conquer(points, middle_index, right_index)

    if dist(*min_pair_left) < dist(*min_pair_right):
        min_pair_lr = min_pair_left
        min_dist_lr = dist(*min_pair_left)
    else:
        min_pair_lr = min_pair_right
        min_dist_lr = dist(*min_pair_right)

    min_pair_center = calculate_min_center(points, left_index, right_index, min_dist_lr)
    if min_pair_center is not None and dist(*min_pair_center) < min_dist_lr:
        return min_pair_center
    else:
        return min_pair_lr

def main():
    points = read_points()
    points.sort()

    min_pair = divide_conquer(points, 0, len(points))

    print("%s, %s" % min_pair)

if __name__ == '__main__':
    main()


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Z. Jl Bot. 15(4): 721 (1978)

#### Original name
Inocybe mendica E. Horak, 1978

### Remarks
null