text:
#import "SFMethodInterceptor.h"
#import <objc/message.h>
#import <objc/runtime.h>

/** This static dictionary contains a map of <class, selector> to <interceptor>.
 In other words, it helps get the interceptor instance for a given
 pair of class and selector. The class is the class to intercept
 an the selector is the selector to intercept
 */
static NSMutableDictionary *InterceptorsForClassAndSelector = nil;

/** This method returns a key given a class and a selector
 */
static NSString * interceptorKey(Class clazz, SEL selector) {
    return [NSString stringWithFormat:@"%@:%@", NSStringFromClass(clazz), NSStringFromSelector(selector)];
}

@interface SFMethodInterceptor ()

/** The instance or class of the intercepted object.
 */
@property (nonatomic, weak) id interceptedObject;

/** Returns a selector who's method implementation contains
 the original method that was intercepted.
 This selector has been renamed to ensure it doesn't collide
 with the original selector or any other existing method
 */
@property (nonatomic, readonly) SEL originalMethodRenamedSelector;
@property (nonatomic, readonly) SEL originalMethodRenamedSelectorForBlock;

@property (nonatomic, strong) NSMethodSignature *interceptedMethodSignature;

@end

@implementation SFMethodInterceptor

+ (void)initialize {
    if (self == [SFMethodInterceptor class] && nil == InterceptorsForClassAndSelector) {
        InterceptorsForClassAndSelector = [NSMutableDictionary dictionary];
    }
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _enabled = NO;
    }
    return self;
}

- (void)dealloc {
    @synchronized (InterceptorsForClassAndSelector) {
        [InterceptorsForClassAndSelector removeObjectForKey:interceptorKey(self.classToIntercept, self.selectorToIntercept)];
    }
}

- (SEL)originalMethodRenamedSelector {
    // Rename the original selector by inserting a string that ensure it's unique
    NSMutableString *name = [[NSMutableString alloc] initWithCString:sel_getName(self.selectorToIntercept) encoding:NSASCIIStringEncoding];
    [name insertString:@"__method_forwarded_" atIndex:0];

    // use sel_registerName() and not @selector to avoid warning
    SEL sel = sel_registerName([name cStringUsingEncoding:NSASCIIStringEncoding]);
    return sel;
}

- (SEL)originalMethodRenamedSelectorForBlock {
    // Rename the original selector by inserting a string that ensure it's unique
    NSMutableString *name = [[NSMutableString alloc] initWithCString:sel_getName(self.selectorToIntercept) encoding:NSASCIIStringEncoding];
    [name insertString:@"__method_forwarded_block_" atIndex:0];

    // use sel_registerName() and not @selector to avoid warning
    SEL sel = sel_registerName([name cStringUsingEncoding:NSASCIIStringEncoding]);
    return sel;
}

#pragma mark - Forwarding & Swizzling

- (id)forwardingTargetForSelector:(SEL)aSelector {
    // Here `self` is expected to refer to the class instance that's being intercepted
    if ([self isKindOfClass:[SFMethodInterceptor class]]) {
        // If not, then it means some unknown method is called on the SFMethodInterceptor class
        // instance which is left untouched.
        return [super forwardingTargetForSelector:aSelector];
    } else {
        // Let's find out which interceptor instance is managing
        // this selector and class
        SFMethodInterceptor *interceptor = InterceptorsForClassAndSelector[interceptorKey([self class], aSelector)];
        if (interceptor) {
            interceptor.interceptedObject = self;
            return interceptor;
        } else {
            return [super forwardingTargetForSelector:aSelector];
        }
    }
}

/** This method is invoked on the SFMethodInterceptor class when
 a unknown selector is invoked on that class. Normally, it's
 the selector that's being intercepted that's provided here.
 We return the intercepted method signature that was captured
 when the interceptor was created so the Objective-C forwarding
 machinery can correctly create the invocation.
 */
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    return self.interceptedMethodSignature;
}

/** After `methodSignatureForSelector` has been invoked, this
 methid is invoked with the invocation that contains the description
 of the message that was intercepted.
 This is here that we intercept the message, call back any registered
 callback blocks and then invoke the original method code (or skip it).
 */
- (void)forwardInvocation:(NSInvocation *)anInvocation {
    if ([self isKindOfClass:[SFMethodInterceptor class]]) {
        anInvocation.target = self.interceptedObject;
        anInvocation.selector = self.originalMethodRenamedSelector;

        [self invokeCallbacks:anInvocation];
    } else {
        [super forwardInvocation:anInvocation];
    }
}

- (void)invokeCallbacks:(NSInvocation*)anInvocation {
    if (self.targetBeforeBlock) {
        self.targetBeforeBlock(anInvocation);
    }
    NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];
    if (self.targetReplaceBlock) {
        self.targetReplaceBlock(anInvocation);
    } else {
        [self invokeOriginal:anInvocation];
    }
    NSTimeInterval endTime = [NSDate timeIntervalSinceReferenceDate];
    if (self.targetAfterBlock) {
        self.targetAfterBlock(anInvocation, endTime - startTime);
    }
}

- (void)invokeOriginal:(NSInvocation*)anInvocation {
    anInvocation.selector = self.originalMethodRenamedSelector;
    [anInvocation invokeWithTarget:self.interceptedObject];
}

- (void)swizzle {
    if (_enabled) {
        return;
    }
    if (self.instanceMethod) {
        Method originalMethod = class_getInstanceMethod(self.classToIntercept, self.selectorToIntercept);
        const char *methodTypes = method_getTypeEncoding(originalMethod);

        InterceptorsForClassAndSelector[interceptorKey(self.classToIntercept, self.selectorToIntercept)] = self;

        // forward method
        IMP originalMethodIMP = method_setImplementation(originalMethod, (IMP)_objc_msgForward);
        NSAssert(originalMethodIMP, @"Original method implementation must be found");

        SEL forwardingSelector = @selector(forwardingTargetForSelector:);
        Method forwardingMethod = class_getInstanceMethod([self class], forwardingSelector);
        IMP forwardingMethodIMP = method_getImplementation(forwardingMethod);
        const char *forwardingMethodTypes = method_getTypeEncoding(forwardingMethod);
        class_replaceMethod(self.classToIntercept, forwardingSelector, forwardingMethodIMP, forwardingMethodTypes);

        self.interceptedMethodSignature = [self.classToIntercept instanceMethodSignatureForSelector:self.selectorToIntercept];

        class_replaceMethod(self.classToIntercept, self.originalMethodRenamedSelector, originalMethodIMP, methodTypes);
    } else {
        // Note: class method must be added to the class's metaclass
        Class originalMetaClass = objc_getMetaClass(object_getClassName(self.classToIntercept));

        Method originalMethod = class_getClassMethod(originalMetaClass, self.selectorToIntercept);
        const char *methodTypes = method_getTypeEncoding(originalMethod);

        InterceptorsForClassAndSelector[interceptorKey(self.classToIntercept, self.selectorToIntercept)] = self;

        // forward method
        IMP originalMethodIMP = method_setImplementation(originalMethod, (IMP)_objc_msgForward);
        NSAssert(originalMethodIMP, @"Original method implementation must be found");

        SEL forwardingSelector = @selector(forwardingTargetForSelector:);
        Method forwardingMethod = class_getInstanceMethod([self class], forwardingSelector);
        IMP forwardingMethodIMP = method_getImplementation(forwardingMethod);
        const char *forwardingMethodTypes = method_getTypeEncoding(forwardingMethod);
        class_replaceMethod(originalMetaClass, forwardingSelector, forwardingMethodIMP, forwardingMethodTypes);

        self.interceptedMethodSignature = [self.classToIntercept methodSignatureForSelector:self.selectorToIntercept];

        class_replaceMethod(originalMetaClass, self.originalMethodRenamedSelector, originalMethodIMP, methodTypes);
    }
    _enabled = YES;
    NSLog(@"%@ is ENABLED", self);
}

- (void)unswizzle {
    if (!_enabled) {
        return;
    }
    if (self.instanceMethod) {
        Method targetMethod = class_getInstanceMethod(self.classToIntercept, self.selectorToIntercept);
        Method originalMethod = class_getInstanceMethod(self.classToIntercept, self.originalMethodRenamedSelector);
        method_exchangeImplementations(originalMethod, targetMethod);
    } else {
        Method targetMethod = class_getClassMethod(self.classToIntercept, self.selectorToIntercept);
        Method originalMethod = class_getClassMethod(self.classToIntercept, self.originalMethodRenamedSelector);
        method_exchangeImplementations(originalMethod, targetMethod);
    }
    _enabled = NO;
    NSLog(@"%@ is DISABLED", self);
}

- (void)setEnabled:(BOOL)enabled {
    if (_enabled != enabled) {
        [self willChangeValueForKey:@"enabled"];
        if (enabled) {
            [self swizzle];
        } else {
            [self unswizzle];
        }
        _enabled = enabled;
        [self didChangeValueForKey:@"enabled"];
    }
}

- (NSString*)description {
    return [NSString stringWithFormat:@"<%@: %p, %@::%@>", NSStringFromClass([self class]), self, NSStringFromClass(self.classToIntercept), NSStringFromSelector(self.selectorToIntercept)];
}

@end


text:
module StorytimeAdmin
  class ResourceGenerator < Rails::Generators::NamedBase
    source_root File.expand_path('../templates', __FILE__)

    def generate_controller
      template 'controller.rb', "app/controllers/storytime_admin/#{table_name}_controller.rb"
    end

  private
    def table_name
      @table_name ||= file_path.tableize
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
module TestExpense (expenseSpec) where

import Test.Hspec (Spec, describe, it, shouldBe)

import qualified Data.Time.Calendar.Compat as DT

import qualified Data.Expenses.Expense as E

expenseSpec :: Spec
expenseSpec =
  describe "Data.Expenses.Expense" $
    describe "numDaysAfter" $ do
      it "should compute Tue is 1 day after Mon" $
        E.numDaysAfter DT.Monday DT.Tuesday `shouldBe` (1 :: Int)
      it "should compute Mon is 6 days after Tue" $
        E.numDaysAfter DT.Tuesday DT.Monday `shouldBe` (6 :: Int)


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright (c) 2010-2013 Evolveum
  ~
  ~ 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.
  -->

<objectModification
	xmlns='http://midpoint.evolveum.com/xml/ns/public/common/api-types-3'
	xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
	xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
	<oid>00000000-8888-6666-0000-100000000005</oid>
	<itemDelta>
		<t:modificationType>delete</t:modificationType>
		<t:path>c:inducement</t:path>
		<t:value id="3">
            <c:targetRef oid="00000000-76e0-48e2-86d6-3d4f02d3e1a2" type="c:OrgType"/>
		</t:value>
	</itemDelta>
</objectModification>


text:
<?php

namespace Sijot\Http\Controllers;

use Sijot\News;
use Sijot\Http\Requests\NewsValidator;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Sijot\Repositories\CategoryRepository;
use Sijot\Repositories\NewsRepository;

/**
 * Class NewsController
 *
 * @category SIJOT-Website
 * @package  Sijot\Http\Controllers
 * @author   Tim Joosten <topairy@gmail.com>
 * @license  MIT License
 * @link     http://www.st-joris-turnhout.be
 */
class NewsController extends Controller
{
    /**
     * The news database model.
     *
     * @var News
     */
    private $_newsDb;

    /**
     * The categories database model.
     *
     * @var mixed categoriesDb;
     */
    private $_categoriesDb;

    /**
     * NewsController constructor
     *
     * @param CategoryRepository  $_categoriesDb The categories database model.
     * @param NewsRepository      $_newsDb       The news database model.
     *
     * @return void
     */
    public function __construct(CategoryRepository $_categoriesDb, NewsRepository $_newsDb)
    {
        $routes = ['store', 'update', 'delete', 'create', 'index', 'status', 'getById'];

        $this->middleware('auth')->only($routes);
        $this->middleware('forbid-banned-user')->only($routes);

        $this->_categoriesDb = $_categoriesDb;
        $this->_newsDb       = $_newsDb;
    }

    /**
     * Get the news management index.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $data['title']      = 'Nieuws management';
        $data['news']       = $this->_newsDb->with(['author'])->get();
        $data['categories'] = $this->_categoriesDb->all();

        return view('news.index', $data);
    }

    /**
     * The view for creating a new item.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $data['title']      = 'Nieuw Nieuwsbericht';
        $data['categories'] = $this->_categoriesDb->with(['author', 'news'])->get();

        return view('news.create', $data);
    }

    /**
     * Try to find a news message en encode it with json.
     *
     * @param integer $newsId The news id in the database.
     *
     * @return mixed
     */
    public function getById($newsId)
    {
        try { // Try to find and output the record.
            //? Maybe we need convert this in some API form.
            return(json_encode($this->_newsDb->findOrFail($newsId)));
        } catch (ModelNotFoundException $notFoundException) { // The user is not found.
            return app()->abort(404);
        }
    }

    /**
     * Store a new news item in the database.
     *
     * @param NewsValidator $input The user input validator
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(NewsValidator $input)
    {
        $filter = ['_token', 'categories'];

        if ($item = $this->_newsDb->create($input->except($filter))) { // The news message has been stored.
            if (! is_null($input->categories)) { // There are categories find in the user input.
                $this->_newsDb->find($item->id)->categories()->attach($input->categories);
            }

            flash('Het nieuwsbericht is opgeslagen.');
        }

        return back();
    }

    /**
     * Show a specific news item in the application.
     *
     * @param integer $newsId The news id in the database.
     *
     * @return mixed
     */
    public function show($newsId)
    {
        try { // Try to find the record
            $data['news']       = $this->_newsDb->with(['author'])->findOrFail($newsId);
            $data['categories'] = $this->_categoriesDb->all();
            $data['title']      = $data['news']->title;

            return view('news.show', $data);
        } catch (ModelNotFoundException $exception) { // Record not found.
            return app()->abort(404);
        }
    }

    /**
     * Update a news item in the database.
     *
     * @param NewsValidator $input  The user input validator
     * @param integer       $newsId The news id in the database.
     *
     * @return mixed
     */
    public function update(NewsValidator $input, $newsId)
    {
        try { // Try to find the record.
            $newsItem = $this->_newsDb->findOrfail($newsId);

            if ($newsItem->update($input->except(['_token', 'categories']))) { // Record has been updated.
                $newsItem->categories()->sync($input->get('categories'));
                flash('Het nieuwsbericht is aangepast.');
            }

            return back();
        } catch (ModelNotFoundException $exception) { // Record is not found.
            return app()->abort(404);
        }
    }

    /**
     * Change the status for a news message.
     *
     * @param string  $status The status identifier for the news message.
     * @param integer $newsId The news message id in the database.
     *
     * @return mixed
     */
    public function status($status, $newsId)
    {
        try { // Try to find the news item in the database.
            $newsItem = $this->_newsDb->findOrFail($newsId);

            if ($newsItem->update(['publish' => $status])) { // Try to update the record.
                // The record has been updated.
                if ((string) $status === 'Y') { // The status has been set to 'publish'
                    flash('Het nieuwsbericht is gepubliceerd.');
                } elseif ((string) $status === 'N') { // The status has been set to 'Klad'
                    flash('Het nieuws bericht is naar een klad versie gezet.');
                }
            }

            return back(302);
        } catch (ModelNotFoundException $modelNotFoundException) { // News item not found in de database.
            return app()->abort(404);
        }
    }

    /**
     * Delete a news item in the database.
     *
     * @param integer $newsId The news id in the database.
     *
     * @return mixed
     */
    public function delete($newsId)
    {
        try { // Try to find the record.
            $news = $this->_newsDb->findOrFail($newsId);

            if ($news->delete()) { // Record has been deleted.
                flash('Het nieuwsbericht is verwijderd.');
            }

            return back(302);
        } catch (ModelNotFoundException $exception) { // Record not found.
            return app()->abort(404);
        }
    }
}


text:
# Beta Prime Random Numbers

> [Beta prime][betaprime] distributed pseudorandom numbers.

## Usage

```javascript
var betaprime = require( '@stdlib/random/base/betaprime' );
```

#### betaprime( alpha, beta )

Returns a pseudorandom number drawn from a [beta prime][betaprime] distribution with parameters `alpha` (first shape parameter) and `beta` (second shape parameter).

```javascript
var r = betaprime( 2.0, 5.0 );
// returns <number>
```

If `alpha <= 0` or `beta <= 0`, the function returns `NaN`.

```javascript
var r = betaprime( 2.0, -2.0 );
// returns NaN

r = betaprime( -2.0, 2.0 );
// returns NaN
```

If `alpha` or `beta` is `NaN`, the function returns `NaN`.

```javascript
var r = betaprime( NaN, 5.0 );
// returns NaN

r = betaprime( 2.0, NaN );
// returns NaN
```

#### betaprime.factory( \[alpha, beta, ]\[options] )

Returns a pseudorandom number generator (PRNG) for generating pseudorandom numbers drawn from a [beta prime][betaprime] distribution.

```javascript
var rand = betaprime.factory();

var r = rand( 1.5, 1.5 );
// returns <number>
```

If provided `alpha` and `beta`, the returned generator returns random variates from the specified distribution.

```javascript
// Draw from BetaPrime( 1.5, 1.5 ) distribution:
var rand = betaprime.factory( 1.5, 1.5 );

var r = rand();
// returns <number>

r = rand();
// returns <number>
```

If not provided `alpha` and `beta`, the returned generator requires that both parameters be provided at each invocation.

```javascript
var rand = betaprime.factory();

var r = rand( 1.0, 1.0 );
// returns <number>

r = rand( 3.14, 2.25 );
// returns <number>
```

The function accepts the following `options`:

-   **prng**: pseudorandom number generator for generating uniformly distributed pseudorandom numbers on the interval `[0,1)`. If provided, the function **ignores** both the `state` and `seed` options. In order to seed the returned pseudorandom number generator, one must seed the provided `prng` (assuming the provided `prng` is seedable).
-   **seed**: pseudorandom number generator seed.
-   **state**: a [`Uint32Array`][@stdlib/array/uint32] containing pseudorandom number generator state. If provided, the function ignores the `seed` option.
-   **copy**: `boolean` indicating whether to copy a provided pseudorandom number generator state. Setting this option to `false` allows sharing state between two or more pseudorandom number generators. Setting this option to `true` ensures that a returned generator has exclusive control over its internal state. Default: `true`.

To use a custom PRNG as the underlying source of uniformly distributed pseudorandom numbers, set the `prng` option.

```javascript
var minstd = require( '@stdlib/random/base/minstd' );

var rand = betaprime.factory({
    'prng': minstd.normalized
});

var r = rand( 2.0, 3.0 );
// returns <number>
```

To seed a pseudorandom number generator, set the `seed` option.

```javascript
var rand1 = betaprime.factory({
    'seed': 12345
});

var r1 = rand1( 2.0, 3.0 );
// returns <number>

var rand2 = betaprime.factory( 2.0, 3.0, {
    'seed': 12345
});

var r2 = rand2();
// returns <number>

var bool = ( r1 === r2 );
// returns true
```

To return a generator having a specific initial state, set the generator `state` option.

```javascript
var rand;
var bool;
var r;
var i;

// Generate pseudorandom numbers, thus progressing the generator state:
for ( i = 0; i < 1000; i++ ) {
    r = betaprime( 2.0, 3.0 );
}

// Create a new PRNG initialized to the current state of `betaprime`:
rand = betaprime.factory({
    'state': betaprime.state
});

// Test that the generated pseudorandom numbers are the same:
bool = ( rand( 2.0, 3.0 ) === betaprime( 2.0, 3.0 ) );
// returns true
```

#### betaprime.NAME

The generator name.

```javascript
var str = betaprime.NAME;
// returns 'betaprime'
```

#### betaprime.PRNG

The underlying pseudorandom number generator.

```javascript
var prng = betaprime.PRNG;
// returns <Function>
```

#### betaprime.seed

The value used to seed `betaprime()`.

```javascript
var rand;
var r;
var i;

// Generate pseudorandom values...
for ( i = 0; i < 100; i++ ) {
    r = betaprime( 2.0, 2.0 );
}

// Generate the same pseudorandom values...
rand = betaprime.factory( 2.0, 2.0, {
    'seed': betaprime.seed
});
for ( i = 0; i < 100; i++ ) {
    r = rand();
}
```

If provided a PRNG for uniformly distributed numbers, this value is `null`.

```javascript
var rand = betaprime.factory({
    'prng': Math.random
});

var seed = rand.seed;
// returns null
```

#### betaprime.seedLength

Length of generator seed.

```javascript
var len = betaprime.seedLength;
// returns <number>
```

If provided a PRNG for uniformly distributed numbers, this value is `null`.

```javascript
var rand = betaprime.factory({
    'prng': Math.random
});

var len = rand.seedLength;
// returns null
```

#### betaprime.state

Writable property for getting and setting the generator state.

```javascript
var r = betaprime( 2.0, 5.0 );
// returns <number>

r = betaprime( 2.0, 5.0 );
// returns <number>

// ...

// Get a copy of the current state:
var state = betaprime.state;
// returns <Uint32Array>

r = betaprime( 2.0, 5.0 );
// returns <number>

r = betaprime( 2.0, 5.0 );
// returns <number>

// Reset the state:
betaprime.state = state;

// Replay the last two pseudorandom numbers:
r = betaprime( 2.0, 5.0 );
// returns <number>

r = betaprime( 2.0, 5.0 );
// returns <number>

// ...
```

If provided a PRNG for uniformly distributed numbers, this value is `null`.

```javascript
var rand = betaprime.factory({
    'prng': Math.random
});

var state = rand.state;
// returns null
```

#### betaprime.stateLength

Length of generator state.

```javascript
var len = betaprime.stateLength;
// returns <number>
```

If provided a PRNG for uniformly distributed numbers, this value is `null`.

```javascript
var rand = betaprime.factory({
    'prng': Math.random
});

var len = rand.stateLength;
// returns null
```

#### betaprime.byteLength

Size of generator state.

```javascript
var sz = betaprime.byteLength;
// returns <number>
```

If provided a PRNG for uniformly distributed numbers, this value is `null`.

```javascript
var rand = betaprime.factory({
    'prng': Math.random
});

var sz = rand.byteLength;
// returns null
```

#### betaprime.toJSON()

Serializes the pseudorandom number generator as a JSON object.

```javascript
var o = betaprime.toJSON();
// returns { 'type': 'PRNG', 'name': '...', 'state': {...}, 'params': [] }
```

If provided a PRNG for uniformly distributed numbers, this method returns `null`.

```javascript
var rand = betaprime.factory({
    'prng': Math.random
});

var o = rand.toJSON();
// returns null
```

## Notes

-   If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set.
-   If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array).

## Examples

```javascript
var betaprime = require( '@stdlib/random/base/betaprime' );

var seed;
var rand;
var i;

// Generate pseudorandom numbers...
for ( i = 0; i < 100; i++ ) {
    console.log( betaprime( 2.0, 2.0 ) );
}

// Create a new pseudorandom number generator...
seed = 1234;
rand = betaprime.factory( 6.0, 2.0, {
    'seed': seed
});
for ( i = 0; i < 100; i++ ) {
    console.log( rand() );
}

// Create another pseudorandom number generator using a previous seed...
rand = betaprime.factory( 2.0, 2.0, {
    'seed': betaprime.seed
});
for ( i = 0; i < 100; i++ ) {
    console.log( rand() );
}
```

[betaprime]: https://en.wikipedia.org/wiki/Beta_prime_distribution

[@stdlib/array/uint32]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array/uint32


text:
from django.db.models import Sum

from moocng.mongodb import get_db

def calculate_question_mark(kq, question, user):

    """
    Calculate if the user answer is the correct one, and punctuate accordingly.
    If the user did the task right the platform gives a 10, if not, a 0.

    .. versionadded:: 0.1
    """
    db = get_db()
    answers = db.get_collection('answers')
    user_answer = answers.find_one({
        'user_id': user.id,
        'question_id': question.id
    })

    if user_answer:
        mark = question.is_correct(user_answer)
        return mark
    return 0.0

def calculate_peer_review_mark(kq, peer_review_assignment, user):

    """
    Calculate if the user has done the peer reviewed task. This is done by
    checking if the minimum reviews of the task have been done.

    .. versionadded:: 0.1
    """
    from moocng.peerreview.utils import kq_get_peer_review_score

    mark = kq_get_peer_review_score(kq, user,
                                    peer_review_assignment)
    if mark is None:
        mark = 0
    return mark

def calculate_kq_video_mark(kq, user):

    """
    Mark the video as viewed and give the user the punctuation.

    .. versionadded:: 0.1
    """
    if kq.kq_visited_by(user):
        return 10.0
    return 0.0

def calculate_kq_mark(kq, user):

    """
    Calculate is a answer was right or wrong, this is the main function that
    calls the others depending on the content (peerreview, normal, etc.)

    .. warning:: Don't use this in loops

    .. versionadded:: 0.1
    """
    from moocng.peerreview.models import PeerReviewAssignment
    mark = relative_mark = 0

    try:
        question = kq.question_set.get()
        # KQ has a question
        mark = calculate_question_mark(kq, question, user)
    except kq.question_set.model.DoesNotExist:
        try:
            # KQ has a peer review
            pra = kq.peerreviewassignment
            mark = calculate_peer_review_mark(kq, pra, user)
        except PeerReviewAssignment.DoesNotExist:
            # KQ hasn't a question or peer review
            mark = calculate_kq_video_mark(kq, user)
    relative_mark = normalize_kq_weight(kq) * mark / 100.0
    return (mark, relative_mark)

def normalize_kq_weight(kq, unit_kq_counter=None, total_weight_unnormalized=None):
    # KnowledgeQuantumResource does not send unit_kq_counter  [tastypie api]
    if unit_kq_counter is None:
        unit = kq.unit
        total_weight_unnormalized, unit_kq_counter, uni_kqs = get_unit_intermediate_calculations(unit)
    if total_weight_unnormalized == 0:
        if unit_kq_counter == 0:
            return 0
        else:
            return 100.0 / unit_kq_counter
    return (kq.weight * 100.0) / total_weight_unnormalized

def calculate_unit_mark(unit, user, normalized_unit_weight=None):
    """
    Calculate if a unit is approved.

    .. warning:: Don't use this in loops

    .. versionadded:: 0.1
    """

    if normalized_unit_weight is None:
        total_weight_unnormalized, unit_course_counter, course_units = get_course_intermediate_calculations(unit.course)
        normalized_unit_weight = normalize_unit_weight(unit, unit_course_counter, total_weight_unnormalized)
    unit_mark = 0
    kqs = get_kq_info_from_course(unit, user)
    for kq in kqs:
        unit_mark += kq['relative_mark']
    # print "Unit_mark: %d - normalized_unit_weight: %d, normalized_unit_mark: %d" % (unit_mark, normalized_unit_weight, (normalized_unit_weight * unit_mark) / 100.0)
    return (unit_mark, (normalized_unit_weight * unit_mark) / 100.0)

def get_kq_info_from_course(unit, user, db=None):
    db = db or get_db()
    data_unit = {'user_id': user.pk,
                 'unit_id': unit.pk}
    marks_kq = db.get_collection('marks_kq')
    return list(marks_kq.find(data_unit))

def normalize_unit_weight(unit, course_unit_counter, total_weight_unnormalized):
    # print "Unit: %s - Course_unit_counter: %d - total_weight_unnormalized: %d" % (unit, course_unit_counter, total_weight_unnormalized)
    if total_weight_unnormalized == 0:
        if course_unit_counter == 0 or not unit.is_scorable():
            return 0
        else:
            return 100.0 / course_unit_counter
    return (unit.weight * 100.0) / total_weight_unnormalized

def get_course_intermediate_calculations(course):
    course_units = course.unit_set.scorables()
    total_weight_unnormalized = course.unit_set.aggregate(Sum('weight'))['weight__sum']
    unit_course_counter = course_units.count()
    return (total_weight_unnormalized, unit_course_counter, course_units)

def get_unit_intermediate_calculations(unit):
    unit_kqs = unit.knowledgequantum_set.all()
    total_weight_unnormalized = unit_kqs.aggregate(Sum('weight'))['weight__sum']
    unit_kqs_counter = unit_kqs.count()
    return (total_weight_unnormalized, unit_kqs_counter, unit_kqs)

def calculate_course_mark(course, user):
    units_info = get_units_info_from_course(course, user)
    total_mark = sum([unit_info['relative_mark'] for unit_info in units_info])
    return total_mark, units_info

def get_units_info_from_course(course, user, db=None):
    db = db or get_db()
    data_course = {'user_id': user.pk,
                   'course_id': course.pk}
    marks_units = db.get_collection('marks_unit')
    return list(marks_units.find(data_course))

def get_course_mark(course, user, db=None):
    data_course = {'user_id': user.pk,
                   'course_id': course.pk}
    db = db or get_db()
    marks_course = db.get_collection('marks_course')
    mark_course_item = marks_course.find_one(data_course)
    if mark_course_item:
        total_mark = mark_course_item['mark']
    else:
        total_mark = 0
    return (total_mark, get_units_info_from_course(course, user, db=db))

def get_unit_mark(unit, user, db=None):
    data_unit = {   'user_id': user.pk,
                    'unit_id': unit.pk }
    db = db or get_db()
    mark_unit_item = db.get_collection('marks_unit').find(data_unit).limit(1)
    if mark_unit_item:
        mark_unit = mark_unit_item['mark']
    else:
        mark_unit = 0
    return mark_unit

def get_unit_relative_mark(unit, user, db=None):
    data_unit = {   'user_id': user.pk,
                    'unit_id': unit.pk }
    db = db or get_db()
    mark_unit_item = db.get_collection('marks_unit').find(data_unit).limit(1)
    if mark_unit_item:
        mark_unit = mark_unit_item['relative_mark']
    else:
        mark_unit = 0
    return mark_unit

def get_kqs_info_from_unit(unit, user, db=None):
    db = db or get_db()
    data_unit = {'user_id': user.pk,
                   'unit_id': unit.pk}
    marks_kqs = db.get_collection('marks_kq')
    return list(marks_kqs.find(data_unit))

def get_kq_mark(kq, user, db=None):
    data_unit = {   'user_id': user.pk,
                    'kq_id': kq.pk }
    db = db or get_db()
    mark_kq_item = db.get_collection('marks_kq').find(data_unit).limit(1)
    if mark_kq_item and mark_kq_item.count() > 0:
        mark_kq = mark_kq_item[0]['mark']
    else:
        mark_kq = 0

    return mark_kq

def get_kq_relative_mark(kq, user, db=None):
    data_unit = {   'user_id': user.pk,
                    'kq_id': kq.pk }
    db = db or get_db()
    mark_kq_item = db.get_collection('marks_kq').find(data_unit).limit(1)
    if mark_kq_item:
        mark_kq = mark_kq_item['relative_mark']
    else:
        mark_kq = 0
    return mark_kq


text:
'use strict';

const Buffer = require('buffer').Buffer;
const BSON = require('../register-bson');
const BSONTypeError = BSON.BSONTypeError;
const ObjectId = BSON.ObjectId;
const util = require('util');
const getSymbolFrom = require('./tools/utils').getSymbolFrom;
const isBufferOrUint8Array = require('./tools/utils').isBufferOrUint8Array;

describe('ObjectId', function () {
  it('should correctly handle objectId timestamps', function (done) {
    const a = ObjectId.createFromTime(1);
    expect(Buffer.from([0, 0, 0, 1])).to.deep.equal(a.id.slice(0, 4));
    expect(1000).to.equal(a.getTimestamp().getTime());

    const b = new ObjectId();
    b.generationTime = 1;
    expect(Buffer.from([0, 0, 0, 1])).to.deep.equal(b.id.slice(0, 4));
    expect(1).to.equal(b.generationTime);
    expect(1000).to.equal(b.getTimestamp().getTime());

    done();
  });

  it('should correctly create ObjectId from ObjectId', function () {
    const noArgObjID = new ObjectId();
    expect(new ObjectId(noArgObjID).id).to.deep.equal(Buffer.from(noArgObjID.id, 'hex'));
  });

  const invalidInputs = [
    { input: [], description: 'empty array' },
    { input: ['abcdefŽhijkl'], description: 'nonempty array' },
    { input: {}, description: 'empty object' }
  ];

  for (const { input, description } of invalidInputs) {
    it(`should throw error if ${description} is passed in`, function () {
      expect(() => new ObjectId(input)).to.throw(BSONTypeError);
    });
  }

  it('should throw error if object without an id property is passed in', function () {
    const noArgObjID = new ObjectId();
    const objectIdLike = {
      toHexString: function () {
        return noArgObjID.toHexString();
      }
    };
    expect(() => new ObjectId(objectIdLike)).to.throw(BSONTypeError);
  });

  it('should correctly create ObjectId from object with valid string id', function () {
    const objectValidString24Hex = {
      id: 'aaaaaaaaaaaaaaaaaaaaaaaa'
    };
    const objectValidString12Bytes = {
      id: 'abcdefghijkl'
    };
    const buf24Hex = Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaa', 'hex');
    const buf12Bytes = Buffer.from('abcdefghijkl');
    expect(new ObjectId(objectValidString24Hex).id).to.deep.equal(buf24Hex);
    expect(new ObjectId(objectValidString12Bytes).id).to.deep.equal(buf12Bytes);
  });

  it('should correctly create ObjectId from object with valid string id and toHexString method', function () {
    function new24HexToHexString() {
      return 'BBBBBBBBBBBBBBBBBBBBBBBB';
    }
    const buf24hex = Buffer.from('BBBBBBBBBBBBBBBBBBBBBBBB', 'hex');
    const objectValidString24Hex = {
      id: 'aaaaaaaaaaaaaaaaaaaaaaaa',
      toHexString: new24HexToHexString
    };
    const objectValidString12Bytes = {
      id: 'abcdefghijkl',
      toHexString: new24HexToHexString
    };
    expect(new ObjectId(objectValidString24Hex).id).to.deep.equal(buf24hex);
    expect(new ObjectId(objectValidString12Bytes).id).to.deep.equal(buf24hex);
  });

  it('should correctly create ObjectId from object with valid Buffer id', function () {
    const validBuffer24Hex = Buffer.from('AAAAAAAAAAAAAAAAAAAAAAAA', 'hex');
    const validBuffer12Array = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
    const objectBufferId = {
      id: validBuffer24Hex
    };
    const objectBufferFromArray = {
      id: validBuffer12Array
    };
    expect(new ObjectId(objectBufferId).id).to.deep.equals(validBuffer24Hex);
    expect(new ObjectId(objectBufferFromArray).id).to.deep.equals(validBuffer12Array);
  });

  it('should correctly create ObjectId from object with valid Buffer id and toHexString method', function () {
    const validBuffer24Hex = Buffer.from('AAAAAAAAAAAAAAAAAAAAAAAA', 'hex');
    const validBuffer12Array = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
    const bufferNew24Hex = Buffer.from('BBBBBBBBBBBBBBBBBBBBBBBB', 'hex');
    function newToHexString() {
      return 'BBBBBBBBBBBBBBBBBBBBBBBB';
    }
    const objectBufferHex = {
      id: validBuffer24Hex,
      toHexString: newToHexString
    };
    const objectBufferArray = {
      id: validBuffer12Array,
      toHexString: newToHexString
    };
    expect(new ObjectId(objectBufferHex).id).to.deep.equal(bufferNew24Hex);
    expect(new ObjectId(objectBufferArray).id).to.deep.equal(bufferNew24Hex);
  });

  it('should throw error if object with non-Buffer non-string id is passed in', function () {
    const objectNumId = {
      id: 5
    };
    const objectNullId = {
      id: null
    };
    expect(() => new ObjectId(objectNumId)).to.throw(BSONTypeError);
    expect(() => new ObjectId(objectNullId)).to.throw(BSONTypeError);
  });

  it('should throw an error if object with invalid string id is passed in', function () {
    const objectInvalid24HexStr = {
      id: 'FFFFFFFFFFFFFFFFFFFFFFFG'
    };
    expect(() => new ObjectId(objectInvalid24HexStr)).to.throw(BSONTypeError);
  });

  it('should correctly create ObjectId from object with invalid string id and toHexString method', function () {
    function newToHexString() {
      return 'BBBBBBBBBBBBBBBBBBBBBBBB';
    }
    const objectInvalid24HexStr = {
      id: 'FFFFFFFFFFFFFFFFFFFFFFFG',
      toHexString: newToHexString
    };
    const bufferNew24Hex = Buffer.from('BBBBBBBBBBBBBBBBBBBBBBBB', 'hex');
    expect(new ObjectId(objectInvalid24HexStr).id).to.deep.equal(bufferNew24Hex);
  });

  it('should throw an error if object with invalid Buffer id is passed in', function () {
    const objectInvalidBuffer = {
      id: Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
    };
    expect(() => new ObjectId(objectInvalidBuffer)).to.throw(BSONTypeError);
  });

  it('should correctly create ObjectId from object with invalid Buffer id and toHexString method', function () {
    function newToHexString() {
      return 'BBBBBBBBBBBBBBBBBBBBBBBB';
    }
    const objectInvalidBuffer = {
      id: Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]),
      toHexString: newToHexString
    };
    const bufferNew24Hex = Buffer.from('BBBBBBBBBBBBBBBBBBBBBBBB', 'hex');
    expect(new ObjectId(objectInvalidBuffer).id).to.deep.equal(bufferNew24Hex);
  });

  const numericIO = [
    { input: 42, output: 42, description: '42' },
    { input: 0x2a, output: 0x2a, description: '0x2a' },
    { input: 4.2, output: 4, description: '4.2' },
    { input: NaN, output: 0, description: 'NaN' }
  ];

  for (const { input, output } of numericIO) {
    it(`should correctly create ObjectId from ${input} and result in ${output}`, function () {
      const objId = new ObjectId(input);
      expect(objId).to.have.property('id');
      expect(
        isBufferOrUint8Array(objId.id),
        `expected objId.id to be instanceof buffer or uint8Array`
      ).to.be.true;
      const num = new DataView(objId.id.buffer, objId.id.byteOffset, objId.id.byteLength).getInt32(
        0,
        false
      );
      expect(num).to.equal(output);
    });
  }

  it('should correctly create ObjectId undefined or null', function () {
    const objNull = new ObjectId(null);
    const objNoArg = new ObjectId();
    const objUndef = new ObjectId(undefined);
    expect(
      isBufferOrUint8Array(objNull.id),
      `expected objNull.id to be instanceof buffer or uint8Array`
    ).to.be.true;
    expect(
      isBufferOrUint8Array(objNoArg.id),
      `expected objNoArg.id to be instanceof buffer or uint8Array`
    ).to.be.true;
    expect(
      isBufferOrUint8Array(objUndef.id),
      `expected objUndef.id to be instanceof buffer or uint8Array`
    ).to.be.true;
  });

  it('should throw error if non-12 byte non-24 hex string passed in', function () {
    expect(() => new ObjectId('FFFFFFFFFFFFFFFFFFFFFFFG')).to.throw(BSONTypeError);
    expect(() => new ObjectId('thisstringisdefinitelytoolong')).to.throw(BSONTypeError);
    expect(() => new ObjectId('tooshort')).to.throw(BSONTypeError);
    expect(() => new ObjectId('101010')).to.throw(BSONTypeError);
    expect(() => new ObjectId('')).to.throw(BSONTypeError);
  });

  it('should correctly create ObjectId from 24 hex string', function () {
    const validStr24Hex = 'FFFFFFFFFFFFFFFFFFFFFFFF';
    expect(new ObjectId(validStr24Hex).id).to.deep.equal(Buffer.from(validStr24Hex, 'hex'));
  });

  it('should correctly create ObjectId from 12 byte sequence', function () {
    const byteSequence12 = '111111111111';
    expect(new ObjectId(byteSequence12).id).to.deep.equal(Buffer.from(byteSequence12, 'latin1'));
  });

  it('should correctly create ObjectId from uppercase hexstring', function (done) {
    let a = 'AAAAAAAAAAAAAAAAAAAAAAAA';
    let b = new ObjectId(a);
    let c = b.equals(a); // => false
    expect(true).to.equal(c);

    a = 'aaaaaaaaaaaaaaaaaaaaaaaa';
    b = new ObjectId(a);
    c = b.equals(a); // => true
    expect(true).to.equal(c);
    expect(a).to.equal(b.toString());

    done();
  });

  it('should correctly create ObjectId from valid Buffer', function (done) {
    if (!Buffer.from) return done();
    let a = 'AAAAAAAAAAAAAAAAAAAAAAAA';
    let b = new ObjectId(Buffer.from(a, 'hex'));
    let c = b.equals(a); // => false
    expect(true).to.equal(c);

    a = 'aaaaaaaaaaaaaaaaaaaaaaaa';
    b = new ObjectId(Buffer.from(a, 'hex'));
    c = b.equals(a); // => true
    expect(a).to.equal(b.toString());
    expect(true).to.equal(c);
    done();
  });

  it('should throw an error if invalid Buffer passed in', function () {
    const a = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
    expect(() => new ObjectId(a)).to.throw(BSONTypeError);
  });

  it('should correctly allow for node.js inspect to work with ObjectId', function (done) {
    const a = 'AAAAAAAAAAAAAAAAAAAAAAAA';
    const b = new ObjectId(a);
    expect(util.inspect(b)).to.equal('new ObjectId("aaaaaaaaaaaaaaaaaaaaaaaa")');

    done();
  });

  it('should isValid check input Buffer length', function (done) {
    const buffTooShort = Buffer.from([]);
    const buffTooLong = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
    const buff12Bytes = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);

    expect(ObjectId.isValid(buffTooShort)).to.be.false;
    expect(ObjectId.isValid(buffTooLong)).to.be.false;
    expect(ObjectId.isValid(buff12Bytes)).to.be.true;
    done();
  });

  it('should throw if a 12-char length but non-12 byte string is passed in', function () {
    const characterCodesLargerThan256 = 'abcdefŽhijkl';
    const length12Not12Bytes = '🐶🐶🐶🐶🐶🐶';
    expect(() => new ObjectId(characterCodesLargerThan256).toHexString()).to.throw(
      BSONTypeError,
      'Argument passed in must be a string of 12 bytes'
    );
    expect(() => new ObjectId(length12Not12Bytes).id).to.throw(
      BSONTypeError,
      'Argument passed in must be a string of 12 bytes'
    );
  });

  it('should have isValid be true for 12-char length and 12-byte length string', function () {
    const plainASCIIstr = 'aaaaaaaaaaaa';
    expect(ObjectId.isValid(plainASCIIstr)).to.be.true;
  });

  it('should have isValid be false for 12-char length but non-12-byte length string', function () {
    const characterCodesLargerThan256 = 'abcdefŽhijkl';
    const length12Not12Bytest1 = '🐶🐶🐶🐶🐶🐶';
    const length12Not12Bytest2 = 'value with é';
    expect(ObjectId.isValid(characterCodesLargerThan256)).to.be.false;
    expect(ObjectId.isValid(length12Not12Bytest1)).to.be.false;
    expect(ObjectId.isValid(length12Not12Bytest2)).to.be.false;
  });

  it('should correctly interpret timestamps beyond 2038', function () {
    const farFuture = new Date('2040-01-01T00:00:00.000Z').getTime();
    expect(
      new BSON.ObjectId(BSON.ObjectId.generate(farFuture / 1000)).getTimestamp().getTime()
    ).to.equal(farFuture);
  });

  describe('.equals(otherId)', () => {
    /*
     * ObjectId.equals() covers many varieties of cases passed into it In an attempt to handle ObjectId-like objects
     * Each test covers a corresponding if stmt in the equals method.
     */
    const oidBytesInAString = 'kaffeeklatch';
    const oidString = '6b61666665656b6c61746368';
    const oid = new ObjectId(oidString);
    const oidKId = getSymbolFrom(oid, 'id');
    it('should return false for an undefined otherId', () => {
      // otherId === undefined || otherId === null
      expect(oid.equals(null)).to.be.false;
      expect(oid.equals(undefined)).to.be.false;
      expect(oid.equals()).to.be.false;
    });

    it('should return true for another ObjectId with the same bytes', () => {
      // otherId instanceof ObjectId
      const equalOid = new ObjectId(oid.id);
      expect(oid.equals(equalOid)).to.be.true;
    });

    it('should return true if otherId is a valid 24 char hex string', () => {
      // typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24
      const equalOid = oidString;
      expect(oid.equals(equalOid)).to.be.true;
    });

    it('should return true if otherId is a valid 12 byte string', () => {
      /*
      typeof otherId === 'string' &&
      ObjectId.isValid(otherId) &&
      otherId.length === 12 &&
      isUint8Array(this.id)
      */
      const equalOid = oidBytesInAString;
      expect(oid.equals(equalOid)).to.be.true;
    });

    it.skip('should return true if otherId is a valid 12 byte string and oid.id is not Uint8Array', () => {
      // typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12
      // Skipped because the check inside of this if statement is incorrect, it will never return true
      // But it is also unreachable because of the other 12 len case checked before it
      const equalOid = oidBytesInAString;
      Object.defineProperty(oid, 'id', { value: oid.toHexString() });
      expect(oid.equals(equalOid)).to.be.true;
    });

    it('should return true if otherId is an object with a toHexString function, regardless of casing', () => {
      /*
      typeof otherId === 'object' &&
      'toHexString' in otherId &&
      typeof otherId.toHexString === 'function'
      */
      expect(oid.equals({ toHexString: () => oidString.toLowerCase() })).to.be.true;
      expect(oid.equals({ toHexString: () => oidString.toUpperCase() })).to.be.true;
    });

    it('should return false if toHexString does not return a string', () => {
      // typeof otherIdString === 'string'

      // Now that we call toLowerCase() make sure we guard the call with a type check
      expect(() => oid.equals({ toHexString: () => 100 })).to.not.throw(TypeError);
      expect(oid.equals({ toHexString: () => 100 })).to.be.false;
    });

    it('should not rely on toString for otherIds that are instanceof ObjectId', () => {
      // Note: the method access the symbol prop directly instead of the getter
      const equalId = { toString: () => oidString + 'wrong', [oidKId]: oid.id };
      Object.setPrototypeOf(equalId, ObjectId.prototype);
      expect(oid.toString()).to.not.equal(equalId.toString());
      expect(oid.equals(equalId)).to.be.true;
    });

    it('should use otherId[kId] Buffer for equality when otherId is instanceof ObjectId', () => {
      let equalId = { [oidKId]: oid.id };
      Object.setPrototypeOf(equalId, ObjectId.prototype);

      const propAccessRecord = [];
      equalId = new Proxy(equalId, {
        get(target, prop, recv) {
          propAccessRecord.push(prop);
          return Reflect.get(target, prop, recv);
        }
      });

      expect(oid.equals(equalId)).to.be.true;
      // once for the 11th byte shortcut
      // once for the total equality
      expect(propAccessRecord).to.deep.equal([oidKId, oidKId]);
    });
  });

  it('should return the same instance if a buffer is passed in', function () {
    const inBuffer = Buffer.from('00'.repeat(12), 'hex');

    const outBuffer = new ObjectId(inBuffer);

    // instance equality
    expect(inBuffer).to.equal(outBuffer.id);
    // deep equality
    expect(inBuffer).to.deep.equal(outBuffer.id);
    // class method equality
    expect(Buffer.prototype.equals.call(inBuffer, outBuffer.id)).to.be.true;
  });
});


text:
const foo = function (x) {
    console.log('foo')
}

// wrong
const bar = function (x) {
  console.log('bar')
}

// correct: switch case with 1 indent(i.e. 4 spaces)
switch (foo) {
    case 'foo':
        console.log('switch foo')
        break
    case 'bar':
        console.log('switch bar')
        break
    default:
        break
}

// wrong: switch case
switch (foo) {
  case 'foo':
    console.log('switch foo')
    break
  case 'bar':
    console.log('switch bar')
    break
  default:
    break
}

// correct: multi-line property chains with 1 indent(i.e. 4 spaces)
foo()
    .bar()
    .foobar

// wrong: multi-line property chains
foo
.bar()
.foobar


text:
namespace Tangram {

class TileManager;
class DataSource;
class Tile;
class MapProjection;
struct TileData;

class TileTask {

public:

    TileTask(TileID& _tileId, std::shared_ptr<DataSource> _source);

    // No copies
    TileTask(const TileTask& _other) = delete;
    TileTask& operator=(const TileTask& _other) = delete;

    virtual ~TileTask() {}

    virtual bool hasData() const { return true; }

    void setTile(std::shared_ptr<Tile>&& _tile) {
        m_tile = std::move(_tile);
    }

    std::shared_ptr<Tile>& tile() { return m_tile; }

    bool isReady() const { return bool(m_tile); }

    DataSource& source() { return *m_source; }
    int64_t sourceGeneration() const { return m_sourceGeneration; }

    TileID tileId() const { return m_tileId; }

    void cancel() { m_canceled = true; }

    bool isCanceled() const { return m_canceled; }

    double getPriority() const {
        return m_priority.load();
    }

    void setPriority(double _priority) {
        m_priority.store(_priority);
    }

    bool isProxy() const { return m_proxyState; }

    void setProxyState(bool isProxy) { m_proxyState = isProxy; }

protected:

    const TileID m_tileId;

    // Save shared reference to Datasource while building tile
    std::shared_ptr<DataSource> m_source;

    const int64_t m_sourceGeneration;

    // Tile result, set when tile was  sucessfully created
    std::shared_ptr<Tile> m_tile;

    bool m_canceled = false;

    std::atomic<double> m_priority;
    bool m_proxyState = false;
};

class DownloadTileTask : public TileTask {
public:
    DownloadTileTask(TileID& _tileId, std::shared_ptr<DataSource> _source)
        : TileTask(_tileId, _source) {}

    virtual bool hasData() const override {
        return rawTileData && !rawTileData->empty();
    }
    // Raw tile data that will be processed by DataSource.
    std::shared_ptr<std::vector<char>> rawTileData;
};

struct TileTaskQueue {
    virtual void enqueue(std::shared_ptr<TileTask>&& task) = 0;

    // Check processed-tiles flag. Resets flag on each call..
    // TODO better name checkAndResetProcessedTilesFlag?
    virtual bool checkProcessedTiles() = 0;

};

struct TileTaskCb {
    std::function<void(std::shared_ptr<TileTask>&&)> func;
};

}


text:
layout: post
title: Пролог
tags: [London, Intro]
categories: [london]
image:
  #background:
  feature: 2015-09-09-prologue/1.png
  credit: underconsideration.com
  creditlink: http://www.underconsideration.com/brandnew/archives/new_logo_for_facebook_done_in-house_with_eric_olson.php
#link:
#modified: YYYY-MM-DD
---

Починати завжди складно, тому цей пост буде маленьким і нудним.

Влітку 2014 я проходив стажування у Facebook Inc. (Менло Парк, Каліфорнія, США). Після стажування
мені запропонували приєднатись до компанії вже в якості повноцінного працівника, і я погодився. У квітні
2015 уряд США провів чергову лотерею робочих віз H1B, за результатами якої візу я не отримав. Компанія
запропонувала мені роботу в лондонському офісі – на даний момент це єдиний офіс Facebook за межами США,
в якому ведеться розробка. Я погодився, і 4 вересня прилетів до Великої Британії.

Мені одразу захотілось писати – писати багато і про все. Але, спробувавши написати
перший суттєвий пост, я зрозумів, що це надзвичайно складно – писати про все і одразу,
водночас для всіх і ні для кого. Так народилась ідея інтерактивного блогу.


text:
include .defs.mk

TYPE := ndbapi

BIN_TARGET := perfTransporterTest
BIN_TARGET_ARCHIVES := transporter portlib general

SOURCES   = perfTransporterTest.cpp

include $(NDB_TOP)/Epilogue.mk


text:
/*
*= require stylesheets/bootstrap.css
*= require stylesheets/bootstrap.min.css
*= require stylesheets/freelancer.css
*= require stylesheets/font-awesome.css
*= require stylesheets/font-awesome.min.css
*= require stylesheets/font-awesome.css
*/


text:
package org.apache.cassandra.distributed.fuzz;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;

import harry.core.Run;
import harry.ddl.SchemaSpec;
import harry.model.OpSelectors;
import harry.operations.Relation;
import harry.operations.Query;
import harry.operations.QueryGenerator;
import harry.util.BitSet;
import org.apache.cassandra.Util;
import org.apache.cassandra.cql3.AbstractMarker;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.cql3.Operator;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.SingleColumnRelation;
import org.apache.cassandra.cql3.VariableSpecifications;
import org.apache.cassandra.cql3.WhereClause;
import org.apache.cassandra.cql3.restrictions.StatementRestrictions;
import org.apache.cassandra.cql3.statements.Bound;
import org.apache.cassandra.cql3.statements.DeleteStatement;
import org.apache.cassandra.cql3.statements.StatementType;
import org.apache.cassandra.db.ClusteringBound;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.DeletionTime;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.RangeTombstone;
import org.apache.cassandra.db.RowUpdateBuilder;
import org.apache.cassandra.db.Slices;
import org.apache.cassandra.db.marshal.ByteBufferAccessor;
import org.apache.cassandra.db.marshal.CompositeType;
import org.apache.cassandra.db.partitions.PartitionUpdate;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;

import static harry.generators.DataGenerators.UNSET_VALUE;

public class SSTableGenerator
{
    protected final SchemaSpec schema;
    protected final OpSelectors.DescriptorSelector descriptorSelector;
    protected final OpSelectors.MonotonicClock clock;
    protected final ColumnFamilyStore store;
    protected final TableMetadata metadata;
    protected final QueryGenerator rangeSelector;

    private final Set<SSTableReader> sstables = new HashSet<>();

    private long lts = 0;

    public SSTableGenerator(Run run,
                            ColumnFamilyStore store)
    {
        this.schema = run.schemaSpec;
        this.descriptorSelector = run.descriptorSelector;
        this.clock = run.clock;
        this.store = store;
        // We assume metadata can not change over the lifetime of sstable generator
        this.metadata = store.metadata.get();
        this.rangeSelector = new QueryGenerator(schema, run.pdSelector, descriptorSelector, run.rng);
        store.disableAutoCompaction();
    }

    public Collection<SSTableReader> gen(int rows)
    {
        mark();
        for (int i = 0; i < rows; i++)
        {
            long current = lts++;
            write(current, current, current, current, true).applyUnsafe();
            if (schema.staticColumns != null)
                writeStatic(current, current, current, current, true).applyUnsafe();
        }

        return flush();
    }

    public void mark()
    {
        sstables.clear();
        sstables.addAll(store.getLiveSSTables());
    }

    public Collection<SSTableReader> flush()
    {
        Util.flush(store);
        sstables.removeAll(store.getLiveSSTables());

        Set<SSTableReader> ret = new HashSet<>(sstables);
        mark();
        return ret;
    }

    public Mutation write(long lts, long pd, long cd, long opId, boolean withRowMarker)
    {
        long[] vds = descriptorSelector.vds(pd, cd, lts, opId, OpSelectors.OperationKind.INSERT, schema);

        Object[] partitionKey = schema.inflatePartitionKey(pd);
        Object[] clusteringKey = schema.inflateClusteringKey(cd);
        Object[] regularColumns = schema.inflateRegularColumns(vds);

        RowUpdateBuilder builder = new RowUpdateBuilder(metadata,
                                                        FBUtilities.nowInSeconds(),
                                                        clock.rts(lts),
                                                        metadata.params.defaultTimeToLive,
                                                        serializePartitionKey(store, partitionKey))
                                   .clustering(clusteringKey);

        if (!withRowMarker)
            builder.noRowMarker();

        for (int i = 0; i < regularColumns.length; i++)
        {
            Object value = regularColumns[i];
            if (value == UNSET_VALUE)
                continue;

            ColumnMetadata def = metadata.getColumn(new ColumnIdentifier(schema.regularColumns.get(i).name, false));
            builder.add(def, value);
        }

        return builder.build();
    }

    public Mutation writeStatic(long lts, long pd, long cd, long opId, boolean withRowMarker)
    {
        long[] sds = descriptorSelector.sds(pd, cd, lts, opId, OpSelectors.OperationKind.INSERT_WITH_STATICS, schema);

        Object[] partitionKey = schema.inflatePartitionKey(pd);
        Object[] staticColumns = schema.inflateStaticColumns(sds);

        RowUpdateBuilder builder = new RowUpdateBuilder(metadata,
                                                        FBUtilities.nowInSeconds(),
                                                        clock.rts(lts),
                                                        metadata.params.defaultTimeToLive,
                                                        serializePartitionKey(store, partitionKey));

        if (!withRowMarker)
            builder.noRowMarker();

        for (int i = 0; i < staticColumns.length; i++)
        {
            Object value = staticColumns[i];
            if (value == UNSET_VALUE)
                continue;
            ColumnMetadata def = metadata.getColumn(new ColumnIdentifier(schema.staticColumns.get(i).name, false));
            builder.add(def, staticColumns[i]);
        }

        return builder.build();
    }

    public Mutation deleteColumn(long lts, long pd, long cd, long opId)
    {
        Object[] partitionKey = schema.inflatePartitionKey(pd);
        Object[] clusteringKey = schema.inflateClusteringKey(cd);

        RowUpdateBuilder builder = new RowUpdateBuilder(metadata,
                                                        FBUtilities.nowInSeconds(),
                                                        clock.rts(lts),
                                                        metadata.params.defaultTimeToLive,
                                                        serializePartitionKey(store, partitionKey))
                                   .noRowMarker()
                                   .clustering(clusteringKey);

        BitSet columns = descriptorSelector.columnMask(pd, lts, opId, OpSelectors.OperationKind.DELETE_COLUMN);
        BitSet mask = schema.regularColumnsMask();

        if (columns == null || columns.allUnset(mask))
            throw new IllegalArgumentException("Can't have a delete column query with no columns set. Column mask: " + columns);

        columns.eachSetBit((idx) -> {
            if (idx < schema.regularColumnsOffset)
                throw new RuntimeException("Can't delete parts of partition or clustering key");

            if (idx > schema.allColumns.size())
                throw new IndexOutOfBoundsException(String.format("Index %d is out of bounds. Max index: %d", idx, schema.allColumns.size()));

            builder.delete(schema.allColumns.get(idx).name);
        }, mask);

        return builder.build();
    }

    public Mutation deleteStatic(long lts, long pd, long opId)
    {
        Object[] partitionKey = schema.inflatePartitionKey(pd);

        RowUpdateBuilder builder = new RowUpdateBuilder(metadata,
                                                        FBUtilities.nowInSeconds(),
                                                        clock.rts(lts),
                                                        metadata.params.defaultTimeToLive,
                                                        serializePartitionKey(store, partitionKey))
                                   .noRowMarker();

        BitSet columns = descriptorSelector.columnMask(pd, lts, opId, OpSelectors.OperationKind.DELETE_COLUMN_WITH_STATICS);
        BitSet mask = schema.staticColumnsMask();

        if (columns == null || columns.allUnset(mask))
            throw new IllegalArgumentException("Can't have a delete column query with no columns set. Column mask: " + columns);

        columns.eachSetBit((idx) -> {
            if (idx < schema.staticColumnsOffset)
                throw new RuntimeException(String.format("Can't delete parts of partition or clustering key %d (%s)",
                                                         idx, schema.allColumns.get(idx)));

            if (idx > schema.allColumns.size())
                throw new IndexOutOfBoundsException(String.format("Index %d is out of bounds. Max index: %d", idx, schema.allColumns.size()));

            builder.delete(schema.allColumns.get(idx).name);
        }, mask);

        return builder.build();
    }

    public Mutation deletePartition(long lts, long pd)
    {
        Object[] partitionKey = schema.inflatePartitionKey(pd);

        PartitionUpdate update = PartitionUpdate.fullPartitionDelete(metadata,
                                                                     serializePartitionKey(store, partitionKey),
                                                                     clock.rts(lts),
                                                                     FBUtilities.nowInSeconds());

        return new Mutation(update);
    }

    public Mutation deleteRow(long lts, long pd, long cd)
    {
        Object[] partitionKey = schema.inflatePartitionKey(pd);
        Object[] clusteringKey = schema.inflateClusteringKey(cd);

        return RowUpdateBuilder.deleteRow(metadata,
                                          clock.rts(lts),
                                          serializePartitionKey(store, partitionKey),
                                          clusteringKey);
    }

    public Mutation deleteSlice(long lts, long pd, long opId)
    {
        return delete(lts, pd, rangeSelector.inflate(lts, opId, Query.QueryKind.CLUSTERING_SLICE));
    }

    public Mutation deleteRange(long lts, long pd, long opId)
    {
        return delete(lts, pd, rangeSelector.inflate(lts, opId, Query.QueryKind.CLUSTERING_RANGE));
    }

    Mutation delete(long lts, long pd, Query query)
    {
        Object[] partitionKey = schema.inflatePartitionKey(pd);
        WhereClause.Builder builder = new WhereClause.Builder();
        List<ColumnIdentifier> variableNames = new ArrayList<>();

        List<ByteBuffer> values = new ArrayList<>();
        for (int i = 0; i < partitionKey.length; i++)
        {
            String name = schema.partitionKeys.get(i).name;
            ColumnMetadata columnDef = metadata.getColumn(ByteBufferUtil.bytes(name));
            variableNames.add(columnDef.name);
            values.add(ByteBufferUtil.objectToBytes(partitionKey[i]));
            builder.add(new SingleColumnRelation(ColumnIdentifier.getInterned(name, true),
                                                 toOperator(Relation.RelationKind.EQ),
                                                 new AbstractMarker.Raw(values.size() - 1)));
        }

        for (Relation relation : query.relations)
        {
            String name = relation.column();
            ColumnMetadata columnDef = metadata.getColumn(ByteBufferUtil.bytes(relation.column()));
            variableNames.add(columnDef.name);
            values.add(ByteBufferUtil.objectToBytes(relation.value()));
            builder.add(new SingleColumnRelation(ColumnIdentifier.getInterned(name, false),
                                                 toOperator(relation.kind),
                                                 new AbstractMarker.Raw(values.size() - 1)));
        }

        StatementRestrictions restrictions = new StatementRestrictions(StatementType.DELETE,
                                                                       metadata,
                                                                       builder.build(),
                                                                       new VariableSpecifications(variableNames),
                                                                       false,
                                                                       false,
                                                                       false,
                                                                       false);

        QueryOptions options = QueryOptions.forInternalCalls(ConsistencyLevel.QUORUM, values);
        SortedSet<ClusteringBound<?>> startBounds = restrictions.getClusteringColumnsBounds(Bound.START, options);
        SortedSet<ClusteringBound<?>> endBounds = restrictions.getClusteringColumnsBounds(Bound.END, options);

        Slices slices = DeleteStatement.toSlices(metadata, startBounds, endBounds);
        assert slices.size() == 1;
        int deletionTime = FBUtilities.nowInSeconds();
        long rts = clock.rts(lts);

        return new RowUpdateBuilder(metadata,
                                    deletionTime,
                                    rts,
                                    metadata.params.defaultTimeToLive,
                                    serializePartitionKey(store, partitionKey))
               .noRowMarker()
               .addRangeTombstone(new RangeTombstone(slices.get(0), new DeletionTime(rts, deletionTime)))
               .build();
    }

    public static Operator toOperator(Relation.RelationKind kind)
    {
        switch (kind)
        {
            case LT: return Operator.LT;
            case GT: return Operator.GT;
            case LTE: return Operator.LTE;
            case GTE: return Operator.GTE;
            case EQ: return Operator.EQ;
            default: throw new IllegalArgumentException("Unsupported " + kind);
        }
    }

    public static DecoratedKey serializePartitionKey(ColumnFamilyStore store, Object... pk)
    {
        if (pk.length == 1)
            return store.getPartitioner().decorateKey(ByteBufferUtil.objectToBytes(pk[0]));

        ByteBuffer[] values = new ByteBuffer[pk.length];
        for (int i = 0; i < pk.length; i++)
            values[i] = ByteBufferUtil.objectToBytes(pk[i]);
        return store.getPartitioner().decorateKey(CompositeType.build(ByteBufferAccessor.instance, values));
    }
}


text:
namespace staff
{
#ifneq($(Interface.Enums.$Count),0)
///////////////////////////////////////////////////////////////////////////////////////////////////////
// enums
#foreach $(Interface.Enums)
#ifeq($(Enum.Extern),false) // do not serialize extern type
#cginclude "EnumSerialization.cpp"
#ifeqend
#end

#ifeqend // enums
#ifneq($(Interface.Structs.$Count),0)
///////////////////////////////////////////////////////////////////////////////////////////////////////
// struct serializators/deserializators
#foreach $(Interface.Structs)
#cginclude "StructSerialization.cpp"
#end

#ifeqend
#ifneq($(Interface.Typedefs.$Count),0)
///////////////////////////////////////////////////////////////////////////////////////////////////////
// typedef serializators
#foreach $(Interface.Typedefs)
#ifeq($(Typedef.Extern),false) // do not serialize extern type

DataObject& SerializeTypedef_$(Typedef.NsName.!mangle)(DataObject& rdoParam, const $(Typedef.NsName)& rtType)
{
#cgpushvars
#var bUseParentElement $(Typedef.Options.*useParentElement)
#var bDontWriteNs true
#context $(Typedef.DataType)
#var sParamName
#var sParam rtType
#var sdoParam rdoParam
#cginclude "TypeSerialization.cpp"
#contextend
#cgpopvars
  return rdoParam;
}

#ifeqend //ifeq($(Typedef.Extern),false) // do not serialize extern type
#end // foreach $(Interface.Structs)
#ifeqend

///////////////////////////////////////////////////////////////////////////////////////////////////////
// typedef deserializators
#foreach $(Interface.Typedefs)
#ifeq($(Typedef.Extern),false)
const DataObject& DeserializeTypedef_$(Typedef.NsName.!mangle)\
(const DataObject& rdoParam, $(Typedef.NsName)& rtType)
{
#cgpushvars
#var bUseParentElement $(Typedef.Options.*useParentElement)
#context $(Typedef.DataType)
#var bRValue 1
#var sParamName
#var sParam rtType
#var sdoParam rdoParam
#cginclude "TypeDeserialization.cpp"
#contextend
#cgpopvars
  return rdoParam;
}

#ifeqend // ifeq($(Typedef.Extern),false) // do not serialize extern type
#end
}


text:
package com.furnaghan.home.component.metrics.dropwizard;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.furnaghan.home.component.Configuration;
import org.hibernate.validator.constraints.NotEmpty;

public class DropwizardMetricsConfiguration implements Configuration {

    @NotEmpty
    @JsonProperty
    private String namespace = "home";

    public String getNamespace() {
        return namespace;
    }
}


text:
<?php $this->load->view('employer/v_employer_sidenav')?>

 EDIT COMPANY PROFILE

                        General

                        Contact Person

                        Company Photos

 COMPANY INFORMATION

                                    <form id="company_settings_form">

                                                Company Name
                                                <input type="text" name="company_name" class="form-control" value="<?=$employer->company_name?>" placeholder="Company Name" tabindex="1"  autofocus>

                                                Company Industry
                                                <select class="form-control" tabindex="2" name="company_industry" >
                                                    <option> </option>
                                                    <?php foreach($industries as $industry):
                                                    $selected = ($industry['id'] == $employer->industry_id)? "selected":"";
                                                    ?>
                                                    <option value="<?=$industry['id']?>"  <?php echo $selected?>> <?=$industry['industry_name'];?></option>
                                                    <?php endforeach;?>
                                                </select>

                                                Company Address
                                                <input type="text" name="street_address" class="form-control" value="<?=$employer->street_1?>" placeholder="Street Address" tabindex="3" >

                                                 (click to set location)

                                                <input type="text" class="form-control" name="permanent-address" value="<?php echo $employer->city.",".$employer->province ; ?>" tabindex="4" onkeydown="return false;" placeholder="City Address" >
                                                <input type="hidden" name="region_id" value="<?=$employer->province_1?>">
                                                <input type="hidden" name="city_id" value="<?=$employer->city_1?>">

                                            Company Website
                                            <input type="url" name="company_website" class="form-control" value="<?=$employer->company_website?>" placeholder="http://yourdomain.com">

                                            Company Description
                                            <textarea name="company_description" class="form-control" placeholder="Describe something about your company" rows="5" tabindex="5" ><?php echo ($employer->company_description);?></textarea>

                                            <button id="btn-save-info" type="submit" class="btn btn-success btn-materialize">Save Changes</button>

                                </form>

 CONTACT PERSON DETAILS

                                    <form action="" method="" id="contact_settings_form">

                                                First Name
                                                <input type="text" name="first_name" value="<?=$employer->first_name?>" class="form-control" placeholder="" tabindex="1" >

                                                Middle Name
                                                <input type="text" name="middlename" value="<?=$employer->middle_name?>" class="form-control" placeholder="" tabindex="2" >

                                                Last Name
                                                <input type="text" name="lastname" class="form-control" placeholder="" value="<?=$employer->last_name?>" tabindex="3" >

                                                Position
                                                <input type="text" name="position" value="<?=$employer->position?>" class="form-control" placeholder="Position" tabindex="4">

                                                Department
                                                <input type="text" name="department" class="form-control" value="<?=$employer->department?>" placeholder="Department" tabindex="5">

                                                Landline (optional)

                                                        <input type="text" name="area-code" placeholder="Area-code" value="<?=$employer->area_code?>" class="form-control">

                                                        <input type="text" id="landline" name="landline" placeholder="411-11-11" value="<?=$employer->telephone_number?>" class="form-control" data-inputmask='"mask": "999-99-99"' data-mask tabindex="12">

                                                <button id="btn-save-cinfo" type="submit" class="btn btn-success btn-materialize">Save Changes</button>

                                    </form>

 UPLOAD BANNER

                                    (Image dimension at least 800 x 200)

                                        <button class="btn btn-success btn-materialize btn-materialize-sm" id="upload-banner" disabled>Save</button>
                                        <button class="btn btn-danger btn-materialize btn-materialize-sm" id="remove-banner" disabled>Remove</button>

                                            <?php echo form_open_multipart('', array("class" => "dropzone", "id" => "companyBanner"))?>

                                            <input type="hidden" name="" value=>

Current Banner

                                               <?php if($employer->company_banner != ""):?>
                                                <img class="card-img-top" id="current-banner" data-val="<?=$employer->company_banner?>" src="<?=$company_banner?>" alt="Card image cap" style="width: 100%; height: auto;">
                                               <?php endif?>

<?php $this->load->view('template/modal')?>


text:
require 'hashie'

require 'raven/interfaces'

module Raven

  class StacktraceInterface < Interface

    name 'sentry.interfaces.Stacktrace'
    property :frames, :default => []

    def initialize(*arguments)
      self.frames = []
      super(*arguments)
    end

    def to_hash
      data = super
      data['frames'] = data['frames'].map{|frame| frame.to_hash}
      data
    end

    def frame(attributes=nil, &block)
      Frame.new(attributes, &block)
    end

    # Not actually an interface, but I want to use the same style
    class Frame < Interface
      property :abs_path
      property :filename, :required => true
      property :function
      property :vars
      property :pre_context
      property :post_context
      property :context_line
      property :lineno, :required => true

      def initialize(*arguments)
        self.vars= {}
        self.pre_context = []
        self.post_context = []
        super(*arguments)
      end

      def to_hash
        data = super
        data.delete('vars') unless self.vars && !self.vars.empty?
        data.delete('pre_context') unless self.pre_context && !self.pre_context.empty?
        data.delete('post_context') unless self.post_context && !self.post_context.empty?
        data.delete('context_line') unless self.context_line && !self.context_line.empty?
        data
      end
    end

  end

  register_interface :stack_trace => StacktraceInterface

end


text:
<fieldset ng-disabled="form.readonly" class="schema-form-fieldset {{form.htmlClass}}" schema-validate="form" ng-model="$$value$$"
     ng-class="{'has-error': hasError(), 'has-success': hasSuccess()}">
  <legend ng-show="form.title">{{ form.title }}</legend>

  <sf-decorator ng-repeat="item in form.items" form="item"></sf-decorator>
</fieldset>


text:
var path = require('path');

global.assert = require('assert');

global.paths = {};
global.paths.base = process.env.PWD;

paths.src = function(p) {
  return path.join(paths.base, 'src', p);
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sber. Akad. Wiss. Wien, Math. -naturw. Kl. , Abt. 1 106: 231 (1897)

#### Original name
Arthonia ilicinodes J. Steiner

### Remarks
null


text:
using C3DE.VR;
using Microsoft.Xna.Framework;

namespace C3DE.Components.VR
{
    public class MotionController : Behaviour
    {
        private VRService _service;
        private Vector3 _position;
        private Quaternion _rotation;

        public bool LeftHand { get; set; }

        public override void Start()
        {
            _service = VRManager.ActiveService;
            VRManager.VRServiceChanged += OnVRServiceChanged;
        }

        private void OnVRServiceChanged(VRService service)
        {
            _service = service;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            VRManager.VRServiceChanged -= OnVRServiceChanged;
        }

        public override void Update()
        {
            if (_service == null)
                return;

            _service.GetLocalPosition(LeftHand ? 0 : 1, ref _position);
            _service.GetLocalRotation(LeftHand ? 0 : 1, ref _rotation);

            _transform.LocalPosition = _position;
            _transform.LocalRotation = _rotation.ToEuler();
        }
    }
}


text:
package org.esupportail.publisher.service.factories.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.esupportail.publisher.domain.SubjectKey;
import org.esupportail.publisher.domain.enums.SubjectType;
import org.esupportail.publisher.service.factories.CompositeKeyDTOFactory;
import org.esupportail.publisher.web.rest.dto.SubjectKeyDTO;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;

@Service
public class SubjectKeyDTOFactoryImpl implements
    CompositeKeyDTOFactory<SubjectKeyDTO, SubjectKey, String, SubjectType> {

    public SubjectKey convertToModelKey(@NotNull final SubjectKeyDTO id) {
        return new SubjectKey(id.getKeyId(), id.getKeyType());
    }

    public SubjectKeyDTO convertToDTOKey(@NotNull final SubjectKey id) {
        return new SubjectKeyDTO(id.getKeyId(), id.getKeyType());
    }

    public Set<SubjectKey> convertToModelKey(@NotNull final Set<SubjectKeyDTO> dtos) {
        final Set<SubjectKey> models = Sets.newHashSet();
        for (SubjectKeyDTO dto : dtos) {
            models.add(this.convertToModelKey(dto));
        }
        return models;
    }

    public List<SubjectKey> convertToModelKey(@NotNull final List<SubjectKeyDTO> dtos) {
        final List<SubjectKey> models = Lists.newArrayList();
        for (SubjectKeyDTO dto : dtos) {
            models.add(this.convertToModelKey(dto));
        }
        return models;
    }

    public Set<SubjectKeyDTO> convertToDTOKey(@NotNull final Set<SubjectKey> models) {
        final Set<SubjectKeyDTO> dtos = Sets.newHashSet();
        for (SubjectKey model : models) {
            dtos.add(this.convertToDTOKey(model));
        }
        return dtos;
    }

    public List<SubjectKeyDTO> convertToDTOKey(@NotNull final List<SubjectKey> models) {
        final List<SubjectKeyDTO> dtos = Lists.newArrayList();
        for (SubjectKey model : models) {
            dtos.add(this.convertToDTOKey(model));
        }
        return dtos;
    }

}


text:
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.text.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

import org.apache.lucene.util.AttributeSource;

import com.twitter.common.text.token.TwitterTokenStream;

/**
 * Helper class to serialize a TwitterTokenStream into a byte array.
 *
 * A list of AttributeSerializers must be defined using the Builder, which serialize
 * and deserialize individual attributes.
 *
 * The same TokenStreamSerializer should be used for serialization/de-serialization, as the order
 * of the {@link AttributeSerializer}s must be consistent.
 */
public class TokenStreamSerializer {
  public static enum Version {
    VERSION_1,
    VERSION_2
  }

  protected static final Version CURRENT_VERSION = Version.VERSION_2;

  private final List<AttributeSerializer> attributeSerializers;

  private final int attributeSerializersFingerprint;

  public TokenStreamSerializer(List<AttributeSerializer> attributeSerializers) {
    this.attributeSerializers = attributeSerializers;
    this.attributeSerializersFingerprint = computeFingerprint(attributeSerializers);
  }

  public static int computeFingerprint(List<AttributeSerializer> attributeSerializers) {
    int result = 0;
    int i = 0;
    for (AttributeSerializer attributeSerializer : attributeSerializers) {
      int hashCode = attributeSerializer.getClass().getName().hashCode();
      result = result ^ ((hashCode << i) | (hashCode >> i));
      i++;
    }
    return result;
  }

  /**
   * The fingerprint of the attribute serializers that are attached to this TokenStreamSerializer.
   */
  public int attributeSerializersFingerprint() {
    return attributeSerializersFingerprint;
  }

  /**
   * Serialize the given TwitterTokenStream into a byte array using the provided AttributeSerializer(s).
   * Note that this method doesn't serialize the CharSequence of the TwitterTokenStream - the caller
   * has to take care of serializing this if necessary.
   */
  public final byte[] serialize(final TwitterTokenStream twitterTokenStream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    AttributeOutputStream output = new AttributeOutputStream(baos);

    for (AttributeSerializer serializer : attributeSerializers) {
      serializer.initialize(twitterTokenStream, CURRENT_VERSION);
    }

    int numTokens = 0;

    while (twitterTokenStream.incrementToken()) {
      serializeAttributes(output);
      numTokens++;
    }

    output.flush();

    byte[] data = baos.toByteArray();
    baos.close();
    baos = new ByteArrayOutputStream(8 + data.length);
    output = new AttributeOutputStream(baos);
    output.writeVInt(CURRENT_VERSION.ordinal());
    output.writeInt(attributeSerializersFingerprint);
    output.writeVInt(numTokens);
    output.write(data);
    output.flush();

    return baos.toByteArray();
  };

  /**
   * Same as above but serializers a lucene TwitterTokenStream.
   */
  public final byte[] serialize(final org.apache.lucene.analysis.TokenStream tokenStream)
      throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    AttributeOutputStream output = new AttributeOutputStream(baos);

    for (AttributeSerializer serializer : attributeSerializers) {
      serializer.initialize(tokenStream, CURRENT_VERSION);
    }

    int numTokens = 0;

    while (tokenStream.incrementToken()) {
      serializeAttributes(output);
      numTokens++;
    }

    output.flush();

    byte[] data = baos.toByteArray();
    baos.close();
    baos = new ByteArrayOutputStream(8 + data.length);
    output = new AttributeOutputStream(baos);
    output.writeVInt(CURRENT_VERSION.ordinal());
    output.writeInt(attributeSerializersFingerprint);
    output.writeVInt(numTokens);
    output.write(data);
    output.flush();

    return baos.toByteArray();
  };

  /**
   * Deserializes the previously serialized TwitterTokenStream using the provided AttributeSerializer(s).
   *
   * This method only deserializes all Attributes; the CharSequence instance containing the text
   * must be provided separately.
   * @param data  the byte-serialized representation of the tokenstream.
   * @param charSequence  the text that was tokenized.
   * @return  a TwitterTokenStream object. Notice that, in order to support lucene-like TwitterTokenStream
   *          behavior, this object's reset method must only be used as reset(null) and will reset
   *          the TwitterTokenStream to its starting point.
   */
  public final TwitterTokenStream deserialize(final byte[] data,
                                       final CharSequence charSequence) throws IOException {
    return deserialize(data, 0, data.length, charSequence);
  }

  /**
   * Other form of deserialize that reads data from a "slice" in a byte array.
   */
  public final TwitterTokenStream deserialize(final byte[] data, int offset, int length,
                                       final CharSequence charSequence) throws IOException {
    Preconditions.checkNotNull(data);
    Preconditions.checkState(length > 0);
    Preconditions.checkState(data.length >= length);

    ByteArrayInputStream bais = new ByteArrayInputStream(data, offset, length);
    return deserialize(bais, charSequence);
  }

  /**
   * An unckecked Exception that we throw for version mismatch between the
   * serializer and the deserializer.
   */
  public static class VersionMismatchException extends RuntimeException {
    public VersionMismatchException(String msg) {
      super(msg);
    }
  }

  public static Version readVersionAndCheckFingerprint(
      AttributeInputStream input, int attributeSerializersFingerprint) throws IOException {
    int ordinal = input.readVInt();
    if (ordinal > CURRENT_VERSION.ordinal()) {
      throw new VersionMismatchException(
          "Version of serialized data is newer than the version this serializer" +
          "supports: " + ordinal + " > " + CURRENT_VERSION.ordinal());
    }
    if (ordinal >= Version.VERSION_2.ordinal()) {
      int fp = input.readInt();
      if (fp != attributeSerializersFingerprint) {
        throw new VersionMismatchException(
            "Attributes of serialized data are different than attributes of " +
            "this serializer: " + fp + " != " + attributeSerializersFingerprint);
      }
    }
    return Version.values()[ordinal];
  }

  /**
   * Other form of deserialize for a ByteArrayInputStream.
   */
  public final TwitterTokenStream deserialize(final ByteArrayInputStream bais, final CharSequence charSequence)
      throws IOException {
    final AttributeInputStream input = new AttributeInputStream(bais);

    TwitterTokenStream twitterTokenStream = new TwitterTokenStream() {
      CharSequence chars = charSequence;
      // All other members are initialized in reset.
      int token;
      Version version;
      int numTokens;

      @Override
      public final boolean incrementToken() {
        if (token < numTokens) {
          token++;
          try {
            deserializeAttributes(input, chars);
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
          return true;
        }

        return false;
      }

      @Override
      public void reset() {
        CharSequence newChars = inputCharSequence();
        Preconditions.checkArgument(newChars == null || newChars == chars,
            "this TwitterTokenStream does not do actual tokenization and only supports reset(null)");
        try {
          input.reset();
          bais.reset();
          version = readVersionAndCheckFingerprint(input, attributeSerializersFingerprint);
          numTokens = input.readVInt();
          for (AttributeSerializer deserializer : attributeSerializers) {
            deserializer.initialize(this, version);
          }
        } catch (IOException e) {
          throw new IllegalStateException("Unexpected exception, but...", e);
        }
        token = 0;
      }
    };

    twitterTokenStream.reset(null);
    return twitterTokenStream;
  };

  private void deserializeAttributes(AttributeInputStream input,
                                     CharSequence charSequence) throws IOException {
    for (AttributeSerializer serializer : attributeSerializers) {
      serializer.deserialize(input, charSequence);
    }
  }

  private void serializeAttributes(AttributeOutputStream output) throws IOException {
    for (AttributeSerializer serializer : attributeSerializers) {
      serializer.serialize(output);
    }
  }

  /**
   * Returns a new Builder to build a TokenStreamSerializer.
   */
  public static Builder builder() {
    return new Builder();
  }

  /**
   * Defines how individual attributes a (de)serialized.
   */
  public interface AttributeSerializer {
    /**
     * Initialises this AttributeSerializer. This method should be used to get the attribute
     * instance from the TwitterTokenStream that this serializer handles. E.g.:
     *
     * CharSequenceTermAttribute termAtt =
     *                    attributeSource.addAttribute(CharSequenceTermAttribute.class);
     *
     */
    public abstract void initialize(AttributeSource attributeSource, Version version)
        throws IOException;

    /**
     * Serializes a single attribute.
     */
    public abstract void serialize(AttributeOutputStream output) throws IOException ;

    /**
     * Deserializes a single attribute.
     */
    public abstract void deserialize(AttributeInputStream input, CharSequence charSequence)
        throws IOException;

    /**
     * Create a new instance of this AttributeSerializer.
     */
    public abstract AttributeSerializer newInstance();
  }

  /**
   * Builds an TokenStreamSerializer.
   */
  public final static class Builder {
    private final List<AttributeSerializer> attributeSerializers = Lists.newLinkedList();

    /**
     * Adds an AttributeSerializer. The order in which the AttributeSerializers are added here
     * is the same order in which they will be called for serializing a Token.
     */
    public Builder add(AttributeSerializer serializer) {
      attributeSerializers.add(serializer);
      return this;
    }

    /**
     * Builds the TokenStreamSerializer.
     */
    public TokenStreamSerializer build() {
      return new TokenStreamSerializer(attributeSerializers);
    }

    /**
     * Build a TokenStreamSerializer. This can be repeatedly called to create TokenStreamSerializers
     * that do not share AttributeSerializers
     */
    public TokenStreamSerializer safeBuild() {
      List<AttributeSerializer> attributeSerializersCopy =
          Lists.newArrayListWithCapacity(attributeSerializers.size());
      for(AttributeSerializer serializer : attributeSerializers) {
        attributeSerializersCopy.add(serializer.newInstance());
      }
      return new TokenStreamSerializer(attributeSerializersCopy);
    }
  }

  /**
   * A DataOutputStream that supports VInt-encoding.
   */
  public static class AttributeOutputStream extends DataOutputStream {
    public AttributeOutputStream(OutputStream output) {
      super(output);
    }

    /**
     * Writes an integer value using VInt encoding.
     */
    public final void writeVInt(int value) throws IOException {
      while ((value & ~0x7F) != 0) {
        writeByte((byte)((value & 0x7f) | 0x80));
        value >>>= 7;
      }
      writeByte((byte)value);
    }

    /**
     * Writes a long value using VInt encoding.
     */
    public final void writeVLong(long value) throws IOException {
      while ((value & ~0x7FL) != 0) {
        writeByte((byte)((value & 0x7f) | 0x80));
        value >>>= 7;
      }
      writeByte((byte)value);
    }
  }

  /**
   * A DataInputStream that supports VInt-encoding.
   */
  public static class AttributeInputStream extends DataInputStream {
    public AttributeInputStream(InputStream input) {
      super(input);
    }

    /**
     * Reads a int value using VInt encoding.
     */
    public final int readVInt() throws IOException {
      byte b = readByte();
      int value = b & 0x7F;
      for (int shift = 7; (b & 0x80) != 0; shift += 7) {
        b = readByte();
        value |= (b & 0x7F) << shift;
      }
      return value;
    }

    /**
     * Reads a long value using VInt encoding.
     */
    public final long readVLong() throws IOException {
      byte b = readByte();
      long value = b & 0x7FL;
      for (int shift = 7; (b & 0x80) != 0; shift += 7) {
        b = readByte();
        // Must use 0x7FL here instead of 0x7F.
        value |= (b & 0x7FL) << shift;
      }
      return value;
    }
  }
}