text:
""" altsets.py -- An alternate implementation of Sets.py

Implements set operations using sorted lists as the underlying data structure.

Advantages:

  * Space savings -- lists are much more compact than a dictionary
    based implementation.

  * Flexibility -- elements do not need to be hashable, only __cmp__
    is required.

  * Fast operations depending on the underlying data patterns.
    Non-overlapping sets get united, intersected, or differenced
    with only log(N) element comparisons.  Results are built using
    fast-slicing.

  * Algorithms are designed to minimize the number of compares
    which can be expensive.

  * Natural support for sets of sets.  No special accomodation needs to
    be made to use a set or dict as a set member, but users need to be
    careful to not mutate a member of a set since that may breaks its
    sort invariant.

Disadvantages:

  * Set construction uses list.sort() with potentially N log(N)
    comparisons.

  * Membership testing and element addition use log(N) comparisons.
    Element addition uses list.insert() with takes O(N) time.

ToDo:

   * Make the search routine adapt to the data; falling backing to
     a linear search when encountering random data.

"""

from bisect import bisect_left, insort_left

class Set:

    def __init__(self, iterable):
        data = list(iterable)
        data.sort()
        result = data[:1]
        for elem in data[1:]:
            if elem == result[-1]:
                continue
            result.append(elem)
        self.data = result

    def __repr__(self):
        return 'Set(' + repr(self.data) + ')'

    def __iter__(self):
        return iter(self.data)

    def __contains__(self, elem):
        data = self.data
        i = bisect_left(self.data, elem, 0)
        return i<len(data) and data[i] == elem

    def add(self, elem):
        insort_left(self.data, elem)

    def remove(self, elem):
        data = self.data
        i = bisect_left(self.data, elem, 0)
        if i<len(data) and data[i] == elem:
            del data[i]

    def _getotherdata(other):
        if not isinstance(other, Set):
            other = Set(other)
        return other.data
    #_getotherdata = staticmethod(_getotherdata)

    def __cmp__(self, other, cmp=cmp):
        return cmp(self.data, Set._getotherdata(other))

    def union(self, other, find=bisect_left):
        i = j = 0
        x = self.data
        y = Set._getotherdata(other)
        result = Set([])
        append = result.data.append
        extend = result.data.extend
        try:
            while 1:
                if x[i] == y[j]:
                    append(x[i])
                    i += 1
                    j += 1
                elif x[i] > y[j]:
                    cut = find(y, x[i], j)
                    extend(y[j:cut])
                    j = cut
                else:
                    cut = find(x, y[j], i)
                    extend(x[i:cut])
                    i = cut
        except IndexError:
            extend(x[i:])
            extend(y[j:])
        return result

    def intersection(self, other, find=bisect_left):
        i = j = 0
        x = self.data
        y = Set._getotherdata(other)
        result = Set([])
        append = result.data.append
        try:
            while 1:
                if x[i] == y[j]:
                    append(x[i])
                    i += 1
                    j += 1
                elif x[i] > y[j]:
                    j = find(y, x[i], j)
                else:
                    i = find(x, y[j], i)
        except IndexError:
            pass
        return result

    def difference(self, other, find=bisect_left):
        i = j = 0
        x = self.data
        y = Set._getotherdata(other)
        result = Set([])
        extend = result.data.extend
        try:
            while 1:
                if x[i] == y[j]:
                    i += 1
                    j += 1
                elif x[i] > y[j]:
                    j = find(y, x[i], j)
                else:
                    cut = find(x, y[j], i)
                    extend(x[i:cut])
                    i = cut
        except IndexError:
            extend(x[i:])
        return result

    def symmetric_difference(self, other, find=bisect_left):
        i = j = 0
        x = self.data
        y = Set._getotherdata(other)
        result = Set([])
        extend = result.data.extend
        try:
            while 1:
                if x[i] == y[j]:
                    i += 1
                    j += 1
                elif x[i] > y[j]:
                    cut = find(y, x[i], j)
                    extend(y[j:cut])
                    j = cut
                else:
                    cut = find(x, y[j], i)
                    extend(x[i:cut])
                    i = cut
        except IndexError:
            extend(x[i:])
            extend(y[j:])
        return result


text:
<?php namespace PhilippBaschke\ACFProInstaller\Test;

use PhilippBaschke\ACFProInstaller\RemoteFilesystem;

class RemoteFilesystemTest extends \PHPUnit_Framework_TestCase
{
    protected $io;
    protected $config;

    protected function setUp()
    {
        $this->io = $this->getMock('Composer\IO\IOInterface');
    }

    public function testExtendsComposerRemoteFilesystem()
    {
        $this->assertInstanceOf(
            'Composer\Util\RemoteFilesystem',
            new RemoteFilesystem('', $this->io)
        );
    }

    // Inspired by testCopy of Composer
    public function testCopyUsesAcfFileUrl()
    {
        $acfFileUrl = 'file://'.__FILE__;
        $rfs = new RemoteFilesystem($acfFileUrl, $this->io);
        $file = tempnam(sys_get_temp_dir(), 'pb');

        $this->assertTrue(
            $rfs->copy('http://example.org', 'does-not-exist', $file)
        );
        $this->assertFileExists($file);
        unlink($file);
    }
}

redpajama_set_name: RedPajamaGithub


text:
section: libraries
toc: true
description: Validating JWTs with Auth0-PHP
topics:
  - libraries
  - php
contentType: how-to
---

# Validating JWTs with Auth0-PHP

Auth0-PHP includes an interface to the [lcobucci/jwt library](https://github.com/lcobucci/jwt), used to validate and decode <dfn data-key="json-web-token">JSON Web Tokens (JWT)</dfn>. More information on JWTs and how to build and decode them can be found [jwt.io](https://jwt.io/).

The decoder can work with both HS256 and RS256 tokens. Both types require the algorithm and valid <dfn data-key="audience">audiences</dfn> to be indicated before processing. Additionally, HS256 tokens require the client secret while RS256 tokens require an authorized issuer. The issuer is used to fetch a JWKs file during the decoding process as well. ([More about signing algorithms here](https://auth0.com/blog/navigating-rs256-and-jwks/).)

Here is an example of a small, URL-based JWT decoder:

```php
// decode-jwt.php
use Auth0\SDK\Helpers\JWKFetcher;
use Auth0\SDK\Helpers\Tokens\AsymmetricVerifier;
use Auth0\SDK\Helpers\Tokens\SymmetricVerifier;
use Auth0\SDK\Helpers\Tokens\IdTokenVerifier;

if (empty($_GET['id_token'])) {
    die( 'No `id_token` URL parameter' );
}

if (empty($_GET['token_alg']) || ! in_array($_GET['token_alg'], [ 'HS256', 'RS256' ])) {
    die( 'Missing or invalid `token_alg` URL parameter' );
}

$id_token  = rawurldecode($_GET['id_token']);

$token_issuer  = 'https://'.getenv('AUTH0_DOMAIN').'/';
$signature_verifier = null;

if ('RS256' === $_GET['token_alg']) {
    $jwks_fetcher = new JWKFetcher();
    $jwks        = $jwks_fetcher->getKeys($token_issuer.'.well-known/jwks.json');
    $signature_verifier = new AsymmetricVerifier($jwks);
} else if ('HS256' === $_GET['token_alg']) {
    $signature_verifier = new SymmetricVerifier(getenv('AUTH0_CLIENT_SECRET'));
}

$token_verifier = new IdTokenVerifier(
    $token_issuer,
    getenv('AUTH0_CLIENT_ID'),
    $signature_verifier
);

try {
    $decoded_token = $token_verifier->verify($id_token);
    echo '<pre>'.print_r($decoded_token, true).'</pre>';
} catch (\Exception $e) {
    echo 'Caught: Exception - '.$e->getMessage();
}
```

The second parameter of `IdTokenVerifier->verify()` is an optional array of options:

* `nonce` to check the nonce contained in the token (recommended for OIDC-compliant tokens).
* `max_age` to check the auth_time of the token.
* `leeway` clock tolerance in seconds for the current check only (60 seconds default).

## Read More

::: next-steps
* [Auth0-PHP Introduction](/libraries/auth0-php)
* [Auth0-PHP Basic Use](/libraries/auth0-php/basic-use)
* [Auth0-PHP Authentication API](/libraries/auth0-php/authentication-api)
* [Auth0-PHP Management API](/libraries/auth0-php/management-api)
* [Auth0-PHP Troubleshooting](/libraries/auth0-php/troubleshooting)
:::


text:
layout: post
title: "Car Stereo Receiver Replacement"
---

A few months back I replaced the stereo receivers in a 10 and a 20 year old family car.
Fed up with the lack of auxillary input (or even CD player, on the older one), I started on what would end up being a rather straightforward project.

## Shopping
I ordered all my stuff from Amazon, because Prime shipping is awesome.
Shopping ended up being the hardest part for me, because I wasn't sure about compatibility or even what harware was required.
Hence this.

### Receiver
Receiver units follow an ISO standard for sizes, which means your car takes one of two sizes: single or double DIN.
A single DIN is about two inches tall.

If you've got a double slotted opening, either get a double height receiver, or a cheap mounting unit for a single slot sized device.
I went with [this receiver](http://www.amazon.com/Kenwood-KDC-152--Dash-MP3-Receiver/dp/B006KKS7XQ/ref=lp_10980601_1_4?s=car&ie=UTF8&qid=1404681359&sr=1-4), as the cheapest thing I could find with an auxillary input.

### Wiring Harness
Though the receiver sizes may be standardized, the wiring isn't.
The receiver has a bunch of wires leading out, but the dashboard expects a rectangular plug.
You'll want to pick up a Metra Wiring Harness for your make and model.
Amazon is pretty nice for this sort of thing, letting you filter by compatibility with your vehicle.

### More?
The older car needed a special adapter for its non-standard radio.
Never got that working (I don't really miss it), but that means you should look around and see if you can find any model-specific quirks.

## Installing

### Soldering
To wire up the receiver and wiring harness, you gotta solder.
Everything's color coded, so it's pretty self explanatory.
Unless you don't know how to solder, in which case pick up a cheap kit like [this one](http://www.amazon.com/Elenco-Electronics-ST-12-Soldering-Tool/dp/B0002LLWZY/ref=sr_1_1?ie=UTF8&qid=1404782379&sr=8-1) and get learnin'.

Strip the coating from the wires, intertwine the exposed ends, get a nice dollop on there and let it cool.
Insulate with electrical tape or the likes.

![Soldering done](/public/receiver.jpg)

### Time for some open-heart surgery
This part can vary widely from car to car, so you'll need to look for guides on receiver installation for yours, perhaps with some help from the fine chaps over at YouTube.
For one car I had to remove the entire dash, for the other I was able to unscrew just the receiver (but set off the anti-theft alarm midway).

Pop the hood and unplug the battery before starting, of course.

After freeing it, the old receiver should slide out with some encouragement, at which point you can swap the cable plugs and slide the new in.
Daiylight and an extra pair of hands to hold the receiver while you grope around for the cables would be handy, though I ended up doing it alone in the dark because I couldn't wait.

Close it up, reconnect the power, engine on, and hope for the best.

## Done
I'm far from being competant at auto maintenance (this was my first time under the hood, even), but this project was pretty approachable, cheap (<$100) and requires minimal tools -- once you've figured out what parts you need.


text:
layout:     post
title:      "OAuth2.0 reading notes"
subtitle:   ""
date:       2016-09-09 23:00:00
author:     "Phil"
header-img: "img/post-bg-06.jpg"
---

## Overview

OAuth 2.0 is a protocol that allows distinct parties to share information and resources in a secure and reliable manner.

Strictly speaking, the OAuth 2.0 protocol is actually an authorization protocol and not an authentication protocol.

OAuth 2.0 involve two things:

* Allowing a user to log into an application with another account. For example, Pinterest allowing users to log in with their Twitter accounts. This is known as **federated identity**.

* Allowing one service to access resources on another service on behalf of the user. For example, Adobe accessing your Facebook photos on your behalf. This is known as **delegated authority**.

Four main grant typea:

* Authorization code grant
* Implicit grant
* resource owner password credentials (not recommend)
* The client credentials(not recommend)

## Implicit grant(client side flow)

Implicit grant type suited for untrusted case:  access token is provided.

### Pros

There is a convenient pro for being an untrusted client:

**Simplicity**: Due to the straightforward design, this solution is very simple to implement. Since all of the work happens in the browser, no backend servers or data stores are required for such an application. (If they had these, they could be considered trusted.)

### Cons

However, here are the cons:

* Less security: The key must be relayed to the browser for the client application to use. The browser is considered public and so this key may easily fall into the hands of another user.

* Short-term access only: Since the client is untrusted, they cannot store keys for long-term use. Because of this, the user will have to reauthenticate and regrant access more often than with a trusted client.

## Authorization code grant(server side flow)

resource owner password : (end user credential is provided)

user provide credential to client app, client app request the access token on behalf of end user

client credential: (no end user is involved)
client app request the token directly


text:
@implementation CommentModel

-(instancetype)initWithDict:(NSDictionary *)dic{

    if (self = [super init]) {
        NSString *string =dic[@"f"];
        NSRange rang =[string rangeOfString:@"["];

        self.address =[string substringToIndex:rang.location];

        self.comment =dic[@"b"];

        rang =[string rangeOfString:@"["];
        NSInteger start = rang.location;
        rang =[string rangeOfString:@"]"];
        NSInteger end = rang.location;

        self.name = [string substringWithRange:NSMakeRange(start+1, end - start-1)];
        self.timeString =dic[@"t"];

    }
    return self;

}
- (CGSize)sizeWithConstrainedToSize:(CGSize)size
{
    NSDictionary *attribute = @{NSFontAttributeName: CommentFont};
    CGSize textSize         = [self.comment boundingRectWithSize:CGSizeMake(size.width, 0)
                                                 options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading
                                              attributes:attribute
                                                 context:nil].size;
    return textSize;
}
@end


text:
bool StrLessSensitive( const char * const &pszLeft, const char * const &pszRight )
{
	return ( Q_strcmp( pszLeft, pszRight) < 0 );
}

bool StrLessInsensitive( const char * const &pszLeft, const char * const &pszRight )
{
        return ( Q_stricmp( pszLeft, pszRight) < 0 );
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

CStringPool::CStringPool( StringPoolCase_t caseSensitivity )
  : m_Strings( 32, 256, caseSensitivity == StringPoolCaseInsensitive ? StrLessInsensitive : StrLessSensitive )
{
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

CStringPool::~CStringPool()
{
	FreeAll();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

unsigned int CStringPool::Count() const
{
	return m_Strings.Count();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const char * CStringPool::Find( const char *pszValue )
{
	unsigned short i = m_Strings.Find(pszValue);
	if ( m_Strings.IsValidIndex(i) )
		return m_Strings[i];

	return NULL;
}

const char * CStringPool::Allocate( const char *pszValue )
{
	char	*pszNew;

	unsigned short i 	= m_Strings.Find(pszValue);
	bool		   bNew = (i == m_Strings.InvalidIndex());

	if ( !bNew )
		return m_Strings[i];

	pszNew = strdup( pszValue );

	if ( bNew )
		m_Strings.Insert( pszNew );

	return pszNew;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

void CStringPool::FreeAll()
{
	unsigned short i = m_Strings.FirstInorder();
	while ( i != m_Strings.InvalidIndex() )
	{
		free( (void *)m_Strings[i] );
		i = m_Strings.NextInorder(i);
	}
	m_Strings.RemoveAll();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

CCountedStringPool::CCountedStringPool( StringPoolCase_t caseSensitivity )
{
	MEM_ALLOC_CREDIT();
	m_HashTable.EnsureCount(HASH_TABLE_SIZE);

	for( int i = 0; i < m_HashTable.Count(); i++ )
	{
		m_HashTable[i] = INVALID_ELEMENT;
	}

	m_FreeListStart = INVALID_ELEMENT;
	m_Elements.AddToTail();
	m_Elements[0].pString = NULL;
	m_Elements[0].nReferenceCount = 0;
	m_Elements[0].nNextElement = INVALID_ELEMENT;

	m_caseSensitivity = caseSensitivity;
}

CCountedStringPool::~CCountedStringPool()
{
	FreeAll();
}

void CCountedStringPool::FreeAll()
{
	int i;

	// Reset the hash table:
	for( i = 0; i < m_HashTable.Count(); i++ )
	{
		m_HashTable[i] = INVALID_ELEMENT;
	}

	// Blow away the free list:
	m_FreeListStart = INVALID_ELEMENT;

	for( i = 0; i < m_Elements.Count(); i++ )
	{
		if( m_Elements[i].pString )
		{
			delete [] m_Elements[i].pString;
			m_Elements[i].pString = NULL;
			m_Elements[i].nReferenceCount = 0;
			m_Elements[i].nNextElement = INVALID_ELEMENT;
		}
	}

	// Remove all but the invalid element:
	m_Elements.RemoveAll();
	m_Elements.AddToTail();
	m_Elements[0].pString = NULL;
	m_Elements[0].nReferenceCount = 0;
	m_Elements[0].nNextElement = INVALID_ELEMENT;
}

unsigned short CCountedStringPool::FindStringHandle( const char* pIntrinsic )
{
	if( pIntrinsic == NULL )
		return INVALID_ELEMENT;

	unsigned short nHashBucketIndex = (m_caseSensitivity ? HashString( pIntrinsic ) : HashStringCaseless( pIntrinsic ) %HASH_TABLE_SIZE);
	unsigned short nCurrentBucket = m_HashTable[ nHashBucketIndex ];

	// Does the bucket already exist?
	if( nCurrentBucket != INVALID_ELEMENT  )
	{
		for( ; nCurrentBucket != INVALID_ELEMENT  ; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement )
		{
			if( !Q_stricmp( pIntrinsic, m_Elements[nCurrentBucket].pString ) )
			{
				return nCurrentBucket;
			}
		}
	}

	return 0;

}

char* CCountedStringPool::FindString( const char* pIntrinsic )
{
	if( pIntrinsic == NULL )
		return NULL;

	// Yes, this will be NULL on failure.
	return m_Elements[FindStringHandle(pIntrinsic)].pString;
}

unsigned short CCountedStringPool::ReferenceStringHandle( const char* pIntrinsic )
{
	if( pIntrinsic == NULL )
		return INVALID_ELEMENT;

	unsigned short nHashBucketIndex = (m_caseSensitivity ? HashString( pIntrinsic ) : HashStringCaseless( pIntrinsic ) % HASH_TABLE_SIZE);
	unsigned short nCurrentBucket =  m_HashTable[ nHashBucketIndex ];

	// Does the bucket already exist?
	if( nCurrentBucket != INVALID_ELEMENT )
	{
		for( ; nCurrentBucket != INVALID_ELEMENT ; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement )
		{
			if( !Q_stricmp( pIntrinsic, m_Elements[nCurrentBucket].pString ) )
			{
				// Anyone who hits 65k references is permanant
				if( m_Elements[nCurrentBucket].nReferenceCount < MAX_REFERENCE )
				{
					m_Elements[nCurrentBucket].nReferenceCount ++ ;
				}
				return nCurrentBucket;
			}
		}
	}

	if( m_FreeListStart != INVALID_ELEMENT )
	{
		nCurrentBucket = m_FreeListStart;
		m_FreeListStart = m_Elements[nCurrentBucket].nNextElement;
	}
	else
	{
		nCurrentBucket = m_Elements.AddToTail();
	}

	m_Elements[nCurrentBucket].nReferenceCount = 1;

	// Insert at the beginning of the bucket:
	m_Elements[nCurrentBucket].nNextElement = m_HashTable[ nHashBucketIndex ];
	m_HashTable[ nHashBucketIndex ] = nCurrentBucket;

	m_Elements[nCurrentBucket].pString = new char[Q_strlen( pIntrinsic ) + 1];
	Q_strcpy( m_Elements[nCurrentBucket].pString, pIntrinsic );

    return nCurrentBucket;
}

char* CCountedStringPool::ReferenceString( const char* pIntrinsic )
{
	if(!pIntrinsic)
		return NULL;

	return m_Elements[ReferenceStringHandle( pIntrinsic)].pString;
}

void CCountedStringPool::DereferenceString( const char* pIntrinsic )
{
	// If we get a NULL pointer, just return
	if (!pIntrinsic)
		return;

	unsigned short nHashBucketIndex = (m_caseSensitivity ? HashString( pIntrinsic ) : HashStringCaseless( pIntrinsic ) % m_HashTable.Count());
	unsigned short nCurrentBucket =  m_HashTable[ nHashBucketIndex ];

	// If there isn't anything in the bucket, just return.
	if ( nCurrentBucket == INVALID_ELEMENT )
		return;

	for( unsigned short previous = INVALID_ELEMENT; nCurrentBucket != INVALID_ELEMENT ; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement )
	{
		if( !Q_stricmp( pIntrinsic, m_Elements[nCurrentBucket].pString ) )
		{
			// Anyone who hits 65k references is permanant
			if( m_Elements[nCurrentBucket].nReferenceCount < MAX_REFERENCE )
			{
				m_Elements[nCurrentBucket].nReferenceCount --;
			}

			if( m_Elements[nCurrentBucket].nReferenceCount == 0 )
			{
				if( previous == INVALID_ELEMENT )
				{
					m_HashTable[nHashBucketIndex] = m_Elements[nCurrentBucket].nNextElement;
				}
				else
				{
					m_Elements[previous].nNextElement = m_Elements[nCurrentBucket].nNextElement;
				}

				delete [] m_Elements[nCurrentBucket].pString;
				m_Elements[nCurrentBucket].pString = NULL;
				m_Elements[nCurrentBucket].nReferenceCount = 0;

				m_Elements[nCurrentBucket].nNextElement = m_FreeListStart;
				m_FreeListStart = nCurrentBucket;
				break;

			}
		}

		previous = nCurrentBucket;
	}
}

char* CCountedStringPool::HandleToString( unsigned short handle )
{
	return m_Elements[handle].pString;
}

unsigned CCountedStringPool::Hash( const char *pszKey )
{
	if (m_caseSensitivity == StringPoolCaseSensitive)
		return HashString( pszKey );

	return HashStringCaseless( pszKey );
}

void CCountedStringPool::SpewStrings()
{
	int i;
	for ( i = 0; i < m_Elements.Count(); i++ )
	{
		char* string = m_Elements[i].pString;

		Msg("String %d: ref:%d %s", i, m_Elements[i].nReferenceCount, string == NULL? "EMPTY - ok for slot zero only!" : string);
	}

	Msg("\n%d total counted strings.", m_Elements.Count());
}

#ifdef _DEBUG
CON_COMMAND( test_stringpool, "Tests the class CStringPool" )
{
	CStringPool pool;

	Assert(pool.Count() == 0);

	pool.Allocate("test");
	Assert(pool.Count() == 1);

	pool.Allocate("test");
	Assert(pool.Count() == 1);

	pool.Allocate("test2");
	Assert(pool.Count() == 2);

	Assert( pool.Find("test2") != NULL );
	Assert( pool.Find("TEST") != NULL );
	Assert( pool.Find("Test2") != NULL );
	Assert( pool.Find("test") != NULL );

	pool.FreeAll();
	Assert(pool.Count() == 0);

	Msg("Pass.");
}
#endif


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.afn.onthego.activities.DonateActivity">
    <item
        android:enabled="true"
        android:icon="@drawable/navbar_logo"
        android:onClick="openAfn"
        android:title="Go to austinfree.net"
        app:showAsAction="always" />
</menu>


text:
namespace pp {

PaintAggregator::PaintUpdate::PaintUpdate() : has_scroll(false) {}

PaintAggregator::PaintUpdate::~PaintUpdate() {}

PaintAggregator::InternalPaintUpdate::InternalPaintUpdate() {}

PaintAggregator::InternalPaintUpdate::~InternalPaintUpdate() {}

Rect PaintAggregator::InternalPaintUpdate::GetScrollDamage() const {
  // Should only be scrolling in one direction at a time.
  PP_DCHECK(!(scroll_delta.x() && scroll_delta.y()));

  Rect damaged_rect;

  // Compute the region we will expose by scrolling, and paint that into a
  // shared memory section.
  if (scroll_delta.x()) {
    int32_t dx = scroll_delta.x();
    damaged_rect.set_y(scroll_rect.y());
    damaged_rect.set_height(scroll_rect.height());
    if (dx > 0) {
      damaged_rect.set_x(scroll_rect.x());
      damaged_rect.set_width(dx);
    } else {
      damaged_rect.set_x(scroll_rect.right() + dx);
      damaged_rect.set_width(-dx);
    }
  } else {
    int32_t dy = scroll_delta.y();
    damaged_rect.set_x(scroll_rect.x());
    damaged_rect.set_width(scroll_rect.width());
    if (dy > 0) {
      damaged_rect.set_y(scroll_rect.y());
      damaged_rect.set_height(dy);
    } else {
      damaged_rect.set_y(scroll_rect.bottom() + dy);
      damaged_rect.set_height(-dy);
    }
  }

  // In case the scroll offset exceeds the width/height of the scroll rect
  return scroll_rect.Intersect(damaged_rect);
}

Rect PaintAggregator::InternalPaintUpdate::GetPaintBounds() const {
  Rect bounds;
  for (size_t i = 0; i < paint_rects.size(); ++i)
    bounds = bounds.Union(paint_rects[i]);
  return bounds;
}

PaintAggregator::PaintAggregator()
    : max_redundant_paint_to_scroll_area_(0.8f),
      max_paint_rects_(10) {
}

bool PaintAggregator::HasPendingUpdate() const {
  return !update_.scroll_rect.IsEmpty() || !update_.paint_rects.empty();
}

void PaintAggregator::ClearPendingUpdate() {
  update_ = InternalPaintUpdate();
}

PaintAggregator::PaintUpdate PaintAggregator::GetPendingUpdate() const {
  // Convert the internal paint update to the external one, which includes a
  // bit more precomputed info for the caller.
  PaintUpdate ret;
  ret.scroll_delta = update_.scroll_delta;
  ret.scroll_rect = update_.scroll_rect;
  ret.has_scroll = ret.scroll_delta.x() != 0 || ret.scroll_delta.y() != 0;

  ret.paint_rects.reserve(update_.paint_rects.size() + 1);
  for (size_t i = 0; i < update_.paint_rects.size(); i++)
    ret.paint_rects.push_back(update_.paint_rects[i]);

  ret.paint_bounds = update_.GetPaintBounds();

  // Also include the scroll damage (if any) in the paint rects.
  if (ret.has_scroll) {
    PP_Rect scroll_damage = update_.GetScrollDamage();
    ret.paint_rects.push_back(scroll_damage);
    ret.paint_bounds = ret.paint_bounds.Union(scroll_damage);
  }

  return ret;
}

void PaintAggregator::InvalidateRect(const Rect& rect) {
  // Combine overlapping paints using smallest bounding box.
  for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
    const Rect& existing_rect = update_.paint_rects[i];
    if (existing_rect.Contains(rect))  // Optimize out redundancy.
      return;
    if (rect.Intersects(existing_rect) || rect.SharesEdgeWith(existing_rect)) {
      // Re-invalidate in case the union intersects other paint rects.
      Rect combined_rect = existing_rect.Union(rect);
      update_.paint_rects.erase(update_.paint_rects.begin() + i);
      InvalidateRect(combined_rect);
      return;
    }
  }

  // Add a non-overlapping paint.
  update_.paint_rects.push_back(rect);

  // If the new paint overlaps with a scroll, then it forces an invalidation of
  // the scroll.  If the new paint is contained by a scroll, then trim off the
  // scroll damage to avoid redundant painting.
  if (!update_.scroll_rect.IsEmpty()) {
    if (ShouldInvalidateScrollRect(rect)) {
      InvalidateScrollRect();
    } else if (update_.scroll_rect.Contains(rect)) {
      update_.paint_rects[update_.paint_rects.size() - 1] =
          rect.Subtract(update_.GetScrollDamage());
      if (update_.paint_rects[update_.paint_rects.size() - 1].IsEmpty())
        update_.paint_rects.erase(update_.paint_rects.end() - 1);
    }
  }

  if (update_.paint_rects.size() > max_paint_rects_)
    CombinePaintRects();
}

void PaintAggregator::ScrollRect(const Rect& clip_rect, const Point& amount) {
  // We only support scrolling along one axis at a time.
  if (amount.x() != 0 && amount.y() != 0) {
    InvalidateRect(clip_rect);
    return;
  }

  // We can only scroll one rect at a time.
  if (!update_.scroll_rect.IsEmpty() && update_.scroll_rect != clip_rect) {
    InvalidateRect(clip_rect);
    return;
  }

  // Again, we only support scrolling along one axis at a time.  Make sure this
  // update doesn't scroll on a different axis than any existing one.
  if ((amount.x() && update_.scroll_delta.y()) ||
      (amount.y() && update_.scroll_delta.x())) {
    InvalidateRect(clip_rect);
    return;
  }

  // The scroll rect is new or isn't changing (though the scroll amount may
  // be changing).
  update_.scroll_rect = clip_rect;
  update_.scroll_delta += amount;

  // We might have just wiped out a pre-existing scroll.
  if (update_.scroll_delta == Point()) {
    update_.scroll_rect = Rect();
    return;
  }

  // Adjust any contained paint rects and check for any overlapping paints.
  for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
    if (update_.scroll_rect.Contains(update_.paint_rects[i])) {
      update_.paint_rects[i] = ScrollPaintRect(update_.paint_rects[i], amount);
      // The rect may have been scrolled out of view.
      if (update_.paint_rects[i].IsEmpty()) {
        update_.paint_rects.erase(update_.paint_rects.begin() + i);
        i--;
      }
    } else if (update_.scroll_rect.Intersects(update_.paint_rects[i])) {
      InvalidateScrollRect();
      return;
    }
  }

  // If the new scroll overlaps too much with contained paint rects, then force
  // an invalidation of the scroll.
  if (ShouldInvalidateScrollRect(Rect()))
    InvalidateScrollRect();
}

Rect PaintAggregator::ScrollPaintRect(const Rect& paint_rect,
                                      const Point& amount) const {
  Rect result = paint_rect;

  result.Offset(amount);
  result = update_.scroll_rect.Intersect(result);

  // Subtract out the scroll damage rect to avoid redundant painting.
  return result.Subtract(update_.GetScrollDamage());
}

bool PaintAggregator::ShouldInvalidateScrollRect(const Rect& rect) const {
  if (!rect.IsEmpty()) {
    if (!update_.scroll_rect.Intersects(rect))
      return false;

    if (!update_.scroll_rect.Contains(rect))
      return true;
  }

  // Check if the combined area of all contained paint rects plus this new
  // rect comes too close to the area of the scroll_rect.  If so, then we
  // might as well invalidate the scroll rect.

  int paint_area = rect.size().GetArea();
  for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
    const Rect& existing_rect = update_.paint_rects[i];
    if (update_.scroll_rect.Contains(existing_rect))
      paint_area += existing_rect.size().GetArea();
  }
  int scroll_area = update_.scroll_rect.size().GetArea();
  if (float(paint_area) / float(scroll_area) > max_redundant_paint_to_scroll_area_)
    return true;

  return false;
}

void PaintAggregator::InvalidateScrollRect() {
  Rect scroll_rect = update_.scroll_rect;
  update_.scroll_rect = Rect();
  update_.scroll_delta = Point();
  InvalidateRect(scroll_rect);
}

void PaintAggregator::CombinePaintRects() {
  // Combine paint rects down to at most two rects: one inside the scroll_rect
  // and one outside the scroll_rect.  If there is no scroll_rect, then just
  // use the smallest bounding box for all paint rects.
  //
  // NOTE: This is a fairly simple algorithm.  We could get fancier by only
  // combining two rects to get us under the max_paint_rects limit, but if we
  // reach this method then it means we're hitting a rare case, so there's no
  // need to over-optimize it.
  //
  if (update_.scroll_rect.IsEmpty()) {
    Rect bounds = update_.GetPaintBounds();
    update_.paint_rects.clear();
    update_.paint_rects.push_back(bounds);
  } else {
    Rect inner, outer;
    for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
      const Rect& existing_rect = update_.paint_rects[i];
      if (update_.scroll_rect.Contains(existing_rect)) {
        inner = inner.Union(existing_rect);
      } else {
        outer = outer.Union(existing_rect);
      }
    }
    update_.paint_rects.clear();
    update_.paint_rects.push_back(inner);
    update_.paint_rects.push_back(outer);
  }
}

}  // namespace pp


text:
	<input type="text" id="p" value="bar.foo" onkeyup="update()" />
	<input type="text" id="pattern" value="*.foo" onkeyup="update()" />


text:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/from';
import 'rxjs/add/observable/throw';

import { enableProdMode} from '@angular/core';

import { AppModule }  from './app/app.module';

if ('prod' === ENV) {
  enableProdMode();
}

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule);


text:
#include "CCPUForceField.h"

NS_CC_BEGIN

const Vec3 PUForceFieldCalculationFactory::DEFAULT_WORLDSIZE(500.0f, 500.0f, 500.0f);

//-----------------------------------------------------------------------
unsigned short PUForceFieldCalculationFactory::getOctaves(void) const
{
    return _octaves;
}
//-----------------------------------------------------------------------
void PUForceFieldCalculationFactory::setOctaves(unsigned short octaves)
{
    _octaves = octaves;
    generate(getForceFieldSize(), _octaves, _frequency, _amplitude, _persistence, _worldSize);
}
//-----------------------------------------------------------------------
double PUForceFieldCalculationFactory::getFrequency(void) const
{
    return _frequency;
}
//-----------------------------------------------------------------------
void PUForceFieldCalculationFactory::setFrequency(double frequency)
{
    _frequency = frequency;
    generate(getForceFieldSize(), _octaves, _frequency, _amplitude, _persistence, _worldSize);
}
//-----------------------------------------------------------------------
double PUForceFieldCalculationFactory::getAmplitude(void) const
{
    return _amplitude;
}
//-----------------------------------------------------------------------
void PUForceFieldCalculationFactory::setAmplitude(double amplitude)
{
    _amplitude = amplitude;
    generate(getForceFieldSize(), _octaves, _frequency, _amplitude, _persistence, _worldSize);
}
//-----------------------------------------------------------------------
double PUForceFieldCalculationFactory::getPersistence(void) const
{
    return _persistence;
}
//-----------------------------------------------------------------------
void PUForceFieldCalculationFactory::setPersistence(double persistence)
{
    _persistence = persistence;
    generate(getForceFieldSize(), _octaves, _frequency, _amplitude, _persistence, _worldSize);
}
//-----------------------------------------------------------------------
unsigned int PUForceFieldCalculationFactory::getForceFieldSize(void) const
{
    return 1; // Return default cubic size
}
//-----------------------------------------------------------------------
void PUForceFieldCalculationFactory::setForceFieldSize(unsigned int forceFieldSize)
{
    // The forcefield cannot be zero
    if (forceFieldSize == 0)
        return;

    generate(forceFieldSize, _octaves, _frequency, _amplitude, _persistence, _worldSize);
}
//-----------------------------------------------------------------------
Vec3 PUForceFieldCalculationFactory::getWorldSize(void) const
{
    return _worldSize;
}
//-----------------------------------------------------------------------
void PUForceFieldCalculationFactory::setWorldSize(const Vec3& worldSize)
{
    // The worldsize cannot be zero
    if (worldSize == Vec3::ZERO)
        return;

    _worldSize = worldSize;
    generate(getForceFieldSize(), _octaves, _frequency, _amplitude, _persistence, _worldSize);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
void PURealTimeForceFieldCalculationFactory::generate(unsigned int /*forceFieldSize*/,
                                                    unsigned short octaves,
                                                    double frequency,
                                                    double amplitude,
                                                    double persistence,
                                                    const Vec3& worldSize)
{
    _octaves = octaves;
    _frequency = frequency;
    _amplitude = amplitude;
    _persistence = persistence;
    _worldSize = worldSize;
    _noise3D.initialise(octaves, frequency, amplitude, persistence);

    if (worldSize != Vec3::ZERO)
    {
        _mapScale.x = 1.0f / worldSize.x; // Remark: forceFieldSize is not used, because it is a unit cube
        _mapScale.y = 1.0f / worldSize.y;
        _mapScale.z = 1.0f / worldSize.z;
    }
}
//-----------------------------------------------------------------------
void PURealTimeForceFieldCalculationFactory::determineForce(const Vec3& position, Vec3& force, float delta)
{
    _mappedPosition.x = _mapScale.x * position.x;
    _mappedPosition.y = _mapScale.y * position.y;
    _mappedPosition.z = _mapScale.z * position.z;

    if (_mappedPosition.x < 0.0f || _mappedPosition.x > 1.0f ||
        _mappedPosition.y < 0.0f || _mappedPosition.y > 1.0f ||
        _mappedPosition.z < 0.0f || _mappedPosition.z > 1.0f)
    {
        // Position is outside the forcefield (outside the unit cube)
        return;
    }

    force.x = (float)(_noise3D.noise(_mappedPosition.x + delta, _mappedPosition.y, _mappedPosition.z) -
        _noise3D.noise(_mappedPosition.x - delta, _mappedPosition.y, _mappedPosition.z));
    force.y = (float)(_noise3D.noise(_mappedPosition.x, _mappedPosition.y + delta, _mappedPosition.z) -
        _noise3D.noise(_mappedPosition.x, _mappedPosition.y - delta, _mappedPosition.z));
    force.z = (float)(_noise3D.noise(_mappedPosition.x, _mappedPosition.y, _mappedPosition.z + delta) -
        _noise3D.noise(_mappedPosition.x, _mappedPosition.y, _mappedPosition.z - delta));
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
PUForceField::PUForceField(void) :
    _octaves(2),
    _frequency(1.0f),
    _amplitude(1.0f),
    _persistence(1.0f),
    _worldSize(PUForceFieldCalculationFactory::DEFAULT_WORLDSIZE),
    _forceFieldSize(64),
    _forceFieldCalculationFactory(0),
    _forceFieldType(FF_REALTIME_CALC)
{
}
//-----------------------------------------------------------------------
PUForceField::~PUForceField(void)
{
    if (_forceFieldCalculationFactory)
    {
        delete _forceFieldCalculationFactory;
    }
}
//-----------------------------------------------------------------------
void PUForceField::initialise(ForceFieldType type,
                            const Vec3& position,
                            unsigned int forceFieldSize,
                            unsigned short octaves,
                            double frequency,
                            double amplitude,
                            double persistence,
                            const Vec3& worldSize)

{
    // Initialise first
    initialise(type, forceFieldSize, octaves, frequency, amplitude, persistence, worldSize);

    // Store the base and max position of the forcefield.
    _forceFieldPositionBase = position;
    _forceFieldPositionBase.x -= 0.5f * worldSize.x;
    _forceFieldPositionBase.y -= 0.5f * worldSize.y;
    _forceFieldPositionBase.z -= 0.5f * worldSize.z;
}
//-----------------------------------------------------------------------
void PUForceField::initialise(ForceFieldType type,
                            unsigned int forceFieldSize,
                            unsigned short octaves,
                            double frequency,
                            double amplitude,
                            double persistence,
                            const Vec3& worldSize)
{
    // Create a factory
    _forceFieldCalculationFactory = createForceFieldCalculationFactory(type);

    // Create all necessary data for the force field
    _forceFieldCalculationFactory->generate(forceFieldSize, octaves, frequency, amplitude, persistence, worldSize);
}
//-----------------------------------------------------------------------
const Vec3& PUForceField::getForceFieldPositionBase(void) const
{
    return _forceFieldPositionBase;
}
//-----------------------------------------------------------------------
void PUForceField::setForceFieldPositionBase(const Vec3& position)
{
    _forceFieldPositionBase = position;
}
//-----------------------------------------------------------------------
void PUForceField::determineForce(const Vec3& position, Vec3& force, float delta)
{
    force.x = 0.0f;
    force.y = 0.0f;
    force.z = 0.0f;

    if (_forceFieldCalculationFactory)
    {
        _forceFieldCalculationFactory->determineForce(position - _forceFieldPositionBase, force, delta);
    }
}
//-----------------------------------------------------------------------
PUForceFieldCalculationFactory* PUForceField::getForceFieldCalculationFactory() const
{
    return _forceFieldCalculationFactory;
}
//-----------------------------------------------------------------------
void PUForceField::setForceFieldCalculationFactory(PUForceFieldCalculationFactory* forceFieldCalculationFactory)
{
    if (_forceFieldCalculationFactory)
    {
        delete _forceFieldCalculationFactory;
    }
    _forceFieldCalculationFactory = forceFieldCalculationFactory;
}
//-----------------------------------------------------------------------
PUForceFieldCalculationFactory* PUForceField::createForceFieldCalculationFactory(ForceFieldType type)
{
    _forceFieldType = type;
    if (type == FF_MATRIX_CALC)
    {
        // Use precreated matrix
        //setForceFieldCalculationFactory(new MatrixForceFieldCalculationFactory());
        return getForceFieldCalculationFactory();
    }
    else
    {
        // Use realtime calculation
        setForceFieldCalculationFactory(new (std::nothrow) PURealTimeForceFieldCalculationFactory());
        return getForceFieldCalculationFactory();
    }
}
//-----------------------------------------------------------------------
PUForceField::ForceFieldType PUForceField::getForceFieldType() const
{
    return _forceFieldType;
}
//-----------------------------------------------------------------------
void PUForceField::setForceFieldType(const PUForceField::ForceFieldType forceFieldType)
{
    _forceFieldType = forceFieldType;
    if (_forceFieldCalculationFactory)
    {
        initialise(_forceFieldType, _forceFieldSize, _octaves, _frequency, _amplitude, _persistence, _worldSize);
    }
}
//-----------------------------------------------------------------------
unsigned short PUForceField::getOctaves(void) const
{
    return _octaves;
}
//-----------------------------------------------------------------------
void PUForceField::setOctaves(unsigned short octaves)
{
    _octaves = octaves;
    if (_forceFieldCalculationFactory)
    {
        _forceFieldCalculationFactory->setOctaves(octaves);
    }
}
//-----------------------------------------------------------------------
double PUForceField::getFrequency(void) const
{
    return _frequency;
}
//-----------------------------------------------------------------------
void PUForceField::setFrequency(double frequency)
{
    _frequency = frequency;
    if (_forceFieldCalculationFactory)
    {
        _forceFieldCalculationFactory->setFrequency(frequency);
    }
}
//-----------------------------------------------------------------------
double PUForceField::getAmplitude(void) const
{
    return _amplitude;
}
//-----------------------------------------------------------------------
void PUForceField::setAmplitude(double amplitude)
{
    _amplitude = amplitude;
    if (_forceFieldCalculationFactory)
    {
        _forceFieldCalculationFactory->setAmplitude(amplitude);
    }
}
//-----------------------------------------------------------------------
double PUForceField::getPersistence(void) const
{
    return _persistence;
}
//-----------------------------------------------------------------------
void PUForceField::setPersistence(double persistence)
{
    _persistence = persistence;
    if (_forceFieldCalculationFactory)
    {
        _forceFieldCalculationFactory->setPersistence(persistence);
    }
}
//-----------------------------------------------------------------------
unsigned int PUForceField::getForceFieldSize(void) const
{
    return _forceFieldSize;
}
//-----------------------------------------------------------------------
void PUForceField::setForceFieldSize(unsigned int forceFieldSize)
{
    _forceFieldSize = forceFieldSize;
    if (_forceFieldCalculationFactory)
    {
        _forceFieldCalculationFactory->setForceFieldSize(forceFieldSize);
    }
}
//-----------------------------------------------------------------------
Vec3 PUForceField::getWorldSize(void) const
{
    return _worldSize;
}
//-----------------------------------------------------------------------
void PUForceField::setWorldSize(const Vec3& worldSize)
{
    _worldSize = worldSize;
    if (_forceFieldCalculationFactory)
    {
        _forceFieldCalculationFactory->setWorldSize(worldSize);
    }
}

NS_CC_END


text:
<form name="importForm" ng-submit="importBlob(importForm)" novalidate>

Choose a backup file from your computer

        <input type="file"
          placeholder="{{'Select a backup file'|translate}}"
          ng-model="formData.backupFile" ng-file-select>

      Paste the backup plain text code
      <textarea ng-model="formData.backupText" rows="5"></textarea>

      Password
      <input type="password"
        placeholder="{{'Your password'|translate}}"
        ng-model="formData.password">

      Show advanced options
      Hide advanced options

        Wallet Service URL
        <input type="text" ng-model="formData.bwsurl">

  <button type="submit" class="button button-standard button-primary" ng-disabled="importForm.$invalid || !formData.password" translate>
    Import backup
  </button>
</form>


text:
import angr
from angr.sim_type import SimTypeString, SimTypeInt

import logging
l = logging.getLogger("angr.procedures.libc.strcmp")

class strcmp(angr.SimProcedure):
    #pylint:disable=arguments-differ

    def run(self, a_addr, b_addr):
        self.argument_types = {0: self.ty_ptr(SimTypeString()),
                       1: self.ty_ptr(SimTypeString())}
        self.return_type = SimTypeInt(32, True)

        strlen = angr.SIM_PROCEDURES['libc']['strlen']

        a_strlen = self.inline_call(strlen, a_addr)
        b_strlen = self.inline_call(strlen, b_addr)
        maxlen = self.state.se.BVV(max(a_strlen.max_null_index, b_strlen.max_null_index), self.state.arch.bits)

        strncmp = self.inline_call(angr.SIM_PROCEDURES['libc']['strncmp'], a_addr, b_addr, maxlen, a_len=a_strlen, b_len=b_strlen)
        return strncmp.ret_expr


text:
"""
    pyexcel.plugins.parsers.excel
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Parsing excel sources

    :copyright: (c) 2015-2017 by Onni Software Ltd.
    :license: New BSD License
"""
from pyexcel.parser import AbstractParser
from pyexcel_io import get_data, iget_data

class ExcelParser(AbstractParser):
    """get data from excel files"""
    def parse_file(self, file_name, **keywords):
        return self._parse_any(file_name, **keywords)

    def parse_file_stream(self, file_stream, **keywords):
        return self._parse_any(
            file_stream, file_type=self._file_type, **keywords)

    def parse_file_content(self, file_content, **keywords):
        return self._parse_any(
            file_content, file_type=self._file_type, **keywords)

    def _parse_any(self, anything, on_demand=False,
                   file_type=None, **keywords):
        if on_demand:
            sheets, reader = iget_data(
                anything, file_type=file_type, **keywords)
            self._free_me_up_later(reader)
        else:
            sheets = get_data(
                anything, file_type=file_type, **keywords)
        return sheets


text:
package gitutils

import (
	"fmt"

	"gopkg.in/libgit2/git2go.v22"
)

type CloneInfo struct {
	Reponame string
	Path string
	URL string
	Branch string
}

// Clone a repo
func (c *CloneInfo) CloneRepo() (*git.Repository, error) {
	repo, err := git.OpenRepository(c.Path)
	if err != nil {
		cloneOptions := &git.CloneOptions{
			Bare:             false,
			CheckoutBranch:   c.Branch,
			FetchOptions: &git.FetchOptions {
				RemoteCallbacks: git.RemoteCallbacks{
					CredentialsCallback:  credentialsCallback,
					CertificateCheckCallback: certificateCheckCallback,
				},
			},
			CheckoutOpts: &git.CheckoutOpts{
				Strategy: git.CheckoutSafe,
			},
		}
		repo, err := git.Clone(c.URL,c.Path,cloneOptions)
		if err != nil {
			ret := fmt.Errorf(" %s : %s\n", err, c.URL)
			return nil, ret
		}
		return repo, nil
	}
	return repo, nil
}


text:
Spree::Product.class_eval do
  # Can't use add_search_scope for this as it needs a default argument
  def self.available(available_on = nil, currency = nil)
    scope = joins(:master => :prices).where("#{Spree::Product.quoted_table_name}.available_on <= ?", available_on || Time.now)
    scope = scope.where('spree_variants.sku != "SMP0001"')# TODO don't hard code this
    unless Spree::Config.show_products_without_price
      # should render product with any not null price
      scope = scope.where('spree_prices.amount IS NOT NULL')
    end
    scope
  end

  search_scopes << :available
end


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title></title>
  <base href="/">

  <link rel="stylesheet" href="stylesheets/app.css">
  <link rel="stylesheet" href="stylesheets/style.css">
  <link rel="stylesheet" href="stylesheets/offcanvas.css">
  <link rel="stylesheet" href="stylesheets/barlicons.css">

  <link rel="alternate" type="application/rss+xml" title="Full Blog Entries Feed" href="/feed" />

Home

About Us

Blog

Contact Us

 1-800-555-1234

 123 Main Street, Springfield, IL 12345

Home

About Us

Blog

Contact Us

Contact Us

Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa.

Our Location

123 Main Street

      		Springfield, IL 12345

1-800-555-1234 (toll-free)

      		555-555-1234 (cellular)

http://getbarley.com

Facebook

      		Twitter

      		Skype

      		LinkedIn

Panel Heading

Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit.

              Contact Us

Home

About Us

Blog

Contact

© Copyright Sequoia. All rights reserved.


text:
require 'test/unit'

class TC_File_Size_ClassMethod < Test::Unit::TestCase
   def setup
      @zero_file  = "zero.test"  # Size 0
      @small_file = "small.test" # Size > 0 < 2 GB
      @large_file = "large.test" # Size > 2 GB

      File.open(@zero_file, "wb+"){}
      File.open(@small_file, "wb+"){ |fh| 50.times{ fh.syswrite('hello') } }
   end

   def test_size_basic
      assert_respond_to(File, :size)
      assert_nothing_raised{ File.size(@zero_file) }
      assert_kind_of(Integer, File.size(@zero_file))
   end

   def test_size
      assert_equal(0, File.size(@zero_file))
      assert_equal(250, File.size(@small_file))
   end

   def test_size_expected_errors
      assert_raise(ArgumentError){ File.size }
      assert_raise(ArgumentError){ File.size(@zero_file, @small_file) }
   end

   def teardown
      File.unlink(@zero_file) if File.exists?(@zero_file)
      File.unlink(@small_file) if File.exists?(@small_file)
      File.unlink(@large_file) if File.exists?(@large_file)
   end
end


text:
aws-sqs-producer-consumer
=========================

A simple AWS Simple Queue Service (SQS) producer consumer programs.

###AWS Credentials:

create ~/.aws/credentails file with following content
```
[default]
aws_access_key_id=<your_access_key>
aws_secret_access_key=<your_secret_key>
```

###Producer:

Producer sends 'HELO' message to a queue every 100ms.

Producer takes two command line arguments

1. no of messages to send to the queue
2. producer identifier to label the message

To run:  `ruby producer.rb 100 1`

###Consumer:

Consumer consumes the message sent to the queue and wait for 200 ms before consuming the next message.

To run:  `ruby consumer.rb`

###Config:

You can change the queue_name, message_to_send, aws_region in config.yml


text:
namespace zippylog {

/// Parameters to instantiate a StoreWatcher class
class ZIPPYLOG_EXPORT StoreWatcherStartParams {
public:
    /// 0MQ context to use
    ::zmq::context_t *zctx;

    /// Store filesystem path to watch
    ::std::string store_path;

    /// 0MQ socket endpoint to send change notifications to
    ::std::string endpoint;

    /// 0MQ endpoint to send log messages to
    ::std::string logging_endpoint;

    /// Semaphore to control whether device should run
    ::zippylog::platform::ConditionalWait *active;
};

/// A directory watcher for file-based stores
///
/// This class watches the specified store directory for changes.
/// When changes are detected, it executes function callbacks, which
/// must be defined in an inherited class.
///
/// The directory watcher is currently designed to execute on its own
/// thread. Just instantiate a directory watcher and invoke Run(). This
/// function will block until the active semaphore contained in the start
/// parameters goes to false.
///
/// @todo move to device namespace
class ZIPPYLOG_EXPORT StoreWatcher : public ::zippylog::device::Device {
public:
    /// Instantiate a store watcher with the given parameters
    ///
    /// Will not actually start the store watcher. To do that, execute
    /// Run().
    ///
    /// @param params Parameters to construct watcher with
    StoreWatcher(StoreWatcherStartParams params);
    virtual ~StoreWatcher();

    /// Performs work
    ///
    /// @param timeout
    ::zippylog::device::PumpResult Pump(int32 timeout = 100);

    ///@{
    /// Device hooks
    virtual void OnRunStart();
    virtual void OnRunFinish();
    ///@}

protected:
    /// Function that performs actions when something is created
    ///
    /// Receives the path that was added as a store path (e.g.
    /// "/bucket/store/20101107T1615") and a stat record that describes
    /// the filesystem entity.
    ///
    /// @param path Store path that was added
    /// @param stat Filesystem stat result of new path
    virtual void HandleAdded(::std::string path, platform::FileStat &stat) = 0;

    /// Function that performs actions when something is deleted
    ///
    /// @param path The path that was deleted
    virtual void HandleDeleted(::std::string path) = 0;

    /// Performs actions when something (probably a stream) is modified
    ///
    /// @param path The path that was modified
    /// @param stat The result of a stat() on the modified path
    virtual void HandleModified(::std::string path, platform::FileStat &stat) = 0;

    /// Sends a change notification across the socket
    ///
    /// @param e Envelope to send
    void SendChangeMessage(Envelope &e);

    /// The store we are watching
    SimpleDirectoryStore * _store;

    /// 0MQ context
    ::zmq::context_t *_ctx;

    /// 0MQ endpoint to send notification messages to
    ::std::string _endpoint;

    /// 0MQ endpoint to send logging messages to
    ::std::string logging_endpoint;

    /// Unique identifier of this device
    ::std::string id;

    /// 0MQ socket we are sending notifications on
    ::zmq::socket_t * socket;

    /// 0MQ socket we are sending logging messages on
    ::zmq::socket_t * logging_sock;

    /// The underlying watcher looking for store changes
    platform::DirectoryWatcher watcher;

private:
    // we don't provide these
    StoreWatcher(StoreWatcher const &orig);
    StoreWatcher & operator=(StoreWatcher const &orig);

};

}

#endif


text:
DROP VIEW IF EXISTS staff_appointments;
DROP TABLE IF EXISTS appointments;
DROP TABLE IF EXISTS officehours;
DROP VIEW IF EXISTS staff_client_relationships;
DROP TABLE IF EXISTS relationship;
DROP VIEW IF EXISTS staff_members;
DROP TABLE IF EXISTS staff;
DROP VIEW IF EXISTS client_members;
DROP TABLE IF EXISTS clients;
DROP VIEW IF EXISTS usernames;
DROP TABLE IF EXISTS users CASCADE;

-- DROP VIEW IF EXISTS relationships;

CREATE TABLE users (
       id SERIAL PRIMARY KEY UNIQUE,
       email CITEXT UNIQUE NOT NULL,
       nickname TEXT NOT NULL
);

-- Users who are currently staff

CREATE TABLE staff (
       staff_id INTEGER UNIQUE REFERENCES users(id) ON DELETE CASCADE,
       active BOOLEAN
);

-- Users who are currently clients

CREATE TABLE clients (
       client_id INTEGER UNIQUE REFERENCES users(id) ON DELETE CASCADE,
       active BOOLEAN
);

-- This is interesting, because we've basically created a M:1
-- relationship of staff and clients, but a 1:1 relationship of
-- clients to staff.  That satisfies the current assignment, mostly.
-- An appointment can then be made my a client, and there's only one
-- staff person who it could apply to, so the query is straightforward
-- then.
--
-- If we wanted a client to have more than one coach, we'd have to
-- remove the UNIQUE constraint and let there be more than one
-- client-staff relationships.

CREATE TABLE relationship (
       id SERIAL PRIMARY KEY UNIQUE,
       client_id INTEGER UNIQUE NOT NULL REFERENCES clients(client_id) ON DELETE CASCADE,
       staff_id INTEGER NOT NULL REFERENCES staff(staff_id) ON DELETE CASCADE
);

-- Staff members may create office hours, but to prevent confusion we
-- should not allow a single staff-member's officehour entries to
-- overlap.  The && is the "overlaps" (has points in common) operator
-- for ranges.

CREATE TABLE officehours (
       id SERIAL PRIMARY KEY UNIQUE,
       staff_id INTEGER NOT NULL REFERENCES staff(staff_id) ON DELETE CASCADE,
       during TSRANGE,
       EXCLUDE USING gist (staff_id WITH =, during WITH &&)
);

-- This one is tricky.  We're basically saying that the client has an
-- appointment, and that's all we care about.  BUT the INSERT must
-- find the staff member with whom this client has a relationship, and
-- assert that the staff member has office hours at that time, and
-- that no other client off that staff member has already chosen an
-- overlapping appointment.

CREATE TABLE appointments (
       id SERIAL PRIMARY KEY UNIQUE,
       during TSRANGE,
       client_id INTEGER NOT NULL REFERENCES clients(client_id) ON DELETE CASCADE
);

CREATE VIEW usernames AS SELECT id, nickname FROM users;

CREATE VIEW staff_members AS
       (SELECT users.nickname AS staff_name, users.id AS staff_id
        FROM users WHERE users.id IN (SELECT staff_id FROM staff WHERE active=true));

CREATE VIEW client_members AS
         (SELECT users.nickname AS client_name, users.id AS client_id
          FROM users WHERE users.id IN (SELECT client_id FROM clients WHERE active=true));

CREATE VIEW staff_client_relationships AS
       (SELECT staff_name, staff_members.staff_id AS staff_id,
                           client_name, client_members.client_id AS client_id FROM relationship
               INNER JOIN staff_members ON relationship.staff_id = staff_members.staff_id
               INNER JOIN client_members ON relationship.client_id = client_members.client_id);

CREATE VIEW staff_appointments AS
       (SELECT staff_name,
               staff_client_relationships.staff_id AS staff_id,
               client_name,
               staff_client_relationships.client_id AS client_id,
               appointments.id AS appointment_id,
               during
        FROM appointments INNER JOIN staff_client_relationships
                          ON appointments.client_id = staff_client_relationships.client_id);

DROP FUNCTION IF EXISTS add_appointment(INT, TSRANGE);
CREATE OR REPLACE FUNCTION add_appointment(q_client_id INT, q_timerange TSRANGE) RETURNS VOID as $$
BEGIN
IF NOT EXISTS (SELECT officehours.id FROM officehours INNER JOIN relationship
    ON relationship.staff_id = officehours.staff_id
    WHERE relationship.client_id = q_client_id
    AND (q_timerange <@ officehours.during)) THEN
   RAISE EXCEPTION 'There are no office hours for your coach at that time.';
END IF;
IF EXISTS (SELECT appointments.id FROM appointments WHERE client_id IN (
                                 SELECT client_id FROM relationship WHERE staff_id IN (
                                 SELECT staff_id FROM relationship WHERE client_id = q_client_id))
                                  AND (q_timerange && appointments.during)) THEN
   RAISE EXCEPTION 'That appointment slot is already taken.';
END IF;
INSERT INTO appointments (client_id, during) SELECT q_client_id, q_timerange;
END
$$ LANGUAGE plpgsql;

-- Some basic testing starts below:

-- INSERT INTO users (nickname, email) VALUES ('Alice', 'alice@example.com');
-- INSERT INTO users (nickname, email) VALUES ('Bob', 'bob@example.com');
-- INSERT INTO users (nickname, email) VALUES ('Carol', 'carol@example.com');
-- INSERT INTO users (nickname, email) VALUES ('Doug', 'doug@example.com');

-- SELECT * from usernames;

-- INSERT INTO users (nickname, email) VALUES ('Ellen', 'ellen@example.com');
-- INSERT INTO users (nickname, email) VALUES ('Fred', 'fred@example.com');

-- SELECT * from usernames;

-- INSERT INTO staff (staff_id) SELECT id from users where email IN ('alice@example.com', 'bob@example.com');
-- INSERT INTO clients (client_id) SELECT id from users where email NOT IN ('alice@example.com', 'bob@example.com');
-- UPDATE staff SET active = True;
-- UPDATE clients SET active = True;

-- INSERT INTO relationship (staff_id, client_id) VALUES (1, 3);
-- INSERT INTO relationship (staff_id, client_id) VALUES (1, 4);
-- INSERT INTO relationship (staff_id, client_id) VALUES (2, 5);
-- INSERT INTO relationship (staff_id, client_id) VALUES (2, 6);

-- Note the plural:

-- WITH staff_members AS (SELECT users.nickname AS staff_name, users.id AS staff_id FROM users WHERE users.id IN (SELECT staff_id FROM staff WHERE active=true))

-- SELECT staff_name from staff_members;
-- SELECT client_name from client_members;

-- INSERT INTO officehours (staff_id, during) VALUES (1, '[2015-02-07 10:00, 2015-02-07 17:00)');
-- INSERT INTO officehours (staff_id, during) VALUES (2, '[2015-02-07 12:00, 2015-02-07 15:00)');

-- Insert an appointment with a client
-- WHERE the client's staffer has those office hours (DOES OVERLAP)

-- SELECT * FROM officehours INNER JOIN relationship
--                           ON relationship.staff_id = officehours.staff_id
--                           WHERE relationship.client_id = 3;

-- SELECT add_appointment(3, '[2015-02-07 10:00, 2015-02-07 10:30)');
-- SELECT add_appointment(4, '[2015-02-07 10:30, 2015-02-07 11:00)');
-- SELECT add_appointment(5, '[2015-02-07 13:00, 2015-02-07 13:30)');
-- SELECT add_appointment(6, '[2015-02-07 13:30, 2015-02-07 14:00)');

-- INSERT INTO appointments (client_id, during)
--        SELECT 3, '[2015-02-07 10:00, 2015-02-07 10:30)'
--        WHERE EXISTS (SELECT * FROM officehours INNER JOIN relationship
--                           ON relationship.staff_id = officehours.staff_id
--                           WHERE relationship.client_id = 3
--                           AND (officehours.during && '[2015-02-07 10:00, 2015-02-07 10:30)'))
--        AND NOT EXISTS (SELECT * from appointments INNER JOIN
--
-- SELECT * FROM officehours INNER JOIN relationship
--                           ON relationship.staff_id = officehours.staff_id
--                           WHERE relationship.client_id = 3
--                           AND (officehours.during && '[2015-02-07 10:00, 2015-02-07 10:30)');
--

-- SELECT client_id, during FROM appointments WHERE client_id IN (
--        SELECT client_id FROM relationship WHERE staff_id IN (
--               SELECT staff_id FROM relationship WHERE client_id = 3));
--


text:
package org.culturegraph.mf.stream.converter.xml;

import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;

import org.culturegraph.mf.framework.StreamReceiver;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.xml.sax.helpers.AttributesImpl;

/**
 * Tests for class {@link GenericXmlHandler}.
 *
 * @author Christoph Böhme
 *
 */
public final class GenericXMLHandlerTest {

	@Mock
	private StreamReceiver receiver;

	private GenericXmlHandler genericXmlHandler;

	private AttributesImpl attributes;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
		genericXmlHandler = new GenericXmlHandler("record");
		genericXmlHandler.setReceiver(receiver);
	}

	@Before
	public void createHelperObjects() {
		attributes = new AttributesImpl();
	}

	@Test
	public void shouldIgnoreElementsOutsideRecordElement() {
		genericXmlHandler.startElement("", "ignore-me", "ignore-me", attributes);

		verifyZeroInteractions(receiver);
	}

	@Test
	public void shouldEmitRecordElementAsStartAndEndRecordEvent() {
		genericXmlHandler.startElement("", "record", "record", attributes);
		genericXmlHandler.endElement("", "record", "record");

		final InOrder ordered = inOrder(receiver);
		ordered.verify(receiver).startRecord("");
		ordered.verify(receiver).endRecord();
	}

	@Test
	public void shouldEmitEmptyStringIfRecordTagHasNoIdAttribute() {
		genericXmlHandler.startElement("", "record", "record", attributes);

		verify(receiver).startRecord("");
	}

	@Test
	public void shouldEmitValueOfIdAttribute() {
		attributes.addAttribute("", "id", "id", "CDATA", "theRecordID");
		genericXmlHandler.startElement("", "record", "record", attributes);

		verify(receiver).startRecord("theRecordID");
	}

	@Test
	public void shouldEmitAttributesOnRecordElementAsLiterals() {
		attributes.addAttribute("", "attr", "attr", "CDATA", "attr-value");
		genericXmlHandler.startElement("", "record", "record", attributes);

		final InOrder ordered = inOrder(receiver);
		ordered.verify(receiver).startRecord("");
		ordered.verify(receiver).literal("attr", "attr-value");
	}

	@Test
	public void shouldEmitElementsAsStartAndEndEntityEvents() {
		genericXmlHandler.startElement("", "record", "record", attributes);
		genericXmlHandler.startElement("", "entity", "entity", attributes);
		genericXmlHandler.endElement("", "entity", "entity");

		final InOrder ordered = inOrder(receiver);
		ordered.verify(receiver).startEntity("entity");
		ordered.verify(receiver).endEntity();
	}

	@Test
	public void shouldEmitAttributesOnEntityElementAsLiterals() {
		genericXmlHandler.startElement("", "record", "record", attributes);
		attributes.addAttribute("", "attr", "attr", "CDATA", "attr-value");
		genericXmlHandler.startElement("", "entity", "entity", attributes);

		final InOrder ordered = inOrder(receiver);
		ordered.verify(receiver).startEntity("entity");
		ordered.verify(receiver).literal("attr", "attr-value");
	}

	@Test
	public void shouldEmitPCDataAsALiteralNamedValue() {
		final char[] charData = "char-data".toCharArray();
		genericXmlHandler.startElement("", "record", "record", attributes);
		genericXmlHandler.startElement("", "entity", "entity", attributes);
		genericXmlHandler.characters(charData, 0, charData.length);
		genericXmlHandler.endElement("", "entity", "entity");

		final InOrder ordered = inOrder(receiver);
		ordered.verify(receiver).startEntity("entity");
		ordered.verify(receiver).literal("value", "char-data");
	}

}


text:
package org.plasma.provisioning.xsd;

import java.util.List;
import java.util.UUID;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.plasma.metamodel.Alias;
import org.plasma.metamodel.Body;
import org.plasma.metamodel.Class;
import org.plasma.metamodel.ClassRef;
import org.plasma.metamodel.DataTypeRef;
import org.plasma.metamodel.Documentation;
import org.plasma.metamodel.DocumentationType;
import org.plasma.metamodel.Enumeration;
import org.plasma.metamodel.EnumerationConstraint;
import org.plasma.metamodel.EnumerationRef;
import org.plasma.metamodel.Key;
import org.plasma.metamodel.KeyType;
import org.plasma.metamodel.Model;
import org.plasma.metamodel.Package;
import org.plasma.metamodel.Property;
import org.plasma.metamodel.Sort;
import org.plasma.metamodel.ValueConstraint;
import org.plasma.metamodel.VisibilityType;
import org.plasma.metamodel.XmlNodeType;
import org.plasma.metamodel.XmlProperty;
import org.plasma.runtime.PlasmaRuntime;
import org.plasma.xml.schema.Annotated;
import org.plasma.xml.schema.Attribute;
import org.plasma.xml.schema.ComplexType;
import org.plasma.xml.schema.Element;
import org.plasma.xml.schema.ExplicitGroup;
import org.plasma.xml.schema.ExtensionType;
import org.plasma.xml.schema.Facet;
import org.plasma.xml.schema.LocalElement;
import org.plasma.xml.schema.LocalSimpleType;
import org.plasma.xml.schema.Restriction;
import org.plasma.xml.schema.Schema;
import org.plasma.xml.schema.SchemaConverter;
import org.plasma.xml.schema.SchemaUtil;
import org.plasma.xml.schema.SimpleType;
import org.plasma.xml.sdox.SDOXConstants;

public class SDOXSchemaConverter extends ConverterSupport implements SchemaConverter {
  private static Log log = LogFactory.getLog(SDOXSchemaConverter.class);

  private QName appNamespaceQName;
  private EnumerationAssembler enumerationAssembler;
  private ConstraintAssembler constraintAssembler;

  public SDOXSchemaConverter(Schema schema, String destNamespaceURI, String destNamespacePrefix) {
    super(schema, destNamespaceURI, destNamespacePrefix);
    enumerationAssembler = new EnumerationAssembler(this, destNamespaceURI, destNamespacePrefix);
    constraintAssembler = new ConstraintAssembler(this, destNamespaceURI, destNamespacePrefix);
  }

  @SuppressWarnings("unchecked")
  public Model buildModel() {
    Model model = new Model();
    model.setName(schema.getId());
    model.setId(UUID.randomUUID().toString());
    model.setUri(this.destNamespaceURI);

    this.appNamespaceQName = findOpenAttributeQNameByValue(schema.getTargetNamespace(), schema);

    // process top-level complex types (process attributes/properties on another
    // pass)
    for (Annotated annotated : schema.getSimpleTypesAndComplexTypesAndGroups()) {
      if (annotated instanceof ComplexType) {
        ComplexType complexType = (ComplexType) annotated;
        if (complexType.getName().equals(SchemaUtil.getSerializationBaseTypeName()))
          continue; // skip the serialization base type
        this.complexTypeMap.put(complexType.getName(), complexType);
        Class cls = buildClass(model, complexType);
        this.classQualifiedNameMap.put(destNamespaceURI + "#" + cls.getName(), cls);
      } else if (annotated instanceof SimpleType) {
        SimpleType simpleType = (SimpleType) annotated;
        this.simpleTypeMap.put(simpleType.getName(), simpleType);
      } else if (annotated instanceof Element) {
        // ignore top level elements on first pass to first load entier set of
        // types
      } else
        log.warn("unknown annotated class, " + annotated.getClass().getName());
    }

    // look at top level elements
    for (Annotated annotated : schema.getSimpleTypesAndComplexTypesAndGroups()) {
      if (annotated instanceof Element) {
        Element element = (Element) annotated;
        if (element.getName().equals(SchemaUtil.getSerializationBaseTypeName()))
          continue; // skip the serialization base type
        ComplexType complexType = this.complexTypeMap.get(element.getName());
        if (complexType == null)
          throw new IllegalStateException("found top-level Element '" + element.getName()
              + "' but expected top-level "
              + "ComplexType with the same name (XML Schema re-use best practice)");
      }
    }

    for (Class cls : this.classQualifiedNameMap.values()) {
      String localName = cls.getName();
      if (cls.getAlias() != null && cls.getAlias().getLocalName() != null)
        localName = cls.getAlias().getLocalName();
      ComplexType complexType = this.complexTypeMap.get(localName);

      List<Annotated> annotatedList = null;
      if (complexType.getComplexContent() == null) { // no base type
        annotatedList = complexType.getAttributesAndAttributeGroups();
      } else {
        annotatedList = complexType.getComplexContent().getExtension()
            .getAttributesAndAttributeGroups();
      }

      for (Annotated annot : annotatedList) {
        if (annot instanceof Attribute) {
          Attribute attribute = (Attribute) annot;
          Property property = buildDatatypeProperty(complexType, attribute);
          cls.getProperties().add(property);
        } else
          throw new IllegalStateException("unexpected ComplexType child class, "
              + annot.getClass().getName());
      }

      ExplicitGroup sequence = null;
      if (complexType.getComplexContent() == null) { // no base type
        sequence = complexType.getSequence();
      } else {
        sequence = complexType.getComplexContent().getExtension().getSequence();
      }

      if (sequence != null)
        for (int i = 0; i < sequence.getElementsAndGroupsAndAlls().size(); i++) {
          Object obj = sequence.getElementsAndGroupsAndAlls().get(i);
          if (obj instanceof JAXBElement) {
            JAXBElement element = (JAXBElement) obj;
            if (element.getValue() instanceof LocalElement) {
              LocalElement localElement = (LocalElement) element.getValue();
              Property property = buildProperty(complexType, localElement, i);
              cls.getProperties().add(property);
            } else
              throw new IllegalStateException("unexpected JAXBElement value class, "
                  + element.getValue().getClass().getName());
          } else
            throw new IllegalStateException("unexpected sequence child class, "
                + obj.getClass().getName());
        }
    }

    // add derived target properties
    for (Class cls : this.classQualifiedNameMap.values()) {
      Property[] props = new Property[cls.getProperties().size()];
      cls.getProperties().toArray(props); // avoid concurrent mods for recursive
                                          // relationships
      for (Property prop : props) {
        if (prop.getType() instanceof DataTypeRef)
          continue;
        ClassRef classRef = (ClassRef) prop.getType();
        String qualifiedName = classRef.getUri() + "#" + classRef.getName();
        Class targetClass = this.classQualifiedNameMap.get(qualifiedName);
        if (targetClass == null)
          throw new IllegalStateException("no class definition found for qualified name '"
              + qualifiedName + "'");
        Property targetProperty = null;
        Property[] pdefs2 = new Property[targetClass.getProperties().size()];
        targetClass.getProperties().toArray(pdefs2);
        for (Property pdef2 : pdefs2) {
          if (pdef2.getName().equals(prop.getOpposite())) {
            targetProperty = pdef2;
            break;
          }
        }
        if (targetProperty == null) {
          if (prop.getOpposite() != null) {
            targetProperty = createDerivedPropertyOpposite(cls, prop);
            targetClass.getProperties().add(targetProperty);
          }
        }
      }
    }

    for (SimpleType simpleType : this.simpleTypeMap.values()) {
      Enumeration enm = this.enumerationAssembler.buildEnumeration(simpleType);
      model.getEnumerations().add(enm);
    }

    return model;
  }

  private Class buildClass(Package pkg, ComplexType complexType) {
    Class clss = new Class();
    pkg.getClazzs().add(clss);
    clss.setId(UUID.randomUUID().toString());
    clss.setUri(this.destNamespaceURI); // FIXME - what if we collect multiple
                                        // URI's in the query
    Alias alias = new Alias();
    clss.setAlias(alias);
    alias.setLocalName(complexType.getName()); // because XML schema
                                               // "projection" names could
                                               // differ

    String name = getSDOXValue(complexType, SDOXConstants.LOCAL_NAME_NAME);
    clss.setName(name); // actual SDO type name stored as sdox name
    String physicalNameAlias = findSDOXValue(complexType, SDOXConstants.LOCAL_NAME_ALIAS_NAME);
    if (physicalNameAlias != null)
      alias.setPhysicalName(physicalNameAlias); // Note: SDOX only allows one
                                                // alias name, hence we expect
                                                // PhysicalName

    Documentation documentation = createDocumentation(DocumentationType.DEFINITION,
        getDocumentationContent(complexType));
    clss.getDocumentations().add(documentation);

    if (complexType.getComplexContent() != null) { // has a base type
      ExtensionType baseType = complexType.getComplexContent().getExtension();
      QName base = baseType.getBase();
      if (!base.getLocalPart().equals(SchemaUtil.getSerializationBaseTypeName())) {
        ClassRef baseRef = new ClassRef();
        baseRef.setName(base.getLocalPart());
        baseRef.setUri(this.destNamespaceURI);
        clss.getSuperClasses().add(baseRef);
      }
    }

    return clss;
  }

  private Property buildProperty(ComplexType complexType, LocalElement element, int sequenceNum) {
    Property property = new Property();
    property.setId(UUID.randomUUID().toString());
    Alias alias = new Alias();
    property.setAlias(alias);
    alias.setLocalName(element.getName()); // because XML schema "projection"
                                           // names could differ
    QName nameQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, SDOXConstants.LOCAL_NAME_NAME,
        SDOXConstants.SDOX_NAMESPACE_PREFIX);
    String name = getOpenAttributeValue(nameQName, element);
    property.setName(name); // actual SDO type name stored as sdox name

    XmlProperty xmlProp = new XmlProperty();
    xmlProp.setNodeType(XmlNodeType.ELEMENT);
    property.setXmlProperty(xmlProp);

    Documentation documentation = createDocumentation(DocumentationType.DEFINITION,
        getDocumentationContent(element));
    property.getDocumentations().add(documentation);

    property.setVisibility(VisibilityType.PUBLIC);

    if ("1".equals(String.valueOf(element.getMinOccurs())))
      property.setNullable(false);

    QName aliasQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
        SDOXConstants.LOCAL_NAME_ALIAS_NAME, SDOXConstants.SDOX_NAMESPACE_PREFIX);
    String physicalNameAlias = findOpenAttributeValue(aliasQName, element);
    if (physicalNameAlias != null)
      alias.setPhysicalName(physicalNameAlias);
    else if (!"unbounded".equals(element.getMaxOccurs()))
      log.warn("expected SDOX '" + SDOXConstants.LOCAL_NAME_ALIAS_NAME
          + "' attribute for local Element '" + element.getName() + "' for ComplexType '"
          + complexType.getName() + "'");

    QName manyQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, SDOXConstants.LOCAL_NAME_MANY,
        SDOXConstants.SDOX_NAMESPACE_PREFIX);
    Boolean many = new Boolean(getOpenAttributeValue(manyQName, element));
    if (many.booleanValue())
      property.setMany(true);
    else
      property.setMany(false);

    // is key
    // FIXME: is there not a key-type SDOX attribute??
    QName keyQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, SDOXConstants.LOCAL_NAME_KEY,
        SDOXConstants.SDOX_NAMESPACE_PREFIX);
    Boolean isKey = new Boolean(findOpenAttributeValue(keyQName, element));
    if (isKey.booleanValue()) {
      property.setVisibility(VisibilityType.PRIVATE);
      Key key = new Key();
      key.setType(KeyType.PRIMARY);
      property.setKey(key);
    }

    QName typeQName = element.getType();
    // if a reference to another entity
    if (typeQName.getPrefix() == null
        || (appNamespaceQName != null && typeQName.getPrefix().equals(
            this.appNamespaceQName.getPrefix()))) {
      QName oppositeQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
          SDOXConstants.LOCAL_NAME_OPPOSITE_PROPERTY, SDOXConstants.SDOX_NAMESPACE_PREFIX);
      String oppositeName = findOpenAttributeValue(oppositeQName, element);
      if (oppositeName != null)
        property.setOpposite(oppositeName);
      QName datatypeQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
          SDOXConstants.LOCAL_NAME_DATATYPE, SDOXConstants.SDOX_NAMESPACE_PREFIX);
      Class targetDef = this.classQualifiedNameMap
          .get(getOpenAttributeValue(datatypeQName, element));
      if (targetDef != null) {
        ClassRef targetClassRef = new ClassRef();
        targetClassRef.setName(targetDef.getName());
        targetClassRef.setUri(targetDef.getUri());
        property.setType(targetClassRef);
        property.setContainment(true);
      } else {
        throw new IllegalStateException("could not find target class from, " + datatypeQName);
      }
    } else { // datatype .
      QName datatypeQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
          SDOXConstants.LOCAL_NAME_DATATYPE, SDOXConstants.SDOX_NAMESPACE_PREFIX);

      DataTypeRef dataTypeRef = new DataTypeRef();
      dataTypeRef.setName(getOpenAttributeValue(datatypeQName, element));
      dataTypeRef.setUri(PlasmaRuntime.getInstance().getSDODataTypesNamespace().getUri());
      property.setType(dataTypeRef);
    }

    QName readonlyQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
        SDOXConstants.LOCAL_NAME_READ_ONLY, SDOXConstants.SDOX_NAMESPACE_PREFIX);
    Boolean isReadonly = new Boolean(getOpenAttributeValue(readonlyQName, element));
    property.setReadOnly(isReadonly);

    // FIXME; add isSequence and isUnique and maxlength added to plasma specific
    // XML annotation ??
    // Integer maxLength =
    // (Integer)property.get(PlasmaProperty.INSTANCE_PROPERTY_INT_MAXLENGTH);
    // if (maxLength != null && maxLength.intValue() > 0)
    // pdef.setMaxLength(maxLength.intValue());
    if (sequenceNum > -1) {
      Sort seq = new Sort();
      seq.setKey(String.valueOf(sequenceNum));
      property.setSort(seq);
    }

    return property;
  }

  private Property createDerivedPropertyOpposite(Class clss, Property sourceProperty) {
    Property targetProperty = new Property();
    targetProperty.setId(UUID.randomUUID().toString());
    targetProperty.setName(sourceProperty.getOpposite()); // actual SDO type
                                                          // name stored as sdox
                                                          // name
    Documentation documentation = createDocumentation(DocumentationType.DEFINITION,
        "private derived opposite for, " + clss.getUri() + "#" + clss.getName() + "."
            + sourceProperty.getName());
    targetProperty.getDocumentations().add(documentation);
    targetProperty.setVisibility(VisibilityType.PRIVATE);

    targetProperty.setNullable(true);
    targetProperty.setMany(true);

    targetProperty.setDerived(true);
    targetProperty.setContainment(false);

    targetProperty.setOpposite(sourceProperty.getName());

    ClassRef targetClassRef = new ClassRef();
    targetClassRef.setName(clss.getName());
    targetClassRef.setUri(clss.getUri());
    targetProperty.setType(targetClassRef);

    return targetProperty;
  }

  /**
   * Creates non-reference property definitions.
   *
   * @param complexType
   *          the Schema Complex Type
   * @param attribute
   *          the Schema Attribute
   * @return the property definition
   */
  private Property buildDatatypeProperty(ComplexType complexType, Attribute attribute) {
    Property property = new Property();
    property.setId(UUID.randomUUID().toString());
    // set property names and aliases
    Alias alias = new Alias();
    property.setAlias(alias);
    alias.setLocalName(attribute.getName()); // because XML schema "projection"
                                             // names could differ
    QName nameQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, SDOXConstants.LOCAL_NAME_NAME,
        SDOXConstants.SDOX_NAMESPACE_PREFIX);
    String name = getOpenAttributeValue(nameQName, attribute);
    property.setName(name); // actual SDO type name stored as sdox name
    QName aliasQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
        SDOXConstants.LOCAL_NAME_ALIAS_NAME, SDOXConstants.SDOX_NAMESPACE_PREFIX);
    String physicalNameAlias = getOpenAttributeValue(aliasQName, attribute);
    alias.setPhysicalName(physicalNameAlias);

    XmlProperty xmlProp = new XmlProperty();
    xmlProp.setNodeType(XmlNodeType.ATTRIBUTE);
    property.setXmlProperty(xmlProp);

    Documentation documentation = new Documentation();
    documentation.setType(DocumentationType.DEFINITION);
    Body body = new Body();
    body.setValue(getDocumentationContent(attribute));
    documentation.setBody(body);
    property.getDocumentations().add(documentation);

    property.setVisibility(VisibilityType.PUBLIC); // FIXME

    // nullable
    if ("required".equals(attribute.getUse()))
      property.setNullable(false);
    else
      property.setNullable(true);

    // multiplicity
    QName manyQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, SDOXConstants.LOCAL_NAME_MANY,
        SDOXConstants.SDOX_NAMESPACE_PREFIX);
    Boolean many = new Boolean(getOpenAttributeValue(manyQName, attribute));
    if (many.booleanValue())
      property.setMany(true);
    else
      property.setMany(false);

    // datatype
    QName datatypeQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
        SDOXConstants.LOCAL_NAME_DATATYPE, SDOXConstants.SDOX_NAMESPACE_PREFIX);

    DataTypeRef dataTypeRef = new DataTypeRef();
    dataTypeRef.setName(getOpenAttributeValue(datatypeQName, attribute));
    dataTypeRef.setUri(PlasmaRuntime.getInstance().getSDODataTypesNamespace().getUri());
    property.setType(dataTypeRef);

    // is key
    QName keyQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI, SDOXConstants.LOCAL_NAME_KEY,
        SDOXConstants.SDOX_NAMESPACE_PREFIX);
    Boolean isKey = new Boolean(findOpenAttributeValue(keyQName, attribute));
    if (isKey.booleanValue()) {

      QName keyTypeQName = new QName(SDOXConstants.SDOX_NAMESPACE_URI,
          SDOXConstants.LOCAL_NAME_KEY_TYPE, SDOXConstants.SDOX_NAMESPACE_PREFIX);
      String keyType = findOpenAttributeValue(keyTypeQName, attribute);

      property.setVisibility(VisibilityType.PRIVATE); // FIXME: really
      Key key = new Key();
      key.setType(KeyType.valueOf(keyType.toUpperCase()));
      property.setKey(key);
    }

    QName typeQName = attribute.getType();
    if (typeQName != null) { // if local restriction will not have a simple type
      if (typeQName.getPrefix() == null
          || (appNamespaceQName != null && typeQName.getPrefix().equals(
              this.appNamespaceQName.getPrefix()))) {
        SimpleType simpleType = this.simpleTypeMap.get(typeQName.getLocalPart());

        EnumerationConstraint constraint = new EnumerationConstraint();
        EnumerationRef enumRef = new EnumerationRef();
        enumRef.setName(simpleType.getName());
        enumRef.setUri(this.destNamespaceURI);
        constraint.setValue(enumRef);
        property.setEnumerationConstraint(constraint);
      }
    } else {
      LocalSimpleType lst = attribute.getSimpleType();
      Restriction rest = lst.getRestriction();
      ValueConstraint constraint = this.constraintAssembler.buildValueConstraint(rest);
      property.setValueConstraint(constraint);
    }
    return property;
  }

  @SuppressWarnings("unchecked")
  private JAXBElement<Facet> findFacet(String name, List<Object> list) {
    for (Object obj : list) {
      if (obj instanceof JAXBElement<?>) {
        JAXBElement<Facet> facet = (JAXBElement<Facet>) obj;
        if (facet.getName().getLocalPart().equals(name))
          return facet;
      }
    }
    return null;
  }

}


text:
'use strict';

/**
 * rename_collection_dbname_chain.js
 *
 * Creates a collection and then repeatedly executes the renameCollection
 * command against it, specifying a different database name in the namespace.
 * The previous "to" namespace is used as the next "from" namespace.
 */
load('jstests/concurrency/fsm_workload_helpers/drop_utils.js');  // for dropDatabases

var $config = (function() {

    var data = {
        // Use the workload name as a prefix for the collection name,
        // since the workload name is assumed to be unique.
        prefix: 'rename_collection_dbname_chain'
    };

    var states = (function() {

        function uniqueDBName(prefix, tid, num) {
            return prefix + tid + '_' + num;
        }

        function init(db, collName) {
            this.fromDBName = db.getName() + uniqueDBName(this.prefix, this.tid, 0);
            this.num = 1;
            var fromDB = db.getSiblingDB(this.fromDBName);
            assertAlways.commandWorked(fromDB.createCollection(collName));
        }

        function rename(db, collName) {
            var toDBName = db.getName() + uniqueDBName(this.prefix, this.tid, this.num++);
            var renameCommand = {
                renameCollection: this.fromDBName + '.' + collName,
                to: toDBName + '.' + collName,
                dropTarget: false
            };

            assertAlways.commandWorked(db.adminCommand(renameCommand));

            // Remove any files associated with the "from" namespace
            // to avoid having too many files open
            var res = db.getSiblingDB(this.fromDBName).dropDatabase();
            assertAlways.commandWorked(res);
            assertAlways.eq(this.fromDBName, res.dropped);

            this.fromDBName = toDBName;
        }

        return {init: init, rename: rename};

    })();

    var transitions = {init: {rename: 1}, rename: {rename: 1}};

    function teardown(db, collName, cluster) {
        var pattern = new RegExp('^' + db.getName() + this.prefix + '\\d+_\\d+$');
        dropDatabases(db, pattern);
    }

    return {
        threadCount: 10,
        // We only run a few iterations to reduce the amount of data cumulatively
        // written to disk by mmapv1. For example, setting 10 threads and 5
        // iterations causes this workload to write at least 32MB (.ns and .0 files)
        // * 10 threads * 5 iterations worth of data to disk, which can be slow on
        // test hosts.
        iterations: 5,
        data: data,
        states: states,
        transitions: transitions,
        teardown: teardown
    };

})();


text:
from fairseq.data import data_utils

from . import BaseWrapperDataset

class PadDataset(BaseWrapperDataset):
    def __init__(self, dataset, pad_idx, left_pad, pad_length=None):
        super().__init__(dataset)
        self.pad_idx = pad_idx
        self.left_pad = left_pad
        self.pad_length = pad_length

    def collater(self, samples):
        return data_utils.collate_tokens(
            samples, self.pad_idx, left_pad=self.left_pad, pad_to_length=self.pad_length
        )

class LeftPadDataset(PadDataset):
    def __init__(self, dataset, pad_idx):
        super().__init__(dataset, pad_idx, left_pad=True)

class RightPadDataset(PadDataset):
    def __init__(self, dataset, pad_idx):
        super().__init__(dataset, pad_idx, left_pad=False)


text:
module Alf
  module Lang
    module Parser
      class Lispy
        include Parser
        include Functional
        include Predicates

        def initialize(helpers = [], connection = nil)
          @connection = connection
          @extensions = helpers
          helpers.each do |helper|
            helper.send(:extend_object, self)
          end
        end
        attr_reader :connection

        def connection!
          connection.tap{|c|
            ::Kernel.raise(UnboundError, "#{self} not bound") unless c
          }
        end

        def parse(expr = nil, path = nil, line = nil, &block)
          if (expr && block) || (expr.nil? and block.nil?)
            raise ArgumentError, "Either `expr` or `block` should be specified"
          end
          expr = evaluate(expr, path, line, &block) if block or expr.is_a?(String)
          expr = __send__(expr)                     if expr.is_a?(Symbol)
          expr
        end

        def to_s
          "Lispy(#{@extensions.map(&:name).compact.join(',')})"
        end

        def inspect
          "Lispy(#{@extensions.inspect})"
        end

      private

        def evaluate(expr = nil, path=nil, line=nil, &bl)
          return instance_exec(&bl) if bl
          instance_eval(expr, *[path, line].compact.map(&:to_s))
        end

      public

        # Resolve DUM and DEE in ruby 1.9.2 context
        def self.const_missing(name)
          case name.to_s
          when 'DEE' then ::Alf::Relation::DEE
          when 'DUM' then ::Alf::Relation::DUM
          else
            super
          end
        end

      end # class Lispy
    end # module Parser
  end # module Lang
end # module Alf