text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xinzhongxinbletester"
    android:versionCode="2"
    android:versionName="1.3" >

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

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name="com.xinzhongxin.application.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.xinzhongxin.bletester.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.xinzhongxin.bletester.DeviceConnect" >
        </activity>
        <activity android:name="com.xinzhongxin.bletester.CharacterisiticActivity" >
        </activity>
        <activity android:name="com.xinzhongxin.bletester.ChangeCharActivity" >
        </activity>
        <activity android:name="com.xinzhongxin.bletester.AboutActivity" >
        </activity>
        <activity android:name="com.xinzhongxin.bletester.QrcodeActivity" >
        </activity>

        <service android:name="com.xinzhongxin.service.BleService" >
        </service>
    </application>

</manifest>


text:
<?php

namespace Doctrine\Tests\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\DecimalType;
use Doctrine\DBAL\Types\Type;
use Doctrine\Tests\DbalTestCase;
use PHPUnit\Framework\MockObject\MockObject;

class DecimalTest extends DbalTestCase
{
    /** @var AbstractPlatform|MockObject */
    private $platform;

    /** @var DecimalType */
    private $type;

    protected function setUp() : void
    {
        $this->platform = $this->createMock(AbstractPlatform::class);
        $this->type     = Type::getType('decimal');
    }

    public function testDecimalConvertsToPHPValue() : void
    {
        self::assertIsString($this->type->convertToPHPValue('5.5', $this->platform));
    }

    public function testDecimalNullConvertsToPHPValue() : void
    {
        self::assertNull($this->type->convertToPHPValue(null, $this->platform));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package fulltext

import(
	iface "github.com/opesun/chill/frame/interfaces"
	"github.com/opesun/slugify"
	"labix.org/v2/mgo/bson"
	"strings"
)

type C struct {
}

// TODO: rethink. TODO: Add number support.
// Walks an entire JSON tree recursively, and converts everything to string it can find.
func toStringRecursively(i interface{}) []string {
	switch val := i.(type) {
	case map[string]interface{}:
		ret := []string{}
		for _, v := range val {
			ret = append(ret, toStringRecursively(v)...)
		}
		return ret
	case []interface{}:
		ret := []string{}
		for _, v := range val {
			ret = append(ret, toStringRecursively(v)...)
		}
		return ret
	case string:
		return []string{val}
	}
	return []string{}
}

func filterDupes(s []string) []string {
	ret := []string{}
	c := map[string]struct{}{}
	for _, v := range s {
		if _, has := c[v]; !has {
			c[v] = struct{}{}
			ret = append(ret, v)
		}
	}
	return ret
}

func filterTooShort(s []string, min_len int) []string {
	ret := []string{}
	for _, v := range s {
		if len(v) >= min_len {
			ret = append(ret, v)
		}
	}
	return ret
}

func simpleFulltext(non_split []string) []string {
	split := []string{}
	for _, v := range non_split {
		split = append(split, strings.Split(v, " ")...)
	}
	slugified := []string{}
	for _, v := range split {
		slugified = append(slugified, strings.Trim(slugify.S(v), ",.:;"))
	}
	slugified = filterDupes(slugified)
	return filterTooShort(slugified, 3)
}

func (c *C) updateFromDoc(doc map[string]interface{}) map[string]interface{} {
	non_split := toStringRecursively(doc)
	fullt := simpleFulltext(non_split)
	upd := map[string]interface{}{
		"$set": map[string]interface{}{
			"fulltext": fullt,
		},
	}
	return upd
}

func (c *C) SaveFulltext(a iface.Filter) error {
	doc, err := a.FindOne()
	if err != nil {
		return err
	}
	upd := c.updateFromDoc(doc)
	return a.Update(upd)
}

func (c *C) RegenerateFulltext(a iface.Filter) error {
	cb := func(doc map[string]interface{}, g iface.Grabbed) error {
		upd := c.updateFromDoc(doc)
		return g.Update(upd)
	}
	return a.Iterate(cb)
}

func GenerateKeywords(s string) []string {
	split := strings.Split(s, " ")
	slugified := []string{}
	for _, v := range split {
		slugified = append(slugified, strings.Trim(slugify.S(v), ",.:;"))
	}
	return slugified
}

// Generates [{"fulltext": \^keyword1\}, {"fulltext": \^keyword2\}]
// With this query we can create a good enough full text search, which can search at the beginning of the keywords.
// We could write regexes which searches in the middle of the words too, but that query could not uzilize the btree indexes of mongodb.
// This solution must be efficient, assuming mongodb does the expected sane things: utilizing indexes with ^ regexes, "$and" queries and arrays.
func GenerateQuery(s string) []interface{} {
	sl := GenerateKeywords(s)
	and := []interface{}{}
	for _, v := range sl {
		and = append(and, map[string]interface{}{
			"fulltext": bson.RegEx{
				Pattern: "^" + v,
			},
		})
	}
	return and
}

func (c *C) ProcessMap(inp map[string]interface{}) {
	val, has := inp["search"].(string)
	if !has {
		return
	}
	inp["$and"] = GenerateQuery(val)
	delete(inp, "search")
}


text:
namespace doris {
// Class for managing olap table header.
class OLAPHeader : public OLAPHeaderMessage {
public:
    explicit OLAPHeader() :
            _support_reverse_version(false) {}

    // for compatible header file
    explicit OLAPHeader(const std::string& file_name) :
            _file_name(file_name),
            _support_reverse_version(false) {}

    virtual ~OLAPHeader();

    // Loads the header from disk and init, returning true on success.
    // In load_and_init(), we will validate olap header file, which mainly include
    // tablet schema, delta version and so on.
    OLAPStatus load_and_init();
    OLAPStatus load_for_check();

    // Saves the header to disk, returning true on success.
    OLAPStatus save();
    OLAPStatus save(const std::string& file_path);

    OLAPStatus init();

    // Return the file name of the heade.
    std::string file_name() const {
        return _file_name;
    }

    // Adds a new version to the header. Do not use the proto's
    // add_version() directly.
    OLAPStatus add_version(Version version, VersionHash version_hash,
                           int32_t segment_group_id, int32_t num_segments,
                           int64_t index_size, int64_t data_size, int64_t num_rows,
                           bool empty, const std::vector<KeyRange>* column_statistics);

    OLAPStatus add_pending_version(int64_t partition_id, int64_t transaction_id,
                                 const std::vector<std::string>* delete_conditions);
    OLAPStatus add_pending_segment_group(int64_t transaction_id, int32_t num_segments,
                                  int32_t pending_segment_group_id, const PUniqueId& load_id,
                                  bool empty, const std::vector<KeyRange>* column_statistics);

    // add incremental segment_group into header like "9-9" "10-10", for incremental cloning
    OLAPStatus add_incremental_version(Version version, VersionHash version_hash,
                                       int32_t segment_group_id, int32_t num_segments,
                                       int64_t index_size, int64_t data_size, int64_t num_rows,
                                       bool empty, const std::vector<KeyRange>* column_statistics);

    void add_delete_condition(const DeleteConditionMessage& delete_condition, int64_t version);
    void delete_cond_by_version(const Version& version);
    bool is_delete_data_version(Version version);

    const PPendingDelta* get_pending_delta(int64_t transaction_id) const;
    const PPendingSegmentGroup* get_pending_segment_group(int64_t transaction_id, int32_t pending_segment_group_id) const;
    const PDelta* get_incremental_version(Version version) const;

    // Deletes a version from the header.
    OLAPStatus delete_version(Version version);
    OLAPStatus delete_all_versions();
    void delete_pending_delta(int64_t transaction_id);
    void delete_incremental_delta(Version version);

    // Constructs a canonical file name (without path) for the header.
    // eg "DailyUnitStats_PRIMARY.hdr"
    std::string construct_file_name() const {
        return std::string(basename(_file_name.c_str()));
    }

    // In order to prevent reverse version to appear in the shortest version
    // path, you can call set_reverse_version(false) although schema can
    // support reverse version in the path.
    void set_reverse_version(bool support_reverse_version) {
        _support_reverse_version = support_reverse_version;
    }

    // Try to select the least number of data files that can span the
    // target_version and append these data versions to the span_versions.
    // Return false if the target_version cannot be spanned.
    virtual OLAPStatus select_versions_to_span(const Version& target_version,
                                           std::vector<Version>* span_versions);

    const PDelta* get_lastest_delta_version() const;
    const PDelta* get_lastest_version() const;
    Version get_latest_version() const;
    const PDelta* get_delta(int index) const;
    const PDelta* get_base_version() const;
    const uint32_t get_cumulative_compaction_score() const;
    const uint32_t get_base_compaction_score() const;
    const OLAPStatus version_creation_time(const Version& version, int64_t* creation_time) const;

    int file_delta_size() const {
        return delta_size();
    }
    void change_file_version_to_delta();
private:
    void _convert_file_version_to_delta(const FileVersionMessage& version, PDelta* delta);

    // full path of olap header file
    std::string _file_name;

    // If the aggregation types of all value columns in the schema are SUM,
    // select_versions_to_span can return reverse version in the shortest
    // version path. one can set _support_reverse_version to be false in
    // order to prevent reverse version to appear in the shortest version path.
    // Its default value is false.
    bool _support_reverse_version;

    // OLAP version contains two parts, [start_version, end_version]. In order
    // to construct graph, the OLAP version has two corresponding vertex, one
    // vertex's value is version.start_version, the other is
    // version.end_version + 1.
    // Use adjacency list to describe version graph.
    std::vector<Vertex> _version_graph;

    // vertex value --> vertex_index of _version_graph
    // It is easy to find vertex index according to vertex value.
    std::unordered_map<int, int> _vertex_helper_map;

    DISALLOW_COPY_AND_ASSIGN(OLAPHeader);
};

}  // namespace doris

#endif // DORIS_BE_SRC_OLAP_OLAP_HEADER_H


text:
package org.apereo.cas.services;

import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.JpaServiceRegistryConfiguration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.test.annotation.DirtiesContext;

/**
 * Handles tests for {@link JpaServiceRegistry}
 *
 * @author battags
 * @since 3.1.0
 */
@SpringBootTest(classes = {
    RefreshAutoConfiguration.class,
    AopAutoConfiguration.class,
    CasCoreUtilConfiguration.class,
    JpaServiceRegistryConfiguration.class,
    CasCoreServicesConfiguration.class
})
@DirtiesContext
public class JpaServiceRegistryTests extends AbstractServiceRegistryTests {

    @Autowired
    @Qualifier("jpaServiceRegistry")
    private ServiceRegistry serviceRegistry;

    @Override
    public ServiceRegistry getNewServiceRegistry() {
        return this.serviceRegistry;
    }
}


text:
/* sarray.h - Implementation of a resizable sorted array
 */

#ifndef ARRAY_SORTED_H
#define ARRAY_SORTED_H

#include <stddef.h>
#include "system.h"
#include "array.h"

typedef struct {
	comp_fn_t comp;
	array *a;
} sarray;

/* Initialize a new generic resizable sorted array, where each element in the
array has elem_size. The comparison function is used to decide the order
of the new added elements in the array. */
extern int sarray_init(sarray *as, size_t elem_size, comp_fn_t comp);

/* Add the element at elem_addr to the sorted array, using the compare
function specified in the initialization. */
extern int sarray_add(sarray *as, void *elem_addr);

extern void *sarray_value(sarray *as, size_t index);
extern void *sarray_search(sarray *as, void *elem_addr);
extern int sarray_remove_byindex(sarray *as, size_t index);
extern int sarray_size(sarray *as);
extern void sarray_destroy(sarray *as);

#endif // ARRAY_SORTED_H


text:
package org.hisp.dhis.resultsframework;

import org.hisp.dhis.common.GenericNameableObjectStore;

/**
 * @author Abyot Asalefew Gizaw <abyota@gmail.com>
 *
 */
public interface SubProgrammStore
    extends GenericNameableObjectStore<SubProgramm>
{

}


text:
module MCollective
    module Agent
        # An agent that uses Reductive Labs Puppet to manage packages
        #
        # See http://code.google.com/p/mcollective-plugins/
        #
        # Released under the terms of the GPL, same as Puppet
        class Puppetupdate<RPC::Agent
            metadata :name => "Puppet Update",
              :description => "Agent To Update module checkouts on puppet masters",
              :author      => "Carl Caum",
              :license     => "GPLv2",
              :version     => "1.0",
              :url         => "http://github.com/puppetlabs/puppetlabs-mcmasterupdates",
              :timeout     => 10

            action 'update' do
              validate :rcs, :shellsafe
              validate :environment, :shellsafe

              begin
                require 'puppet'
              rescue LoadError => e
                reply.fail! "Cannot load Puppet"
              end

              case request[:rcs]
              when 'svn'
                command = "svn update"
              when 'git'
                command = "git pull"
              else
                reply.fail! "Unknown RCS #{request[:rcs]}"
              end

              Puppet[:config] = '/etc/puppet/puppet.conf'
              Puppet.parse_config
              Puppet::Node::Environment.new(request[:environment])[:modulepath].split(':').each do |path|
                run "#{command} #{path}", :stderr => :err, :stdout => :out, :chomp => true
              end
            end
        end
    end
end


text:
#ifndef _SPARC64_FPU_FPU_EXTERN_H_
#define _SPARC64_FPU_FPU_EXTERN_H_

struct utrapframe;
struct fpemu;
struct fpn;

/* fpu.c */
int __fpu_exception(struct utrapframe *tf);

/* fpu_add.c */
struct fpn *__fpu_add(struct fpemu *);

/* fpu_compare.c */
void __fpu_compare(struct fpemu *, int, int);

/* fpu_div.c */
struct fpn *__fpu_div(struct fpemu *);

/* fpu_explode.c */
int __fpu_itof(struct fpn *, u_int);
int __fpu_xtof(struct fpn *, u_int64_t);
int __fpu_stof(struct fpn *, u_int);
int __fpu_dtof(struct fpn *, u_int, u_int);
int __fpu_qtof(struct fpn *, u_int, u_int, u_int, u_int);
void __fpu_explode(struct fpemu *, struct fpn *, int, int);

/* fpu_implode.c */
u_int __fpu_ftoi(struct fpemu *, struct fpn *);
u_int __fpu_ftox(struct fpemu *, struct fpn *, u_int *);
u_int __fpu_ftos(struct fpemu *, struct fpn *);
u_int __fpu_ftod(struct fpemu *, struct fpn *, u_int *);
u_int __fpu_ftoq(struct fpemu *, struct fpn *, u_int *);
void __fpu_implode(struct fpemu *, struct fpn *, int, u_int *);

/* fpu_mul.c */
struct fpn *__fpu_mul(struct fpemu *);

/* fpu_sqrt.c */
struct fpn *__fpu_sqrt(struct fpemu *);

/* fpu_subr.c */
/*
 * Shift a number right some number of bits, taking care of round/sticky.
 * Note that the result is probably not a well-formed number (it will lack
 * the normal 1-bit mant[0]&FP_1).
 */
int __fpu_shr(register struct fpn *, register int);
void __fpu_norm(register struct fpn *);
/* Build a new Quiet NaN (sign=0, frac=all 1's). */
struct fpn *__fpu_newnan(register struct fpemu *);

#endif /* !_SPARC64_FPU_FPU_EXTERN_H_ */


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example">

              </button>
            	<a href="<?php echo base_url(); ?>site/index" class="navbar-brand" ><img itemprop="logo" height="28px" src="<?php echo base_url(); ?>img/sajt/logo.png" alt="logo" />

<a href="<?php echo base_url(); ?>site/index">POČETNA

       					 PROIZVODI

<a href="<?php echo base_url(); ?>site/proizvodi/slana-zimnica">Slana zimnica

<a href="<?php echo base_url(); ?>site/proizvodi/slatka-zimnica">Slatka zimnica

<a href="<?php echo base_url(); ?>site/aktuelno">AKTUELNO

<a href="<?php echo base_url(); ?>site/sindikati">SINDIKATI

<a href="<?php echo base_url(); ?>site/recepti">RECEPTI

<a href="<?php echo base_url(); ?>site/oNama">O NAMA

<a href="<?php echo base_url(); ?>site/kontakt">KONTAKT

<a id = "cart_total"href="<?php echo base_url(); ?>site/korpa" rel="nofollow"><?php echo $this->cart->format_number($this->cart->total());?> RSD

<a href="<?php echo base_url(); ?>site/korpa" rel="nofollow"> Korpa

<meta itemprop="name" content="Tornado">


text:
import struct
from datetime import datetime, timedelta

class BPListWriter(object):
    def __init__(self, objects):
        self.bplist = ""
        self.objects = objects

    def binary(self):
        '''binary -> string

        Generates bplist
        '''
        self.data = 'bplist00'

        # TODO: flatten objects and count max length size

        # TODO: write objects and save offsets

        # TODO: write offsets

        # TODO: write metadata

        return self.data

    def write(self, filename):
        '''

        Writes bplist to file
        '''
        if self.bplist != "":
            pass
            # TODO: save self.bplist to file
        else:
            raise Exception('BPlist not yet generated')

class BPlistReader(object):
    def __init__(self, s):
        self.data = s
        self.objects = []
        self.resolved = {}

    def __unpackIntStruct(self, sz, s):
        '''__unpackIntStruct(size, string) -> int

        Unpacks the integer of given size (1, 2 or 4 bytes) from string
        '''
        if   sz == 1:
            ot = '!B'
        elif sz == 2:
            ot = '!H'
        elif sz == 4:
            ot = '!I'
        elif sz == 8:
            ot = '!Q'
        else:
            raise Exception('int unpack size '+str(sz)+' unsupported')
        return struct.unpack(ot, s)[0]

    def __unpackInt(self, offset):
        '''__unpackInt(offset) -> int

        Unpacks int field from plist at given offset
        '''
        return self.__unpackIntMeta(offset)[1]

    def __unpackIntMeta(self, offset):
        '''__unpackIntMeta(offset) -> (size, int)

        Unpacks int field from plist at given offset and returns its size and value
        '''
        obj_header = struct.unpack('!B', self.data[offset])[0]
        obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F)
        int_sz = 2**obj_info
        return int_sz, self.__unpackIntStruct(int_sz, self.data[offset+1:offset+1+int_sz])

    def __resolveIntSize(self, obj_info, offset):
        '''__resolveIntSize(obj_info, offset) -> (count, offset)

        Calculates count of objref* array entries and returns count and offset to first element
        '''
        if obj_info == 0x0F:
            ofs, obj_count = self.__unpackIntMeta(offset+1)
            objref = offset+2+ofs
        else:
            obj_count = obj_info
            objref = offset+1
        return obj_count, objref

    def __unpackFloatStruct(self, sz, s):
        '''__unpackFloatStruct(size, string) -> float

        Unpacks the float of given size (4 or 8 bytes) from string
        '''
        if   sz == 4:
            ot = '!f'
        elif sz == 8:
            ot = '!d'
        else:
            raise Exception('float unpack size '+str(sz)+' unsupported')
        return struct.unpack(ot, s)[0]

    def __unpackFloat(self, offset):
        '''__unpackFloat(offset) -> float

        Unpacks float field from plist at given offset
        '''
        obj_header = struct.unpack('!B', self.data[offset])[0]
        obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F)
        int_sz = 2**obj_info
        return int_sz, self.__unpackFloatStruct(int_sz, self.data[offset+1:offset+1+int_sz])

    def __unpackDate(self, offset):
        td = int(struct.unpack(">d", self.data[offset+1:offset+9])[0])
        return datetime(year=2001,month=1,day=1) + timedelta(seconds=td)

    def __unpackItem(self, offset):
        '''__unpackItem(offset)

        Unpacks and returns an item from plist
        '''
        obj_header = struct.unpack('!B', self.data[offset])[0]
        obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F)
        if   obj_type == 0x00:
            if   obj_info == 0x00: # null   0000 0000
                return None
            elif obj_info == 0x08: # bool   0000 1000           // false
                return False
            elif obj_info == 0x09: # bool   0000 1001           // true
                return True
            elif obj_info == 0x0F: # fill   0000 1111           // fill byte
                raise Exception("0x0F Not Implemented") # this is really pad byte, FIXME
            else:
                raise Exception('unpack item type '+str(obj_header)+' at '+str(offset)+ 'failed')
        elif obj_type == 0x10: #     int    0001 nnnn   ...     // # of bytes is 2^nnnn, big-endian bytes
            return self.__unpackInt(offset)
        elif obj_type == 0x20: #    real    0010 nnnn   ...     // # of bytes is 2^nnnn, big-endian bytes
            return self.__unpackFloat(offset)
        elif obj_type == 0x30: #    date    0011 0011   ...     // 8 byte float follows, big-endian bytes
            return self.__unpackDate(offset)
        elif obj_type == 0x40: #    data    0100 nnnn   [int]   ... // nnnn is number of bytes unless 1111 then int count follows, followed by bytes
            obj_count, objref = self.__resolveIntSize(obj_info, offset)
            return self.data[objref:objref+obj_count] # XXX: we return data as str
        elif obj_type == 0x50: #    string  0101 nnnn   [int]   ... // ASCII string, nnnn is # of chars, else 1111 then int count, then bytes
            obj_count, objref = self.__resolveIntSize(obj_info, offset)
            return self.data[objref:objref+obj_count]
        elif obj_type == 0x60: #    string  0110 nnnn   [int]   ... // Unicode string, nnnn is # of chars, else 1111 then int count, then big-endian 2-byte uint16_t
            obj_count, objref = self.__resolveIntSize(obj_info, offset)
            return self.data[objref:objref+obj_count*2].decode('utf-16be')
        elif obj_type == 0x80: #    uid     1000 nnnn   ...     // nnnn+1 is # of bytes
            # FIXME: Accept as a string for now
            obj_count, objref = self.__resolveIntSize(obj_info, offset)
            return self.data[objref:objref+obj_count]
        elif obj_type == 0xA0: #    array   1010 nnnn   [int]   objref* // nnnn is count, unless '1111', then int count follows
            obj_count, objref = self.__resolveIntSize(obj_info, offset)
            arr = []
            for i in range(obj_count):
                arr.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size]))
            return arr
        elif obj_type == 0xC0: #   set      1100 nnnn   [int]   objref* // nnnn is count, unless '1111', then int count follows
            # XXX: not serializable via apple implementation
            raise Exception("0xC0 Not Implemented") # FIXME: implement
        elif obj_type == 0xD0: #   dict     1101 nnnn   [int]   keyref* objref* // nnnn is count, unless '1111', then int count follows
            obj_count, objref = self.__resolveIntSize(obj_info, offset)
            keys = []
            for i in range(obj_count):
                keys.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size]))
            values = []
            objref += obj_count*self.object_ref_size
            for i in range(obj_count):
                values.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size]))
            dic = {}
            for i in range(obj_count):
                dic[keys[i]] = values[i]
            return dic
        else:
            raise Exception('don\'t know how to unpack obj type '+hex(obj_type)+' at '+str(offset))

    def __resolveObject(self, idx):
        try:
            return self.resolved[idx]
        except KeyError:
            obj = self.objects[idx]
            if type(obj) == list:
                newArr = []
                for i in obj:
                    newArr.append(self.__resolveObject(i))
                self.resolved[idx] = newArr
                return newArr
            if type(obj) == dict:
                newDic = {}
                for k,v in obj.iteritems():
                    rk = self.__resolveObject(k)
                    rv = self.__resolveObject(v)
                    newDic[rk] = rv
                self.resolved[idx] = newDic
                return newDic
            else:
                self.resolved[idx] = obj
                return obj

    def parse(self):
        # read header
        if self.data[:8] != 'bplist00':
            raise Exception('Bad magic')

        # read trailer
        self.offset_size, self.object_ref_size, self.number_of_objects, self.top_object, self.table_offset = struct.unpack('!6xBB4xI4xI4xI', self.data[-32:])
        #print "** plist offset_size:",self.offset_size,"objref_size:",self.object_ref_size,"num_objs:",self.number_of_objects,"top:",self.top_object,"table_ofs:",self.table_offset

        # read offset table
        self.offset_table = self.data[self.table_offset:-32]
        self.offsets = []
        ot = self.offset_table
        for i in range(self.number_of_objects):
            offset_entry = ot[:self.offset_size]
            ot = ot[self.offset_size:]
            self.offsets.append(self.__unpackIntStruct(self.offset_size, offset_entry))
        #print "** plist offsets:",self.offsets

        # read object table
        self.objects = []
        k = 0
        for i in self.offsets:
            obj = self.__unpackItem(i)
            #print "** plist unpacked",k,type(obj),obj,"at",i
            k += 1
            self.objects.append(obj)

        # rebuild object tree
        #for i in range(len(self.objects)):
        #    self.__resolveObject(i)

        # return root object
        return self.__resolveObject(self.top_object)

    @classmethod
    def plistWithString(cls, s):
        parser = cls(s)
        return parser.parse()

# helpers for testing
def plist(obj):
    from Foundation import NSPropertyListSerialization, NSPropertyListBinaryFormat_v1_0
    b = NSPropertyListSerialization.dataWithPropertyList_format_options_error_(obj,  NSPropertyListBinaryFormat_v1_0, 0, None)
    return str(b.bytes())

def unplist(s):
    from Foundation import NSData, NSPropertyListSerialization
    d = NSData.dataWithBytes_length_(s, len(s))
    return NSPropertyListSerialization.propertyListWithData_options_format_error_(d, 0, None, None)


text:
<?php
namespace Vivo\Indexer;

/**
 * Field
 * Represents a document field
 */
class Field
{
    /**
     * Field name
     * @var string
     */
    protected $name;

    /**
     * Field value
     * @var mixed|array
     */
    protected $value;

    /**
     * Constructor
     * @param string $name
     * @param mixed|array $value
     */
    public function __construct($name, $value)
    {
        $this->name  = $name;
        $this->value = $value;
    }

    /**
     * Returns the name of the field
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Return value of the field
     * @return mixed|array
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Returns if the field is multivalued
     * @return bool
     */
    public function isMultiValued()
    {
        return is_array($this->value);
    }
}


text:
package mangos

import (
	"fmt"
	"runtime"
	"strings"
	"time"
)

// mkTimer creates a timer based upon a duration.  If however
// a zero valued duration is passed, then a nil channel is passed
// i.e. never selectable.  This allows the output to be readily used
// with deadlines in network connections, etc.
func mkTimer(deadline time.Duration) <-chan time.Time {

	if deadline == 0 {
		return nil
	}

	return time.After(deadline)
}

var debug = true

func debugf(format string, args ...interface{}) {
	if debug {
		_, file, line, ok := runtime.Caller(1)
		if !ok {
			file = "<?>"
			line = 0
		} else {
			if i := strings.LastIndex(file, "/"); i >= 0 {
				file = file[i+1:]
			}
		}
		fmt.Printf("DEBUG: %s:%d [%s]: %s\n", file, line,
			time.Now().String(), fmt.Sprintf(format, args...))
	}
}


text:
<?php
// autogenerated file 30.09.2013 15:20
// $Id: $
// $Log: $
//
require_once 'EbatNs_FacetType.php';

/**
 * Defines the source for discount price treatment.
 *
 * @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/PricingTreatmentCodeType.html
 *
 * @property string STP
 * @property string MAP
 * @property string None
 * @property string MFO
 * @property string CustomCode
 */
class PricingTreatmentCodeType extends EbatNs_FacetType
{
	const CodeType_STP = 'STP';
	const CodeType_MAP = 'MAP';
	const CodeType_None = 'None';
	const CodeType_MFO = 'MFO';
	const CodeType_CustomCode = 'CustomCode';

	/**
	 * @return
	 */
	function __construct()
	{
		parent::__construct('PricingTreatmentCodeType', 'urn:ebay:apis:eBLBaseComponents');

	}
}

$Facet_PricingTreatmentCodeType = new PricingTreatmentCodeType();

?>


text:
layout: default
title: "Succession"

---

{% include interests/succession.md %}

### Who is interested in Succession?

* [Keith Vaz]({{ site.baseurl }}/members/keith-vaz.html)


text:
#pragma once

#include "models/common/errorlist.h"
#include "models/common/idstring.h"
#include "models/common/namedlist.h"
#include <array>
#include <variant>

namespace UnTech::Scripting {

struct BytecodeMapping;
struct GameStateData;

struct Statement;
struct IfStatement;
struct WhileStatement;
struct Comment;

// ::TODO add CustomIfStatement ::
// NOTE: If I change ScriptNode then I must also update UnTech::Gui::RoomEditorData::AP::ScriptStatements::getList();
using ScriptNode = std::variant<Statement, IfStatement, WhileStatement, Comment>;

enum class ConditionalType {
    Word,
    Flag,
};

enum class ComparisonType {
    Equal,
    NotEqual,
    LessThan,
    GreaterThanEqual,

    Set,
    Clear,
};

struct Conditional {
    ConditionalType type;
    idstring variable;
    ComparisonType comparison;
    std::u8string value;

    bool operator==(const Conditional&) const = default;
};

struct Statement {
    idstring opcode;
    std::array<std::u8string, 2> arguments;

    bool operator==(const Statement&) const = default;
};

struct Comment {
    std::u8string text;

    bool operator==(const Comment&) const = default;
};

struct IfStatement {
    Conditional condition;
    std::vector<ScriptNode> thenStatements;
    std::vector<ScriptNode> elseStatements;

    // Cannot use default here, ScriptNode is incomplete.
    bool operator==(const IfStatement& o) const;
};

struct WhileStatement {
    Conditional condition;
    std::vector<ScriptNode> statements;

    // Cannot use default here, ScriptNode is incomplete.
    bool operator==(const WhileStatement& o) const;
};

struct Script {
    constexpr static unsigned MAX_DEPTH = 8;

    idstring name;

    std::vector<ScriptNode> statements;

    bool operator==(const Script&) const = default;
};

struct RoomScripts {
    RoomScripts();

    std::vector<idstring> tempFlags;
    std::vector<idstring> tempWords;

    Scripting::Script startupScript;

    NamedList<Scripting::Script> scripts;

    bool operator==(const RoomScripts&) const = default;
};

extern const idstring STARTUP_SCRIPT_NAME;

inline bool IfStatement::operator==(const IfStatement& o) const
{
    return condition == o.condition
           && thenStatements == o.thenStatements
           && elseStatements == o.elseStatements;
}

inline bool WhileStatement::operator==(const WhileStatement& o) const
{
    return condition == o.condition
           && statements == o.statements;
}

}


text:
namespace System.Activities.Statements
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;

    [DataContract]
    sealed class ExecutionTracker
    {
        List<CompensationTokenData> executionOrderedList;

        public ExecutionTracker()
        {
            this.executionOrderedList = new List<CompensationTokenData>();
        }

        public int Count
        {
            get
            {
                return this.executionOrderedList.Count;
            }
        }

        [DataMember(Name = "executionOrderedList")]
        internal List<CompensationTokenData> SerializedExecutionOrderedList
        {
            get { return this.executionOrderedList; }
            set { this.executionOrderedList = value; }
        }

        public void Add(CompensationTokenData compensationToken)
        {
            this.executionOrderedList.Insert(0, compensationToken);
        }

        public void Remove(CompensationTokenData compensationToken)
        {
            this.executionOrderedList.Remove(compensationToken);
        }

        public CompensationTokenData Get()
        {
            if (Count > 0)
            {
                return this.executionOrderedList[0];
            }
            else
            {
                return null;
            }
        }
    }
}


text:
layout: page
title: "Please contribute"
description: ""
group: development
---
{% include JB/setup %}

### Waiting for your help
The content does not exist yet.

We're always welcoming contribution.

If you're interested, please check [How to contribute (website)](./development/howtocontributewebsite.html).


text:
title:  Further Thought
date:  02/09/2022
---

Read Ellen G. White, "The Importance of Seeking True Knowledge," pp. 453, 454, in The Ministry of Healing; "The Sermon on the Mount," pp. 298–314, in The Desire of Ages; "The Worker and His Qualifications," p. 630, in Evangelism.

"The difficulties we have to encounter may be very much lessened by that meekness which hides itself in Christ. If we possess the humility of our Master, we shall rise above the slights, the rebuffs, the annoyances, to which we are daily exposed, and they will cease to cast a gloom over the spirit. The highest evidence of nobility in a Christian is self-control. He who under abuse or cruelty fails to maintain a calm and trustful spirit robs God of His right to reveal in him His own perfection of character. Lowliness of heart is the strength that gives victory to the followers of Christ; it is the token of their connection with the courts above."—Ellen G. White, The Desire of Ages, p. 301.

**Discussion Questions**:

`How does humility allow us to "rise above" hurts and annoyances? What do you think is the most important characteristic of humility that allows us to do this?`

`In your own particular culture, how are the characteristics of humility and meekness viewed? Are they respected, despised, or what? What kind of pressures do you face in your culture that work against you in cultivating these characteristics?`

`Are there any great examples of meekness and humility among people alive today? If so, who are they, how have they expressed these traits, and what can you learn from them?`

`Why is it that we so often equate meekness and humility with weakness?`

`We saw how David sought the Lord as a refuge. But how does that work? How is that refuge always manifested? In other words, how can we, as a church, be a refuge for those who need a refuge? What kind of refuge does your own local church provide? What can you do to help make it a place of refuge for those who need it?`

---

#### Additional Reading: Selected Quotes from Ellen G. White

Reflecting Christ, "Christ a Perfect Example for All," p. 37;

Evangelism, "The Worker and His Qualifications," p. 630.


text:
module TwitterCldr
  module Collation

    # Collator uses fractional collation elements table form CLDR to generate sort keys for Unicode strings as well as
    # compare and sort such strings by generated sort keys.
    #
    class Collator

      attr_accessor :locale

      def initialize(locale = nil)
        @locale  = TwitterCldr.convert_locale(locale) if locale
        @options = tailoring_options
        @trie    = load_trie
      end

      def sort(strings)
        strings.map{ |s| [s, get_sort_key(s)] }.sort{ |a, b| a[1] <=> b[1] }.map(&:first)
      end

      def sort!(strings)
        sort_keys = Hash.new { |hash, string| hash[string] = get_sort_key(string) }
        strings.replace(strings.sort_by { |s| sort_keys[s] })
      end

      def compare(string_a, string_b)
        string_a == string_b ? 0 : get_sort_key(string_a) <=> get_sort_key(string_b)
      end

      def get_sort_key(string_or_code_points)
        TwitterCldr::Collation::SortKeyBuilder.build(get_collation_elements(string_or_code_points), @options[:case_first])
      end

      def get_collation_elements(string_or_code_points)
        code_points = get_normalized_code_points(string_or_code_points)

        result = []
        result.concat(code_point_collation_elements(code_points)) until code_points.empty?
        result
      end

      private

      def tailoring_options
        @locale ? TwitterCldr::Collation::TrieBuilder.tailoring_data(@locale)[:collator_options] : {}
      end

      def load_trie
        @locale ? self.class.tailored_trie(@locale) : self.class.default_trie
      end

      def get_normalized_code_points(str_or_code_points)
        code_points = str_or_code_points.is_a?(String) ? TwitterCldr::Utils::CodePoints.from_string(str_or_code_points) : str_or_code_points

        # Normalization makes the collation process significantly slower (like seven times slower on the UCA
        # non-ignorable test from CollationTest_NON_IGNORABLE.txt). ICU uses some optimizations to apply normalization
        # only in special, rare cases. We need to investigate possible solutions and do normalization cleverly too.
        TwitterCldr::Normalization::NFD.normalize_code_points(code_points)
      end

      # Returns the first sequence of fractional collation elements for an array of integer code points. Returned value
      # is an array of well formed (including weights for all significant levels) integer arrays.
      #
      # NOTE (side-effect): all used code points are removed from the input array.
      #
      def code_point_collation_elements(code_points)
        explicit_collation_elements(code_points) || implicit_collation_elements(code_points)
      end

      # Tries to build explicit collation elements array for the longest code points prefix in the given sequence. When
      # possible, combines this prefix with (not necessarily subsequent) non-starters that follow it in the sequence.
      # That's necessary because canonical ordering (that is performed during normalization) can break contractions
      # that existed in the original, de-normalized string.
      #
      # NOTE (side-effect): all used code points are removed from the input array.
      #
      # For more information see section '4.2 Produce Array' of the main algorithm at http://www.unicode.org/reports/tr10/#Main_Algorithm
      #
      def explicit_collation_elements(code_points)
        # find the longest prefix in the trie
        collation_elements, prefix_size, suffixes = @trie.find_prefix(code_points)

        return unless collation_elements

        # remove prefix from the code points sequence
        code_points.shift(prefix_size)

        non_starter_pos = 0

        used_combining_classes = {}

        while non_starter_pos < code_points.size && !suffixes.empty?
          # get next code point (possibly non-starter)
          non_starter_code_point = code_points[non_starter_pos]
          combining_class        = TwitterCldr::Normalization::Base.combining_class_for(non_starter_code_point)

          # code point is a starter or combining class has been already used (non-starter is 'blocked' from the prefix)
          break if combining_class == 0 || used_combining_classes[combining_class]

          used_combining_classes[combining_class] = true

          # Try to find collation elements for [prefix + non-starter] code points sequence. As the subtrie contains
          # suffixes (without prefix) we pass only non-starter itself.
          new_collation_elements, _, new_suffixes = suffixes.find_prefix([non_starter_code_point])

          if new_collation_elements
            # non-starter with a collation elements sequence corresponding to [prefix + non-starter] accepted
            collation_elements = new_collation_elements
            suffixes           = new_suffixes

            # Remove non-starter from its position in the sequence. Then we can move further from the same position.
            code_points.delete_at(non_starter_pos)
          else
            # move to the next code point
            non_starter_pos += 1
          end
        end

        collation_elements
      end

      def implicit_collation_elements(code_points)
        TwitterCldr::Collation::ImplicitCollationElements.for_code_point(code_points.shift)
      end

      class << self

        # Loads and memoizes the default fractional collation elements trie.
        #
        def default_trie
          @default_trie ||= TwitterCldr::Collation::TrieLoader.load_default_trie.lock
        end

        def tailored_trie(locale)
          tailored_tries_cache[locale]
        end

        private

        def tailored_tries_cache
          @tailored_tries_cache ||= Hash.new { |hash, locale| hash[locale] = load_tailored_trie(locale) }
        end

        def load_tailored_trie(locale)
          TwitterCldr::Collation::TrieLoader.load_tailored_trie(locale, default_trie).lock
        end

      end

    end

  end
end


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

import static org.jctools.queues.CircularArrayOffsetCalculator.allocate;
import static org.jctools.util.UnsafeAccess.UNSAFE;
import static org.jctools.util.UnsafeRefArrayAccess.REF_ARRAY_BASE;
import static org.jctools.util.UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
import static org.jctools.util.UnsafeRefArrayAccess.lvElement;
import static org.jctools.util.UnsafeRefArrayAccess.soElement;

import java.lang.reflect.Field;
import java.util.AbstractQueue;
import java.util.Iterator;

import org.jctools.util.Pow2;

abstract class BaseMpscLinkedArrayQueuePad1<E> extends AbstractQueue<E> {
    long p01, p02, p03, p04, p05, p06, p07;
    long p10, p11, p12, p13, p14, p15, p16, p17;
}

abstract class BaseMpscLinkedArrayQueueProducerFields<E> extends BaseMpscLinkedArrayQueuePad1<E> {
    protected long producerIndex;
}

abstract class BaseMpscLinkedArrayQueuePad2<E> extends BaseMpscLinkedArrayQueueProducerFields<E> {
    long p01, p02, p03, p04, p05, p06, p07;
    long p10, p11, p12, p13, p14, p15, p16, p17;
}

abstract class BaseMpscLinkedArrayQueueConsumerFields<E> extends BaseMpscLinkedArrayQueuePad2<E> {
    protected long consumerMask;
    protected E[] consumerBuffer;
    protected long consumerIndex;
}

abstract class BaseMpscLinkedArrayQueuePad3<E> extends BaseMpscLinkedArrayQueueConsumerFields<E> {
    long p0, p1, p2, p3, p4, p5, p6, p7;
    long p10, p11, p12, p13, p14, p15, p16, p17;
}

abstract class BaseMpscLinkedArrayQueueColdProducerFields<E> extends BaseMpscLinkedArrayQueuePad3<E> {
    protected volatile long producerLimit;
    protected long producerMask;
    protected E[] producerBuffer;
}

/**
 * An MPSC array queue which starts at initialCapacity and grows to maxCapacity in linked chunks
 * of the initial size. The queue grows only when the current buffer is full and elements are not copied on
 * resize, instead a link to the new buffer is stored in the old buffer for the consumer to follow.

 *
 * @param <E>
 */
public abstract class BaseMpscLinkedArrayQueue<E> extends BaseMpscLinkedArrayQueueColdProducerFields<E>
        implements MessagePassingQueue<E>, QueueProgressIndicators {
    // No post padding here, subclasses must add

    private final static long P_INDEX_OFFSET;
    private final static long C_INDEX_OFFSET;
    private final static long P_LIMIT_OFFSET;

    static {
        try {
            Field iField = BaseMpscLinkedArrayQueueProducerFields.class.getDeclaredField("producerIndex");
            P_INDEX_OFFSET = UNSAFE.objectFieldOffset(iField);
        }
        catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        try {
            Field iField = BaseMpscLinkedArrayQueueConsumerFields.class.getDeclaredField("consumerIndex");
            C_INDEX_OFFSET = UNSAFE.objectFieldOffset(iField);
        }
        catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        try {
            Field iField = BaseMpscLinkedArrayQueueColdProducerFields.class.getDeclaredField("producerLimit");
            P_LIMIT_OFFSET = UNSAFE.objectFieldOffset(iField);
        }
        catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    private final static Object JUMP = new Object();

    /**
     * @param initialCapacity the queue initial capacity. If chunk size is fixed this will be the chunk size.
     *        Must be 2 or more.
     */
    public BaseMpscLinkedArrayQueue(final int initialCapacity) {
        if (initialCapacity < 2) {
            throw new IllegalArgumentException("Initial capacity must be 2 or more");
        }

        int p2capacity = Pow2.roundToPowerOfTwo(initialCapacity);
        // leave lower bit of mask clear
        long mask = (p2capacity - 1) << 1;
        // need extra element to point at next array
        E[] buffer = allocate(p2capacity + 1);
        producerBuffer = buffer;
        producerMask = mask;
        consumerBuffer = buffer;
        consumerMask = mask;
        soProducerLimit(mask); // we know it's all empty to start with
    }

    @Override
    public final Iterator<E> iterator() {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return this.getClass().getName();
    }

    @Override
    public boolean offer(final E e) {
        if (null == e) {
            throw new NullPointerException();
        }

        long mask;
        E[] buffer;
        long pIndex;

        while (true) {
            long producerLimit = lvProducerLimit();
            pIndex = lvProducerIndex();
            // lower bit is indicative of resize, if we see it we spin until it's cleared
            if ((pIndex & 1) == 1) {
                continue;
            }
            // pIndex is even (lower bit is 0) -> actual index is (pIndex >> 1)

            // mask/buffer may get changed by resizing -> only use for array access after successful CAS.
            mask = this.producerMask;
            buffer = this.producerBuffer;
            // a successful CAS ties the ordering, lv(pIndex)-[mask/buffer]->cas(pIndex)

            // assumption behind this optimization is that queue is almost always empty or near empty
            if (producerLimit <= pIndex) {
                int result = offerSlowPath(mask, pIndex, producerLimit);
                switch (result) {
                case 0:
                    break;
                case 1:
                    continue;
                case 2:
                    return false;
                case 3:
                    resize(mask, buffer, pIndex, e);
                    return true;
                }
            }

            if (casProducerIndex(pIndex, pIndex + 2)) {
                break;
            }
        }
        // INDEX visible before ELEMENT, consistent with consumer expectation
        final long offset = modifiedCalcElementOffset(pIndex, mask);
        soElement(buffer, offset, e);
        return true;
    }

    /**
     * We do not inline resize into this method because we do not resize on fill.
     */
    private int offerSlowPath(long mask, long pIndex, long producerLimit) {
        int result;
        final long cIndex = lvConsumerIndex();
        long bufferCapacity = getCurrentBufferCapacity(mask);
        result = 0;// 0 - goto pIndex CAS
        if (cIndex + bufferCapacity > pIndex) {
            if (!casProducerLimit(producerLimit, cIndex + bufferCapacity)) {
                result = 1;// retry from top
            }
        }
        // full and cannot grow
        else if (availableInQueue(pIndex, cIndex) <= 0) {
            result = 2;// -> return false;
        }
        // grab index for resize -> set lower bit
        else if (casProducerIndex(pIndex, pIndex + 1)) {
            result = 3;// -> resize
        }
        else {
            result = 1;// failed resize attempt, retry from top
        }
        return result;
    }

    /**
     * @return available elements in queue * 2
     */
    protected abstract long availableInQueue(long pIndex, final long cIndex);

    /**
     * This method assumes index is actually (index << 1) because lower bit is used for resize. This is
     * compensated for by reducing the element shift. The computation is constant folded, so there's no cost.
     */
    private static long modifiedCalcElementOffset(long index, long mask) {
        return REF_ARRAY_BASE + ((index & mask) << (REF_ELEMENT_SHIFT - 1));
    }

    /**
     * {@inheritDoc}
     *

     * This implementation is correct for single consumer thread use only.
     */
    @SuppressWarnings("unchecked")
    @Override
    public E poll() {
        final E[] buffer = consumerBuffer;
        final long index = consumerIndex;
        final long mask = consumerMask;

        final long offset = modifiedCalcElementOffset(index, mask);
        Object e = lvElement(buffer, offset);// LoadLoad
        if (e == null) {
            if (index != lvProducerIndex()) {
                // poll() == null iff queue is empty, null element is not strong enough indicator, so we must
                // check the producer index. If the queue is indeed not empty we spin until element is
                // visible.
                do {
                    e = lvElement(buffer, offset);
                } while (e == null);
            }
            else {
                return null;
            }
        }
        if (e == JUMP) {
            final E[] nextBuffer = getNextBuffer(buffer, mask);
            return newBufferPoll(nextBuffer, index);
        }
        soElement(buffer, offset, null);
        soConsumerIndex(index + 2);
        return (E) e;
    }

    /**
     * {@inheritDoc}
     *

     * This implementation is correct for single consumer thread use only.
     */
    @SuppressWarnings("unchecked")
    @Override
    public E peek() {
        final E[] buffer = consumerBuffer;
        final long index = consumerIndex;
        final long mask = consumerMask;

        final long offset = modifiedCalcElementOffset(index, mask);
        Object e = lvElement(buffer, offset);// LoadLoad
        if (e == null && index != lvProducerIndex()) {
            // peek() == null iff queue is empty, null element is not strong enough indicator, so we must
            // check the producer index. If the queue is indeed not empty we spin until element is visible.
            while ((e = lvElement(buffer, offset)) == null)
                ;
        }
        if (e == JUMP) {
            return newBufferPeek(getNextBuffer(buffer, mask), index);
        }
        return (E) e;
    }

    @SuppressWarnings("unchecked")
    private E[] getNextBuffer(final E[] buffer, final long mask) {
        final long nextArrayOffset = nextArrayOffset(mask);
        final E[] nextBuffer = (E[]) lvElement(buffer, nextArrayOffset);
        soElement(buffer, nextArrayOffset, null);
        return nextBuffer;
    }

    private long nextArrayOffset(final long mask) {
        return modifiedCalcElementOffset(mask + 2, Long.MAX_VALUE);
    }

    private E newBufferPoll(E[] nextBuffer, final long index) {
        final long offsetInNew = newBufferAndOffset(nextBuffer, index);
        final E n = lvElement(nextBuffer, offsetInNew);// LoadLoad
        if (n == null) {
            throw new IllegalStateException("new buffer must have at least one element");
        }
        soElement(nextBuffer, offsetInNew, null);// StoreStore
        soConsumerIndex(index + 2);
        return n;
    }

    private E newBufferPeek(E[] nextBuffer, final long index) {
        final long offsetInNew = newBufferAndOffset(nextBuffer, index);
        final E n = lvElement(nextBuffer, offsetInNew);// LoadLoad
        if (null == n) {
            throw new IllegalStateException("new buffer must have at least one element");
        }
        return n;
    }

    private long newBufferAndOffset(E[] nextBuffer, final long index) {
        consumerBuffer = nextBuffer;
        consumerMask = (nextBuffer.length - 2) << 1;
        final long offsetInNew = modifiedCalcElementOffset(index, consumerMask);
        return offsetInNew;
    }

    @Override
    public final int size() {
        // NOTE: because indices are on even numbers we cannot use the size util.

        /*
         * It is possible for a thread to be interrupted or reschedule between the read of the producer and
         * consumer indices, therefore protection is required to ensure size is within valid range. In the
         * event of concurrent polls/offers to this method the size is OVER estimated as we read consumer
         * index BEFORE the producer index.
         */
        long after = lvConsumerIndex();
        long size;
        while (true) {
            final long before = after;
            final long currentProducerIndex = lvProducerIndex();
            after = lvConsumerIndex();
            if (before == after) {
                size = ((currentProducerIndex - after) >> 1);
                break;
            }
        }
        // Long overflow is impossible, so size is always positive. Integer overflow is possible for the unbounded
        // indexed queues.
        if (size > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        else {
            return (int) size;
        }
    }

    @Override
    public final boolean isEmpty() {
        // Order matters!
        // Loading consumer before producer allows for producer increments after consumer index is read.
        // This ensures this method is conservative in it's estimate. Note that as this is an MPMC there is
        // nothing we can do to make this an exact method.
        return (this.lvConsumerIndex() == this.lvProducerIndex());
    }
    private long lvProducerIndex() {
        return UNSAFE.getLongVolatile(this, P_INDEX_OFFSET);
    }

    private long lvConsumerIndex() {
        return UNSAFE.getLongVolatile(this, C_INDEX_OFFSET);
    }

    private void soProducerIndex(long v) {
        UNSAFE.putOrderedLong(this, P_INDEX_OFFSET, v);
    }

    private boolean casProducerIndex(long expect, long newValue) {
        return UNSAFE.compareAndSwapLong(this, P_INDEX_OFFSET, expect, newValue);
    }

    private void soConsumerIndex(long v) {
        UNSAFE.putOrderedLong(this, C_INDEX_OFFSET, v);
    }

    private long lvProducerLimit() {
        return producerLimit;
    }

    private boolean casProducerLimit(long expect, long newValue) {
        return UNSAFE.compareAndSwapLong(this, P_LIMIT_OFFSET, expect, newValue);
    }

    private void soProducerLimit(long v) {
        UNSAFE.putOrderedLong(this, P_LIMIT_OFFSET, v);
    }

    @Override
    public long currentProducerIndex() {
        return lvProducerIndex() / 2;
    }

    @Override
    public long currentConsumerIndex() {
        return lvConsumerIndex() / 2;
    }

    @Override
    public abstract int capacity();

    @Override
    public boolean relaxedOffer(E e) {
        return offer(e);
    }

    @SuppressWarnings("unchecked")
    @Override
    public E relaxedPoll() {
        final E[] buffer = consumerBuffer;
        final long index = consumerIndex;
        final long mask = consumerMask;

        final long offset = modifiedCalcElementOffset(index, mask);
        Object e = lvElement(buffer, offset);// LoadLoad
        if (e == null) {
            return null;
        }
        if (e == JUMP) {
            final E[] nextBuffer = getNextBuffer(buffer, mask);
            return newBufferPoll(nextBuffer, index);
        }
        soElement(buffer, offset, null);
        soConsumerIndex(index + 2);
        return (E) e;
    }

    @SuppressWarnings("unchecked")
    @Override
    public E relaxedPeek() {
        final E[] buffer = consumerBuffer;
        final long index = consumerIndex;
        final long mask = consumerMask;

        final long offset = modifiedCalcElementOffset(index, mask);
        Object e = lvElement(buffer, offset);// LoadLoad
        if (e == JUMP) {
            return newBufferPeek(getNextBuffer(buffer, mask), index);
        }
        return (E) e;
    }

    @Override
    public int fill(Supplier<E> s, int batchSize) {
        long mask;
        E[] buffer;
        long pIndex;
        int claimedSlots;
        while (true) {
            long producerLimit = lvProducerLimit();
            pIndex = lvProducerIndex();
            // lower bit is indicative of resize, if we see it we spin until it's cleared
            if ((pIndex & 1) == 1) {
                continue;
            }
            // pIndex is even (lower bit is 0) -> actual index is (pIndex >> 1)

            // NOTE: mask/buffer may get changed by resizing -> only use for array access after successful CAS.
            // Only by virtue ofloading them between the lvProcducerIndex and a successful casProducerIndex are they
            // safe to use.
            mask = this.producerMask;
            buffer = this.producerBuffer;
            // a successful CAS ties the ordering, lv(pIndex)->[mask/buffer]->cas(pIndex)

            // we want 'limit' slots, but will settle for whatever is visible to 'producerLimit'
            long batchIndex = Math.min(producerLimit, pIndex + 2 * batchSize);

            if (pIndex == producerLimit || producerLimit < batchIndex) {
                int result = offerSlowPath(mask, pIndex, producerLimit);
                switch (result) {
                case 1:
                    continue;
                case 2:
                    return 0;
                case 3:
                    resize(mask, buffer, pIndex, s.get());
                    return 1;
                }
            }

            // claim limit slots at once
            if (casProducerIndex(pIndex, batchIndex)) {
                claimedSlots = (int) ((batchIndex - pIndex) / 2);
                break;
            }
        }

        int i = 0;
        for (i = 0; i < claimedSlots; i++) {
            final long offset = modifiedCalcElementOffset(pIndex + 2 * i, mask);
            soElement(buffer, offset, s.get());
        }
        return claimedSlots;
    }

    private void resize(long oldMask, E[] oldBuffer, long pIndex, final E e) {
        int newBufferLength = getNextBufferSize(oldBuffer);
        final E[] newBuffer = allocate(newBufferLength);

        producerBuffer = newBuffer;
        final int newMask = (newBufferLength - 2) << 1;
        producerMask = newMask;

        final long offsetInOld = modifiedCalcElementOffset(pIndex, oldMask);
        final long offsetInNew = modifiedCalcElementOffset(pIndex, newMask);

        soElement(newBuffer, offsetInNew, e);// element in new array
        soElement(oldBuffer, nextArrayOffset(oldMask), newBuffer);// buffer linked

        // ASSERT code
        final long cIndex = lvConsumerIndex();
        final long availableInQueue = availableInQueue(pIndex, cIndex);
        if (availableInQueue <= 0) {
            throw new IllegalStateException();
        }

        // Invalidate racing CASs
        // We never set the limit beyond the bounds of a buffer
        soProducerLimit(pIndex + Math.min(newMask, availableInQueue));

        // make resize visible to the other producers
        soProducerIndex(pIndex + 2);

        // INDEX visible before ELEMENT, consistent with consumer expectation

        // make resize visible to consumer
        soElement(oldBuffer, offsetInOld, JUMP);
    }

    /**
     * @return next buffer size(inclusive of next array pointer)
     */
    protected abstract int getNextBufferSize(E[] buffer);

    /**
     * @return current buffer capacity for elements (excluding next pointer and jump entry) * 2
     */
    protected abstract long getCurrentBufferCapacity(long mask);

    @Override
    public int fill(Supplier<E> s) {
        long result = 0;// result is a long because we want to have a safepoint check at regular intervals
        final int capacity = capacity();
        do {
            final int filled = fill(s, MpmcArrayQueue.RECOMENDED_OFFER_BATCH);
            if (filled == 0) {
                return (int) result;
            }
            result += filled;
        } while (result <= capacity);
        return (int) result;
    }

    @Override
    public void fill(Supplier<E> s,
            WaitStrategy w,
            ExitCondition exit) {

        while (exit.keepRunning()) {
            while (fill(s, MpmcArrayQueue.RECOMENDED_OFFER_BATCH) != 0 && exit.keepRunning()) {
                continue;
            }
            int idleCounter = 0;
            while (exit.keepRunning() && fill(s, MpmcArrayQueue.RECOMENDED_OFFER_BATCH) == 0) {
                idleCounter = w.idle(idleCounter);
            }

        }
    }

    @Override
    public void drain(Consumer<E> c, WaitStrategy w, ExitCondition exit) {
        int idleCounter = 0;
        while (exit.keepRunning()) {
            E e = relaxedPoll();
            if (e == null) {
                idleCounter = w.idle(idleCounter);
                continue;
            }
            idleCounter = 0;
            c.accept(e);
        }
    }

    @Override
    public int drain(Consumer<E> c) {
        return drain(c, capacity());
    }

    @Override
    public int drain(final Consumer<E> c, final int limit) {
        /**
         * Impl note: there are potentially some small gains to be had by manually inlining relaxedPoll() and hoisting
         * reused fields out to reduce redundant reads.
         */
        int i = 0;
        E m;
        for (; i < limit && (m = relaxedPoll()) != null; i++) {
            c.accept(m);
        }
        return i;
    }
}


text:
package org.wipqueue.consumerthread;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.wipqueue.queue.WipQueueImpl;
import org.wipqueue.WipStrategy;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

public class WipConsumerThreadFactoryDefaultTest {

    @Mock
    private WipStrategy strategy;
    @Mock
    private WipQueueImpl<String, String> queue;
    @Mock
    private WipConsumerThreadFactory<String,String> consumerThreadFactory;

    ThrottledConsumerThreadFactory<String, String> factory;

    @Before
    public void setup() {
        initMocks(this);
        factory = new ThrottledConsumerThreadFactory<String, String>(consumerThreadFactory, 10);

        given(consumerThreadFactory.newConsumer((WipQueueImpl) any(), (WipStrategy) any())).willReturn(true);
    }

    @Test
    public void startConsumersShouldDelegate() {

        factory.startConsumers(queue, strategy, 3);

        verify(consumerThreadFactory).startConsumers(queue, strategy, 3);
    }

    @Test
    public void newConsumerShouldDelegate() {

        factory.newConsumer(queue, strategy);

        verify(consumerThreadFactory).newConsumer(queue, strategy);
    }

    @Test
    public void consumerCountShouldDelegate() {

        factory.consumerCount();

        verify(consumerThreadFactory).consumerCount();
    }

    @Test
    public void stopConsumerShouldDelegate() {

        factory.stopConsumer();

        verify(consumerThreadFactory).stopConsumer();
    }

    @Test
    public void waitToStartShouldDelegate() throws InterruptedException {

        factory.waitToStart();

        verify(consumerThreadFactory).waitToStart();
    }

    @Test
    public void givenAConsumerIsCurrentlyBeingCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
        // given
        factory.newConsumer(queue, strategy);

        // when
        assertThat(factory.newConsumer(null, null), is(false));

        // then
        verify(consumerThreadFactory, times(1)).newConsumer(queue, strategy);
        verify(consumerThreadFactory, never()).newConsumer(null, null);
    }

    @Test
    public void givenManyConsumersAreCurrentlyBeingCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
        // given
        factory.startConsumers(queue, strategy, 3);

        // when
        assertThat(factory.newConsumer(null, null), is(false));

        // then
        verify(consumerThreadFactory, times(1)).startConsumers(queue, strategy, 3);
        verify(consumerThreadFactory, never()).newConsumer(null, null);
    }

    @Test
    public void givenAConsumerHasRecentlyBeenCreatedWhenSufficientTimeHasPassedThenANewConsumerCanBeCreated() throws Exception {
        // given
        factory.newConsumer(queue, strategy);

        // when
        Thread.sleep(20);

        // then
        assertThat(factory.newConsumer(null, null), is(true));

        // then
        verify(consumerThreadFactory, times(1)).newConsumer(queue, strategy);
        verify(consumerThreadFactory, times(1)).newConsumer(null, null);
    }
//    @Test
//    public void givenManyConsumersAreCurrentlyBeingCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
//        WipConsumerThreadFactoryDefault<String, String> factory = new WipConsumerThreadFactoryDefault<String, String>(consumerFactory, wipQueueThreadFactory, 1000);
//
//        given(wipQueueThread.isStarted()).willReturn(false); // will never start
//        factory.startConsumers(queue, strategy, 5);
//
//        factory.newConsumer(queue, strategy);
//
//        verify(wipQueueThreadFactory, times(5)).newAndRunningWipQueueThread(strategy, queue, consumer);
//        assertThat(factory.consumerCount(), is(5));
//    }

//    @Test
//    public void givenAConsumerHasRecentlyBeenCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
//        WipConsumerThreadFactoryDefault<String, String> factory = new WipConsumerThreadFactoryDefault<String, String>(consumerFactory, wipQueueThreadFactory, 1000);
//
//        given(wipQueueThread.isStarted()).willReturn(true); // will immediately start
//        factory.newConsumer(queue, strategy);
//
//        factory.newConsumer(queue, strategy);
//
//        verify(wipQueueThreadFactory, times(1)).newAndRunningWipQueueThread(strategy, queue, consumer);
//        assertThat(factory.consumerCount(), is(1));
//    }

//    @Test
//    public void givenAConsumerHasRecentlyBeenStoppedWhenNewConsumerIsCalledThenNothingShouldHappen() throws InterruptedException {
//        WipConsumerThreadFactoryDefault<String, String> factory = new WipConsumerThreadFactoryDefault<String, String>(consumerFactory, wipQueueThreadFactory, 5);
//
//        given(wipQueueThread.isStarted()).willReturn(true); // will immediately start
//        factory.newConsumer(queue, strategy);
//        Thread.sleep(10);
//
//        factory.stopConsumer();
//
//        // when
//        factory.newConsumer(queue, strategy);
//
//        verify(wipQueueThreadFactory, times(1)).newAndRunningWipQueueThread(strategy, queue, consumer); // only the first new
//        assertThat(factory.consumerCount(), is(0)); // the first was removed, but the second was added too soon after the stop
//    }

    @Test
    public void shouldWaitForConsumersToStart() {
        // pain
    }

}


text:
from parseJSONdata import parseData

# Edit Here
negativeFileName = 'ibm_neg_'
postiveFileName = 'ibm_pos_'
neutralFileName = 'ibm_neu_'
numNegativ = 12
numPositive = 1
numNeutral = 2

parseData(negativeFileName, postiveFileName, neutralFileName, numNegativ, numPositive, numNeutral)


text:
// -----------------------------------------------------------------------
// <copyright file="RandomPoints.cs" company="">
// Christian Woltering, Triangle.NET, http://triangle.codeplex.com/
// </copyright>
// -----------------------------------------------------------------------

namespace MeshExplorer.Generators
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using TriangleNet.Geometry;

    /// <summary>
    /// Simple random points generator.
    /// </summary>
    public class RandomPoints : BaseGenerator
    {
        public RandomPoints()
        {
            name = "Random Points";
            description = "";
            parameter = 3;

            descriptions[0] = "Number of points:";
            descriptions[1] = "Width:";
            descriptions[2] = "Height:";

            ranges[0] = new int[] { 5, 5000 };
            ranges[1] = new int[] { 10, 200 };
            ranges[2] = new int[] { 10, 200 };
        }

        public override InputGeometry Generate(double param0, double param1, double param2)
        {
            int numPoints = GetParamValueInt(0, param0);
            numPoints = (numPoints / 10) * 10;

            if (numPoints < 5)
            {
                numPoints = 5;
            }

            InputGeometry input = new InputGeometry(numPoints);

            int width = GetParamValueInt(1, param1);
            int height = GetParamValueInt(2, param2);

            for (int i = 0; i < numPoints; i++)
            {
                input.AddPoint(Util.Random.NextDouble() * width,
                        Util.Random.NextDouble() * height);
            }

            return input;
        }
    }
}