text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001package org.slf4j.impl;
002
003import java.lang.reflect.Method;
004
005import org.slf4j.helpers.Util;
006
007public class VersionUtil {
008        static final int MINIMAL_VERSION = 5;
009
010        static public int getJavaMajorVersion() {
011                String javaVersionString = Util.safeGetSystemProperty("java.version");
012                return getJavaMajorVersion(javaVersionString);
013        }
014
015        static int getJavaMajorVersion(String versionString) {
016                if (versionString == null)
017                        return MINIMAL_VERSION;
018                if (versionString.startsWith("1.")) {
019                        return versionString.charAt(2) - '0';
020                } else {
021                        // we running under Java 9 or later
022                        try {
023                                Method versionMethod = Runtime.class.getMethod("version");
024                                Object versionObj = versionMethod.invoke(null);
025                                Method majorMethod = versionObj.getClass().getMethod("major");
026                                Integer resultInteger = (Integer) majorMethod.invoke(versionObj);
027                                return resultInteger.intValue();
028                        } catch (Exception e) {
029                                return MINIMAL_VERSION;
030                        }
031                }
032        }
033}

redpajama_set_name: RedPajamaGithub


text:
require 'fog/core/model'

module Fog
  module Zerigo
    class DNS

      class Record < Fog::Model

        identity :id

        attribute :created_at,  :aliases => 'created-at'
        attribute :ip,          :aliases => 'data'
        attribute :domain,      :aliases => 'fqdn'
        attribute :name,        :aliases => 'hostname'
        attribute :description, :aliases => 'notes'
        attribute :priority
        attribute :ttl
        attribute :type,        :aliases => 'host-type'
        attribute :updated_at,  :aliases => 'updated-at'
        attribute :zone_id,     :aliases => 'zone-id'

        def initialize(attributes={})
          self.ttl    ||= 3600
          super
        end

        def destroy
          requires :identity
          connection.delete_host(identity)
          true
        end

        def zone
          @zone
        end

        def save
          requires :zone, :type, :ip
          options = {}
          options[:hostname]  = name if name
          options[:notes]     = description if description
          options[:priority]  = priority if priority
          options[:ttl]       = ttl if ttl
          data = unless identity
            connection.create_host(@zone.id, type, ip, options)
          else
            options[:host_type] = type
            options[:data]      = data
            connection.update_host(identity, options)
          end
          merge_attributes(data.body)
          true
        end

        private

        def zone=(new_zone)
          @zone = new_zone
        end

      end

    end
  end
end


text:
@interface SomeModelObject : NSObject <AGBExpiringCacheItem>

@property (nonatomic, strong) NSDate *expiringCacheItemDate;

@end

@implementation SomeModelObject

@end

@interface AGBViewController ()

@property (nonatomic, strong) AGBExpiringCache *expiringCache;

@end

@implementation AGBViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.expiringCache = [[AGBExpiringCache alloc] init];

    // Expire objects after 60 seconds
    self.expiringCache.expiryTimeInterval = 60;
}

- (IBAction)tryItPressed:(UIButton *)sender {
//
// <--- Set a breakpoint here
//

    SomeModelObject *modelObject = [[SomeModelObject alloc] init];

    static NSString *exampleKey = @"Example Object";

    // Add the object to the cache…
    [self.expiringCache setObject:modelObject forKey:exampleKey];

    // Get the object…
    SomeModelObject *myObject = [self.expiringCache objectForKey:exampleKey];

    // Got it!
    NSLog(@"%@", myObject);

    // Simulate the object being older than 60 seconds
    myObject.expiringCacheItemDate = [[NSDate date] dateByAddingTimeInterval:-100];

    // Now try getting it again…
    SomeModelObject *oldObject = [self.expiringCache objectForKey:exampleKey];

    // It's gone now!
    NSLog(@"%@", oldObject);
}
@end


text:
namespace dotless.Core.Test.Specs.Functions
{
    using NUnit.Framework;

    public class HexFixture : SpecFixtureBase
    {
        [Test]
        public void TestHexInfo()
        {
            var info1 = "hex(number) is not supported by less.js, so this will work but not compile with other less implementations.";

            AssertExpressionLogMessage(info1, "hex(0)");
        }

        [Test]
        public void TestHex()
        {
            AssertExpression("00", "hex(0)");
            AssertExpression("99", "hex(153)");
            AssertExpression("F0", "hex(240)");
            AssertExpression("FF", "hex(255)");
        }

        [Test]
        public void ValuesBelow_0_AreInterpretedAs_0()
        {
            AssertExpression("00", "hex(-1)");
        }

        [Test]
        public void ValuesAbove_255_AreInterpretedAs_FF()
        {
            AssertExpression("FF", "hex(999)");
        }

        [Test]
        public void ThrowsExpressionError_WhenNumberPassedHasUnit()
        {
            AssertExpressionError("Expected unitless number in function 'hex', found 5px", 4, "hex(5px)");
        }
    }
}


text:
/*
 * SELinux support for the XFRM LSM hooks
 *
 * Author : Trent Jaeger, <jaegert@us.ibm.com>
 * Updated : Venkat Yekkirala, <vyekkirala@TrustedCS.com>
 */
#ifndef _SELINUX_XFRM_H_
#define _SELINUX_XFRM_H_

int selinux_xfrm_policy_alloc(struct xfrm_policy *xp,
		struct xfrm_user_sec_ctx *sec_ctx);
int selinux_xfrm_policy_clone(struct xfrm_policy *old, struct xfrm_policy *new);
void selinux_xfrm_policy_free(struct xfrm_policy *xp);
int selinux_xfrm_policy_delete(struct xfrm_policy *xp);
int selinux_xfrm_state_alloc(struct xfrm_state *x,
	struct xfrm_user_sec_ctx *sec_ctx, u32 secid);
void selinux_xfrm_state_free(struct xfrm_state *x);
int selinux_xfrm_state_delete(struct xfrm_state *x);
int selinux_xfrm_policy_lookup(struct xfrm_policy *xp, u32 fl_secid, u8 dir);
int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x,
			struct xfrm_policy *xp, struct flowi *fl);

/*
 * Extract the security blob from the sock (it's actually on the socket)
 */
static inline struct inode_security_struct *get_sock_isec(struct sock *sk)
{
	if (!sk->sk_socket)
		return NULL;

	return SOCK_INODE(sk->sk_socket)->i_security;
}

#ifdef CONFIG_SECURITY_NETWORK_XFRM
int selinux_xfrm_sock_rcv_skb(u32 sid, struct sk_buff *skb,
			struct avc_audit_data *ad);
int selinux_xfrm_postroute_last(u32 isec_sid, struct sk_buff *skb,
			struct avc_audit_data *ad, u8 proto);
int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, int ckall);

static inline void selinux_xfrm_notify_policyload(void)
{
	atomic_inc(&flow_cache_genid);
}
#else
static inline int selinux_xfrm_sock_rcv_skb(u32 isec_sid, struct sk_buff *skb,
			struct avc_audit_data *ad)
{
	return 0;
}

static inline int selinux_xfrm_postroute_last(u32 isec_sid, struct sk_buff *skb,
			struct avc_audit_data *ad, u8 proto)
{
	return 0;
}

static inline int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, int ckall)
{
	*sid = SECSID_NULL;
	return 0;
}

static inline void selinux_xfrm_notify_policyload(void)
{
}
#endif

static inline void selinux_skb_xfrm_sid(struct sk_buff *skb, u32 *sid)
{
	int err = selinux_xfrm_decode_session(skb, sid, 0);
	BUG_ON(err);
}

#endif /* _SELINUX_XFRM_H_ */


text:
package org.apache.jsieve;

import org.apache.commons.logging.Log;
import org.apache.jsieve.exception.CommandException;
import org.apache.jsieve.exception.SyntaxException;

/**
 * Specifies the positional extent of an element within the script being
 * executed. In other words, this gives the line and column at which the elment
 * starts and at which it ends.
 */
public final class ScriptCoordinate {

    private final int startLineNumber;

    private final int startColumnNumber;

    private final int endLineNumber;

    private final int endColumnNumber;

    private Log log;

    public ScriptCoordinate(final int startLineNumber,
            final int startColumnNumber, final int endLineNumber,
            final int endColumnNumber) {
        super();
        this.startLineNumber = startLineNumber;
        this.startColumnNumber = startColumnNumber;
        this.endLineNumber = endLineNumber;
        this.endColumnNumber = endColumnNumber;
    }

    public Log getLog() {
        return log;
    }

    public void setLog(Log logger) {
        this.log = logger;
    }

    /**
     * Gets the number of the column where the elements ends.
     *
     * @return column number
     */
    public int getEndColumnNumber() {
        return endColumnNumber;
    }

    /**
     * Gets the number of the line where the element ends.
     *
     * @return line number
     */
    public int getEndLineNumber() {
        return endLineNumber;
    }

    /**
     * Gets the number of the column where the element start.
     *
     * @return column number
     */
    public int getStartColumnNumber() {
        return startColumnNumber;
    }

    /**
     * Gets the number of the line where the element starts.
     *
     * @return line number
     */
    public int getStartLineNumber() {
        return startLineNumber;
    }

    /**
     * Creates a syntax exception based on the given message containing details
     * of the script position. The message should end with a full stop.
     *
     * @param message
     *            CharSequence containing the base message, not
     *            null
     * @return SyntaxException with details of the script
     *         position appended to the message, not null
     */
    public SyntaxException syntaxException(CharSequence message) {
        if (log != null) {
            if (log.isWarnEnabled()) {
                log.warn(message);
            }
            logDiagnosticsInfo(log);
        }
        final String fullMessage = addStartLineAndColumn(message);
        return new SyntaxException(fullMessage);
    }

    /**
     * Creates a command exception based on the given message containing details
     * of the script position. The message should end with a full stop.
     *
     * @param message
     *            CharSequence containing the base message, not
     *            null
     * @return CommandException with details of the script
     *         position appended to the message, not null
     */
    public CommandException commandException(CharSequence message) {
        if (log != null) {
            if (log.isWarnEnabled()) {
                log.warn(message);
            }
            logDiagnosticsInfo(log);
        }
        final String fullMessage = addStartLineAndColumn(message);
        return new CommandException(fullMessage);
    }

    /**
     * Appends a standard position phrase to the given message. This message
     * should end with a full stop.
     *
     * @param message
     *            CharSequence message, not null
     * @return String containing the original message with
     *         positional phrase appended, not null
     */
    public String addStartLineAndColumn(CharSequence message) {
        final StringBuilder buffer;
        if (message instanceof StringBuilder) {
            buffer = (StringBuilder) message;
        } else {
            buffer = new StringBuilder(message.toString());
        }
        buffer.append(" Line ");
        buffer.append(startLineNumber);
        buffer.append(" column ");
        buffer.append(startColumnNumber);
        buffer.append(".");
        return buffer.toString();
    }

    /**
     * Logs diagnotic information about the script coordinate.
     *
     * @param logger
     *            Log, not null
     */
    public void logDiagnosticsInfo(Log logger) {
        if (logger.isInfoEnabled()) {
            logger.info("Expression starts line " + startLineNumber
                    + " column " + startColumnNumber);
            logger.info("Expression ends line " + endLineNumber + " column "
                    + endColumnNumber);
        }
    }

    /**
     * Logs diagnotic information about the script coordinate.
     *
     * @param logger
     *            Log, not null
     */
    public void debugDiagnostics(Log logger) {
        if (logger.isDebugEnabled()) {
            logger.debug("Expression starts line " + startLineNumber
                    + " column " + startColumnNumber);
            logger.debug("Expression ends line " + endLineNumber + " column "
                    + endColumnNumber);
        }
    }
}


text:
<?php

namespace Documents;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/** @ODM\Document */
class Account
{
    /** @ODM\Id */
    private $id;

    /** @ODM\Field */
    private $name;

    /** @ODM\ReferenceOne */
    protected $user;

    /** @ODM\ReferenceOne(storeAs="dbRef") */
    protected $userDbRef;

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setUser($user)
    {
        $this->user = $user;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function setUserDbRef($userDbRef)
    {
        $this->userDbRef = $userDbRef;
    }

    public function getUserDbRef()
    {
        return $this->userDbRef;
    }
}


text:
package com.thinkaurelius.titan.diskstorage.hbase;

import com.thinkaurelius.titan.HBaseStorageSetup;
import com.thinkaurelius.titan.diskstorage.BackendException;
import com.thinkaurelius.titan.diskstorage.IDAuthorityTest;
import com.thinkaurelius.titan.diskstorage.configuration.WriteConfiguration;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.KeyColumnValueStoreManager;

import org.apache.hadoop.hbase.util.VersionInfo;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;

import java.io.IOException;

public class HBaseIDAuthorityTest extends IDAuthorityTest {

    public HBaseIDAuthorityTest(WriteConfiguration baseConfig) {
        super(baseConfig);
    }

    @BeforeClass
    public static void startHBase() throws IOException {
        HBaseStorageSetup.startHBase();
    }

    @AfterClass
    public static void stopHBase() {
        // Workaround for https://issues.apache.org/jira/browse/HBASE-10312
        if (VersionInfo.getVersion().startsWith("0.96"))
            HBaseStorageSetup.killIfRunning();
    }

    public KeyColumnValueStoreManager openStorageManager() throws BackendException {
        return new HBaseStoreManager(HBaseStorageSetup.getHBaseConfiguration());
    }
}


text:
from django.db import models
from django.utils.translation import ugettext_lazy as _

class {{ model_name }}(models.Model):
    """
        {{ model_name }} model
    """
    name = models.CharField(_('Name'), max_length=200)
    slug = models.SlugField()
    pub_date = models.DateField(_('Date Published'))

    def __unicode__(self):
        return u'%s' % self.name


text:
var has = require('has')

module.exports = function (page) {
  var parts = Object.keys(page.versions || {}).sort().map(function (key) {
    return page.versions[key].map(function (href) {
      var grits = ''
      if (has(page.integrity, href) && page.integrity[href].length) {
        grits = 'integrity="' + esc(page.integrity[href].join(' ')) + '"'
      }
      return '<link rel="version" href="' + esc(href) + '"'
        + ' version="' + esc(key) + '"' + grits + '>'
    }).join('\n')
  })
  ;(page.latest || []).forEach(function (href) {
    parts.push('<link rel="latest-version" href="' + esc(href) + '">')
  })
  ;(page.predecessor || []).forEach(function (href) {
    parts.push('<link rel="predecessor-version" href="' + esc(href) + '">')
  })
  return parts.join('\n')
}

function esc (str) {
  return str.replace(/["'<>]/g, function (s) {
    return '&#x' + s.charCodeAt(0).toString(16) + ';'
  })
}


text:
#include <sstream>
#include <numeric>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <unordered_map>

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    template<typename action_t>
    void traversal(TreeNode* root, action_t action) {
        if (!root) return;

        action(root->val);
        traversal(root->left, action);
        traversal(root->right, action);
    }

    bool isUnivalTree(TreeNode* root) {
        int last = 0;
        bool has_last = false;
        bool univalue = true;

        traversal(root, [&](int val){
            if (has_last && last != val) univalue = false;
            last = val;
            has_last = true;
        });
        return univalue;
    }
};

int main(int argc, char *argv[]) {
    return 0;
}


text:
<?php

namespace Harp\MP\Test;

use Harp\MP\BelongsTo;
use Harp\Harp\Repo\LinkOne;
use Harp\Harp\Model\Models;

class BelongsToTest extends AbstractTestCase
{
    /**
     * @covers ::update
     */
    public function testUpdate()
    {
        $repo = Category::getRepo();
        $model1 = $this->getMock(__NAMESPACE__.'\Category', ['setPathAndUpdateDescendants']);
        $model2 = new Category(['id' => 6, 'path' => '1/4']);

        $models = new Models([$model2]);

        $model1
            ->expects($this->once())
            ->method('setPathAndUpdateDescendants')
            ->with('1/4/6')
            ->will($this->returnValue($models));

        $rel = new BelongsTo('test', $repo->getConfig(), $repo);

        $link = new LinkOne($model1, $rel, $model1);

        $result = $rel->update($link);

        $this->assertNull($result);

        $link->set($model2);

        $result = $rel->update($link);

        $this->assertSame($models, $result);
    }
}


text:
// Imports --------------------------------------------------------------------
module.exports = {

    Server: require('./server'),
    network: require('./network'),
    lib: require('./lib')

};


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using Passenger.Attributes;
using Passenger.CommandHandlers;
using Passenger.Drivers;
using Moq;
using NUnit.Framework;
using OpenQA.Selenium;

namespace Passenger.Test.Unit.CommandHandlers
{
    [TestFixture]
    public class ElementSelectionHandlerTests
    {
        private Mock<IDriverBindings> _mockDriver;
        private ElementSelectionHandler _handler;
        private PropertyInfo _someDivPropertyInfo;
        private IdAttribute _idAttribute;
        private List<DriverBindings.IHandle> _navHandlers;
        private List<string> _collection;

       [SetUp]
        public void Setup()
        {
            _someDivPropertyInfo = typeof (SelectionTestClass).GetProperty("SomeDiv");
            _idAttribute = _someDivPropertyInfo.GetCustomAttribute<IdAttribute>();
            _navHandlers = new List<DriverBindings.IHandle>();

            _mockDriver = new Mock<IDriverBindings>();
            _mockDriver.Setup(x => x.NavigationHandlers).Returns(_navHandlers);
            var cfg = new PassengerConfiguration { Driver = _mockDriver.Object };
            _handler = new ElementSelectionHandler(cfg);
        }

        [Test]
        public void SelectElement_AttributeNull_ReturnsNull()
        {
            var result =_handler.SelectElement(null, _someDivPropertyInfo);

            Assert.That(result, Is.Null);
        }

        [Test]
        public void SelectElement_PropertyInfoNull_ReturnsNull()
        {
            var result = _handler.SelectElement(_idAttribute, null);

            Assert.That(result, Is.Null);
        }

        [Test]
        public void SelectElement_NoTextValueProvidedByAttribute_PropertyNamePassedToAttributeHandler()
        {
            string namePassedIn = "";
            _navHandlers.Add(new DriverBindings.Handle<IdAttribute>((s, bindings) => { namePassedIn = s; return "empty"; }));

            _handler.SelectElement(_idAttribute, _someDivPropertyInfo);

            Assert.That(namePassedIn, Is.EqualTo("SomeDiv"));
        }

        [Test]
        public void SelectElement_NoHandlerAvailableForNavigationAttribute_ThrowsExceptionWithImportantInformationInMessage()
        {
            var ex =
                Assert.Throws<NavigationTypeNotSupportedException>(
                    () => _handler.SelectElement(_idAttribute, _someDivPropertyInfo));

            Assert.That(ex.Message, Does.Contain("IdAttribute"));
            Assert.That(ex.Message, Does.Contain("SomeDiv"));
        }

        [Test]
        public void SelectElement_TargetTypeIsACollection_CollectionReturned()
        {
            var stringsPi = typeof(SelectionTestClass).GetProperty("Strings");
            var idFromStrings = stringsPi.GetCustomAttribute<IdAttribute>();
            _collection = new List<string> {"1", "2", "3"};

            _navHandlers.Add(new DriverBindings.Handle<IdAttribute>((s, bindings) => _collection));

            var selected = _handler.SelectElement(idFromStrings, stringsPi);

            Assert.That(selected, Is.EqualTo(_collection));
        }

        [Test]
        public void SelectElement_TargetTypeIsACollectionOfIWebElements_CollectionReturned()
        {
            var divs = typeof(SelectionTestClass).GetProperty("ListOfSomeDiv");
            var idFromDivs = divs.GetCustomAttribute<IdAttribute>();
            var collectionOfWebElements = new List<IWebElement>();

            _navHandlers.Add(new DriverBindings.Handle<IdAttribute>((s, bindings) => collectionOfWebElements));

            var selected = _handler.SelectElement(idFromDivs, divs);

            Assert.That(selected, Is.EqualTo(collectionOfWebElements));
        }

        [Test]
        public void SelectElement_TargetTypeIsACollectionOfIWebElementsDriverReturnsAReadOnlyCollection_CollectionReturned()
        {
            var divs = typeof(SelectionTestClass).GetProperty("ListOfSomeDiv");
            var idFromDivs = divs.GetCustomAttribute<IdAttribute>();
            var collectionOfWebElements = new List<IWebElement>();
            var roCollectionOfWebElements = new ReadOnlyCollection<IWebElement>(collectionOfWebElements);

            _navHandlers.Add(new DriverBindings.Handle<IdAttribute>((s, bindings) => roCollectionOfWebElements));

            var selected = _handler.SelectElement(idFromDivs, divs);

            Assert.That(selected, Is.EqualTo(collectionOfWebElements));
        }

        [Test]
        public void SelectElement_TargetTypeIsASingleElementAndCollectionFound_FirstItemReturned()
        {
            var stringsPi = typeof(SelectionTestClass).GetProperty("String");
            var idFromStrings = stringsPi.GetCustomAttribute<IdAttribute>();
            _collection = new List<string> {"1", "2", "3"};

            _navHandlers.Add(new DriverBindings.Handle<IdAttribute>((s, bindings) => _collection));

            var selected = _handler.SelectElement(idFromStrings, stringsPi);

            Assert.That(selected, Is.EqualTo(_collection[0]));
        }

        public class SelectionTestClass
        {
            [Id]
            public virtual IWebElement SomeDiv { get; set; }

            [Id]
            public virtual List<string> Strings { get; set; }

            [Id]
            public virtual string String { get; set; }

            [Id]
            public virtual MyButton Button { get; set; }

            [Id]
            public virtual List<MyButton> Buttons { get; set; }

            [Id]
            public virtual MyButton[] ArrayOfButtons { get; set; }

            [Id]
            public virtual List<IWebElement> ListOfSomeDiv { get; set; }
        }

        public class MyButton : IPassengerElement
        {
            public IWebElement Inner { get; set; }
        }
    }
}


text:
package org.vudroid.core;

import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.net.Uri;
import android.util.Log;
import android.view.View;

import org.vudroid.core.codec.CodecContext;
import org.vudroid.core.codec.CodecDocument;
import org.vudroid.core.codec.CodecPage;
import org.vudroid.core.utils.PathFromUri;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DecodeServiceBase implements DecodeService
{
    private static final int PAGE_POOL_SIZE = 16;
    private final CodecContext codecContext;

    private View containerView;
    private CodecDocument document;
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    public static final String DECODE_SERVICE = "ViewDroidDecodeService";
    private final Map<Object, Future<?>> decodingFutures = new ConcurrentHashMap<Object, Future<?>>();
    private final HashMap<Integer, SoftReference<CodecPage>> pages = new HashMap<Integer, SoftReference<CodecPage>>();
    private ContentResolver contentResolver;
    private Queue<Integer> pageEvictionQueue = new LinkedList<Integer>();
    private boolean isRecycled;

    public DecodeServiceBase(CodecContext codecContext)
    {
        this.codecContext = codecContext;
    }

    public void setContentResolver(ContentResolver contentResolver)
    {
        this.contentResolver = contentResolver;
        codecContext.setContentResolver(contentResolver);
    }

    public void setContainerView(View containerView)
    {
        this.containerView = containerView;
    }

    public void open(Uri fileUri)
    {
        document = codecContext.openDocument(PathFromUri.retrieve(contentResolver, fileUri));
    }

    public void decodePage(Object decodeKey, int pageNum, final DecodeCallback decodeCallback, float zoom, RectF pageSliceBounds)
    {
        final DecodeTask decodeTask = new DecodeTask(pageNum, decodeCallback, zoom, decodeKey, pageSliceBounds);
        synchronized (decodingFutures)
        {
            if (isRecycled) {
                return;
            }
            final Future<?> future = executorService.submit(new Runnable()
            {
                public void run()
                {
                    try
                    {
                        Thread.currentThread().setPriority(Thread.NORM_PRIORITY-1);
                        performDecode(decodeTask);
                    }
                    catch (IOException e)
                    {
                        Log.e(DECODE_SERVICE, "Decode fail", e);
                    }
                }
            });
            final Future<?> removed = decodingFutures.put(decodeKey, future);
            if (removed != null)
            {
                removed.cancel(false);
            }
        }
    }

    public void stopDecoding(Object decodeKey)
    {
        final Future<?> future = decodingFutures.remove(decodeKey);
        if (future != null)
        {
            future.cancel(false);
        }
    }

    private void performDecode(DecodeTask currentDecodeTask)
            throws IOException
    {
        if (isTaskDead(currentDecodeTask))
        {
            Log.d(DECODE_SERVICE, "Skipping decode task for page " + currentDecodeTask.pageNumber);
            return;
        }
        Log.d(DECODE_SERVICE, "Starting decode of page: " + currentDecodeTask.pageNumber);
        CodecPage vuPage = getPage(currentDecodeTask.pageNumber);
        preloadNextPage(currentDecodeTask.pageNumber);

        if (isTaskDead(currentDecodeTask))
        {
            return;
        }
        Log.d(DECODE_SERVICE, "Start converting map to bitmap");
        float scale = calculateScale(vuPage) * currentDecodeTask.zoom;
        final Bitmap bitmap = vuPage.renderBitmap(getScaledWidth(currentDecodeTask, vuPage, scale), getScaledHeight(currentDecodeTask, vuPage, scale), currentDecodeTask.pageSliceBounds);
        Log.d(DECODE_SERVICE, "Converting map to bitmap finished");
        if (isTaskDead(currentDecodeTask))
        {
            bitmap.recycle();
            return;
        }
        finishDecoding(currentDecodeTask, bitmap);
    }

    private int getScaledHeight(DecodeTask currentDecodeTask, CodecPage vuPage, float scale)
    {
        return Math.round(getScaledHeight(vuPage, scale) * currentDecodeTask.pageSliceBounds.height());
    }

    private int getScaledWidth(DecodeTask currentDecodeTask, CodecPage vuPage, float scale)
    {
        return Math.round(getScaledWidth(vuPage, scale) * currentDecodeTask.pageSliceBounds.width());
    }

    private int getScaledHeight(CodecPage vuPage, float scale)
    {
        return (int) (scale * vuPage.getHeight());
    }

    private int getScaledWidth(CodecPage vuPage, float scale)
    {
        return (int) (scale * vuPage.getWidth());
    }

    private float calculateScale(CodecPage codecPage)
    {
        return 1.0f * getTargetWidth() / codecPage.getWidth();
    }

    private void finishDecoding(DecodeTask currentDecodeTask, Bitmap bitmap)
    {
        updateImage(currentDecodeTask, bitmap);
        stopDecoding(currentDecodeTask.pageNumber);
    }

    private void preloadNextPage(int pageNumber) throws IOException
    {
        final int nextPage = pageNumber + 1;
        if (nextPage >= getPageCount())
        {
            return;
        }
        getPage(nextPage);
    }

    public CodecPage getPage(int pageIndex)
    {
        if (!pages.containsKey(pageIndex) || pages.get(pageIndex).get() == null)
        {
            pages.put(pageIndex, new SoftReference<CodecPage>(document.getPage(pageIndex)));
            pageEvictionQueue.remove(pageIndex);
            pageEvictionQueue.offer(pageIndex);
            if (pageEvictionQueue.size() > PAGE_POOL_SIZE) {
                Integer evictedPageIndex = pageEvictionQueue.poll();
                CodecPage evictedPage = pages.remove(evictedPageIndex).get();
                if (evictedPage != null) {
                    evictedPage.recycle();
                }
            }
        }
        return pages.get(pageIndex).get();
    }

    @SuppressWarnings("unused")
	private void waitForDecode(CodecPage vuPage)
    {
        vuPage.waitForDecode();
    }

    private int getTargetWidth()
    {
        return containerView.getWidth();
    }

    public int getEffectivePagesWidth()
    {
        final CodecPage page = getPage(0);
        return getScaledWidth(page, calculateScale(page));
    }

    public int getEffectivePagesHeight()
    {
        final CodecPage page = getPage(0);
        return getScaledHeight(page, calculateScale(page));
    }

    public int getPageWidth(int pageIndex)
    {
        return getPage(pageIndex).getWidth();
    }

    public int getPageHeight(int pageIndex)
    {
        return getPage(pageIndex).getHeight();
    }

    private void updateImage(final DecodeTask currentDecodeTask, Bitmap bitmap)
    {
        currentDecodeTask.decodeCallback.decodeComplete(bitmap);
    }

    private boolean isTaskDead(DecodeTask currentDecodeTask)
    {
        synchronized (decodingFutures)
        {
            return !decodingFutures.containsKey(currentDecodeTask.decodeKey);
        }
    }

    public int getPageCount()
    {
        return document.getPageCount();
    }

    private class DecodeTask
    {
        private final Object decodeKey;
        private final int pageNumber;
        private final float zoom;
        private final DecodeCallback decodeCallback;
        private final RectF pageSliceBounds;

        private DecodeTask(int pageNumber, DecodeCallback decodeCallback, float zoom, Object decodeKey, RectF pageSliceBounds)
        {
            this.pageNumber = pageNumber;
            this.decodeCallback = decodeCallback;
            this.zoom = zoom;
            this.decodeKey = decodeKey;
            this.pageSliceBounds = pageSliceBounds;
        }
    }

    public void recycle() {
        synchronized (decodingFutures) {
            isRecycled = true;
        }
        for (Object key : decodingFutures.keySet()) {
            stopDecoding(key);
        }
        executorService.submit(new Runnable() {
            public void run() {
                for (SoftReference<CodecPage> codecPageSoftReference : pages.values()) {
                    CodecPage page = codecPageSoftReference.get();
                    if (page != null) {
                        page.recycle();
                    }
                }
                document.recycle();
                codecContext.recycle();
            }
        });
        executorService.shutdown();
    }
}


text:
import decimal

import sys
from functools import wraps
from . import testutils
from .testutils import unittest, ConnectingTestCase, decorate_all_tests

import psycopg2
from psycopg2.extensions import b

class TypesBasicTests(ConnectingTestCase):
    """Test that all type conversions are working."""

    def execute(self, *args):
        curs = self.conn.cursor()
        curs.execute(*args)
        return curs.fetchone()[0]

    def testQuoting(self):
        s = "Quote'this\\! ''ok?''"
        self.assertTrue(self.execute("SELECT %s AS foo", (s,)) == s,
                        "wrong quoting: " + s)

    def testUnicode(self):
        s = "Quote'this\\! ''ok?''"
        self.assertTrue(self.execute("SELECT %s AS foo", (s,)) == s,
                        "wrong unicode quoting: " + s)

    def testNumber(self):
        s = self.execute("SELECT %s AS foo", (1971,))
        self.assertTrue(s == 1971, "wrong integer quoting: " + str(s))
        s = self.execute("SELECT %s AS foo", (1971,))
        self.assertTrue(s == 1971, "wrong integer quoting: " + str(s))

    def testBoolean(self):
        x = self.execute("SELECT %s as foo", (False,))
        self.assertTrue(x is False)
        x = self.execute("SELECT %s as foo", (True,))
        self.assertTrue(x is True)

    def testDecimal(self):
        s = self.execute("SELECT %s AS foo", (decimal.Decimal("19.10"),))
        self.assertTrue(s - decimal.Decimal("19.10") == 0,
                        "wrong decimal quoting: " + str(s))
        s = self.execute("SELECT %s AS foo", (decimal.Decimal("NaN"),))
        self.assertTrue(str(s) == "NaN", "wrong decimal quoting: " + str(s))
        self.assertTrue(type(s) == decimal.Decimal, "wrong decimal conversion: " + repr(s))
        s = self.execute("SELECT %s AS foo", (decimal.Decimal("infinity"),))
        self.assertTrue(str(s) == "NaN", "wrong decimal quoting: " + str(s))
        self.assertTrue(type(s) == decimal.Decimal, "wrong decimal conversion: " + repr(s))
        s = self.execute("SELECT %s AS foo", (decimal.Decimal("-infinity"),))
        self.assertTrue(str(s) == "NaN", "wrong decimal quoting: " + str(s))
        self.assertTrue(type(s) == decimal.Decimal, "wrong decimal conversion: " + repr(s))

    def testFloatNan(self):
        try:
            float("nan")
        except ValueError:
            return self.skipTest("nan not available on this platform")

        s = self.execute("SELECT %s AS foo", (float("nan"),))
        self.assertTrue(str(s) == "nan", "wrong float quoting: " + str(s))
        self.assertTrue(type(s) == float, "wrong float conversion: " + repr(s))

    def testFloatInf(self):
        try:
            self.execute("select 'inf'::float")
        except psycopg2.DataError:
            return self.skipTest("inf::float not available on the server")
        except ValueError:
            return self.skipTest("inf not available on this platform")
        s = self.execute("SELECT %s AS foo", (float("inf"),))
        self.assertTrue(str(s) == "inf", "wrong float quoting: " + str(s))
        self.assertTrue(type(s) == float, "wrong float conversion: " + repr(s))

        s = self.execute("SELECT %s AS foo", (float("-inf"),))
        self.assertTrue(str(s) == "-inf", "wrong float quoting: " + str(s))

    def testBinary(self):
        if sys.version_info[0] < 3:
            s = ''.join([chr(x) for x in range(256)])
            b = psycopg2.Binary(s)
            buf = self.execute("SELECT %s::bytea AS foo", (b,))
            self.assertEqual(s, str(buf))
        else:
            s = bytes(list(range(256)))
            b = psycopg2.Binary(s)
            buf = self.execute("SELECT %s::bytea AS foo", (b,))
            self.assertEqual(s, buf.tobytes())

    def testBinaryNone(self):
        b = psycopg2.Binary(None)
        buf = self.execute("SELECT %s::bytea AS foo", (b,))
        self.assertEqual(buf, None)

    def testBinaryEmptyString(self):
        # test to make sure an empty Binary is converted to an empty string
        if sys.version_info[0] < 3:
            b = psycopg2.Binary('')
            self.assertEqual(str(b), "''::bytea")
        else:
            b = psycopg2.Binary(bytes([]))
            self.assertEqual(str(b), "''::bytea")

    def testBinaryRoundTrip(self):
        # test to make sure buffers returned by psycopg2 are
        # understood by execute:
        if sys.version_info[0] < 3:
            s = ''.join([chr(x) for x in range(256)])
            buf = self.execute("SELECT %s::bytea AS foo", (psycopg2.Binary(s),))
            buf2 = self.execute("SELECT %s::bytea AS foo", (buf,))
            self.assertEqual(s, str(buf2))
        else:
            s = bytes(list(range(256)))
            buf = self.execute("SELECT %s::bytea AS foo", (psycopg2.Binary(s),))
            buf2 = self.execute("SELECT %s::bytea AS foo", (buf,))
            self.assertEqual(s, buf2.tobytes())

    def testArray(self):
        s = self.execute("SELECT %s AS foo", ([[1,2],[3,4]],))
        self.assertEqual(s, [[1,2],[3,4]])
        s = self.execute("SELECT %s AS foo", (['one', 'two', 'three'],))
        self.assertEqual(s, ['one', 'two', 'three'])

    def testEmptyArrayRegression(self):
        # ticket #42
        import datetime
        curs = self.conn.cursor()
        curs.execute("create table array_test (id integer, col timestamp without time zone[])")

        curs.execute("insert into array_test values (%s, %s)", (1, [datetime.date(2011,2,14)]))
        curs.execute("select col from array_test where id = 1")
        self.assertEqual(curs.fetchone()[0], [datetime.datetime(2011, 2, 14, 0, 0)])

        curs.execute("insert into array_test values (%s, %s)", (2, []))
        curs.execute("select col from array_test where id = 2")
        self.assertEqual(curs.fetchone()[0], [])

    def testEmptyArray(self):
        s = self.execute("SELECT '{}' AS foo")
        self.assertEqual(s, [])
        s = self.execute("SELECT '{}'::text[] AS foo")
        self.assertEqual(s, [])
        s = self.execute("SELECT %s AS foo", ([],))
        self.assertEqual(s, [])
        s = self.execute("SELECT 1 != ALL(%s)", ([],))
        self.assertEqual(s, True)
        # but don't break the strings :)
        s = self.execute("SELECT '{}'::text AS foo")
        self.assertEqual(s, "{}")

    def testArrayEscape(self):
        ss = ['', '\\', '"', '\\\\', '\\"']
        for s in ss:
            r = self.execute("SELECT %s AS foo", (s,))
            self.assertEqual(s, r)
            r = self.execute("SELECT %s AS foo", ([s],))
            self.assertEqual([s], r)

        r = self.execute("SELECT %s AS foo", (ss,))
        self.assertEqual(ss, r)

    def testArrayMalformed(self):
        curs = self.conn.cursor()
        ss = ['', '{', '{}}', '{' * 20 + '}' * 20]
        for s in ss:
            self.assertRaises(psycopg2.DataError,
                psycopg2.extensions.STRINGARRAY, b(s), curs)

    @testutils.skip_before_postgres(8, 2)
    def testArrayOfNulls(self):
        curs = self.conn.cursor()
        curs.execute("""
            create table na (
              texta text[],
              inta int[],
              boola boolean[],

              textaa text[][],
              intaa int[][],
              boolaa boolean[][]
            )""")

        curs.execute("insert into na (texta) values (%s)", ([None],))
        curs.execute("insert into na (texta) values (%s)", (['a', None],))
        curs.execute("insert into na (texta) values (%s)", ([None, None],))
        curs.execute("insert into na (inta) values (%s)",  ([None],))
        curs.execute("insert into na (inta) values (%s)",  ([42, None],))
        curs.execute("insert into na (inta) values (%s)",  ([None, None],))
        curs.execute("insert into na (boola) values (%s)", ([None],))
        curs.execute("insert into na (boola) values (%s)", ([True, None],))
        curs.execute("insert into na (boola) values (%s)", ([None, None],))

        # TODO: array of array of nulls are not supported yet
        # curs.execute("insert into na (textaa) values (%s)", ([[None]],))
        curs.execute("insert into na (textaa) values (%s)", ([['a', None]],))
        # curs.execute("insert into na (textaa) values (%s)", ([[None, None]],))
        # curs.execute("insert into na (intaa) values (%s)",  ([[None]],))
        curs.execute("insert into na (intaa) values (%s)",  ([[42, None]],))
        # curs.execute("insert into na (intaa) values (%s)",  ([[None, None]],))
        # curs.execute("insert into na (boolaa) values (%s)", ([[None]],))
        curs.execute("insert into na (boolaa) values (%s)", ([[True, None]],))
        # curs.execute("insert into na (boolaa) values (%s)", ([[None, None]],))

    @testutils.skip_from_python(3)
    def testTypeRoundtripBuffer(self):
        o1 = buffer("".join(map(chr, list(range(256)))))
        o2 = self.execute("select %s;", (o1,))
        self.assertEqual(type(o1), type(o2))

        # Test with an empty buffer
        o1 = buffer("")
        o2 = self.execute("select %s;", (o1,))
        self.assertEqual(type(o1), type(o2))
        self.assertEqual(str(o1), str(o2))

    @testutils.skip_from_python(3)
    def testTypeRoundtripBufferArray(self):
        o1 = buffer("".join(map(chr, list(range(256)))))
        o1 = [o1]
        o2 = self.execute("select %s;", (o1,))
        self.assertEqual(type(o1[0]), type(o2[0]))
        self.assertEqual(str(o1[0]), str(o2[0]))

    @testutils.skip_before_python(3)
    def testTypeRoundtripBytes(self):
        o1 = bytes(list(range(256)))
        o2 = self.execute("select %s;", (o1,))
        self.assertEqual(memoryview, type(o2))

        # Test with an empty buffer
        o1 = bytes([])
        o2 = self.execute("select %s;", (o1,))
        self.assertEqual(memoryview, type(o2))

    @testutils.skip_before_python(3)
    def testTypeRoundtripBytesArray(self):
        o1 = bytes(list(range(256)))
        o1 = [o1]
        o2 = self.execute("select %s;", (o1,))
        self.assertEqual(memoryview, type(o2[0]))

    @testutils.skip_before_python(2, 6)
    def testAdaptBytearray(self):
        o1 = bytearray(list(range(256)))
        o2 = self.execute("select %s;", (o1,))

        if sys.version_info[0] < 3:
            self.assertEqual(buffer, type(o2))
        else:
            self.assertEqual(memoryview, type(o2))

        self.assertEqual(len(o1), len(o2))
        for c1, c2 in zip(o1, o2):
            self.assertEqual(c1, ord(c2))

        # Test with an empty buffer
        o1 = bytearray([])
        o2 = self.execute("select %s;", (o1,))

        self.assertEqual(len(o2), 0)
        if sys.version_info[0] < 3:
            self.assertEqual(buffer, type(o2))
        else:
            self.assertEqual(memoryview, type(o2))

    @testutils.skip_before_python(2, 7)
    def testAdaptMemoryview(self):
        o1 = memoryview(bytearray(list(range(256))))
        o2 = self.execute("select %s;", (o1,))
        if sys.version_info[0] < 3:
            self.assertEqual(buffer, type(o2))
        else:
            self.assertEqual(memoryview, type(o2))

        # Test with an empty buffer
        o1 = memoryview(bytearray([]))
        o2 = self.execute("select %s;", (o1,))
        if sys.version_info[0] < 3:
            self.assertEqual(buffer, type(o2))
        else:
            self.assertEqual(memoryview, type(o2))

    def testByteaHexCheckFalsePositive(self):
        # the check \x -> x to detect bad bytea decode
        # may be fooled if the first char is really an 'x'
        o1 = psycopg2.Binary(b'x')
        o2 = self.execute("SELECT %s::bytea AS foo", (o1,))
        self.assertEqual(b'x', o2[0])

    def testNegNumber(self):
        d1 = self.execute("select -%s;", (decimal.Decimal('-1.0'),))
        self.assertEqual(1, d1)
        f1 = self.execute("select -%s;", (-1.0,))
        self.assertEqual(1, f1)
        i1 = self.execute("select -%s;", (-1,))
        self.assertEqual(1, i1)
        l1 = self.execute("select -%s;", (-1,))
        self.assertEqual(1, l1)

    def testGenericArray(self):
        a = self.execute("select '{1,2,3}'::int4[]")
        self.assertEqual(a, [1,2,3])
        a = self.execute("select array['a','b','''']::text[]")
        self.assertEqual(a, ['a','b',"'"])

    @testutils.skip_before_postgres(8, 2)
    def testGenericArrayNull(self):
        def caster(s, cur):
            if s is None: return "nada"
            return int(s) * 2
        base = psycopg2.extensions.new_type((23,), "INT4", caster)
        array = psycopg2.extensions.new_array_type((1007,), "INT4ARRAY", base)

        psycopg2.extensions.register_type(array, self.conn)
        a = self.execute("select '{1,2,3}'::int4[]")
        self.assertEqual(a, [2,4,6])
        a = self.execute("select '{1,2,NULL}'::int4[]")
        self.assertEqual(a, [2,4,'nada'])

class AdaptSubclassTest(unittest.TestCase):
    def test_adapt_subtype(self):
        from psycopg2.extensions import adapt
        class Sub(str): pass
        s1 = "hel'lo"
        s2 = Sub(s1)
        self.assertEqual(adapt(s1).getquoted(), adapt(s2).getquoted())

    def test_adapt_most_specific(self):
        from psycopg2.extensions import adapt, register_adapter, AsIs

        class A(object): pass
        class B(A): pass
        class C(B): pass

        register_adapter(A, lambda a: AsIs("a"))
        register_adapter(B, lambda b: AsIs("b"))
        try:
            self.assertEqual(b'b', adapt(C()).getquoted())
        finally:
            del psycopg2.extensions.adapters[A, psycopg2.extensions.ISQLQuote]
            del psycopg2.extensions.adapters[B, psycopg2.extensions.ISQLQuote]

    @testutils.skip_from_python(3)
    def test_no_mro_no_joy(self):
        from psycopg2.extensions import adapt, register_adapter, AsIs

        class A: pass
        class B(A): pass

        register_adapter(A, lambda a: AsIs("a"))
        try:
            self.assertRaises(psycopg2.ProgrammingError, adapt, B())
        finally:
            del psycopg2.extensions.adapters[A, psycopg2.extensions.ISQLQuote]

    @testutils.skip_before_python(3)
    def test_adapt_subtype_3(self):
        from psycopg2.extensions import adapt, register_adapter, AsIs

        class A: pass
        class B(A): pass

        register_adapter(A, lambda a: AsIs("a"))
        try:
            self.assertEqual(b"a", adapt(B()).getquoted())
        finally:
            del psycopg2.extensions.adapters[A, psycopg2.extensions.ISQLQuote]

class ByteaParserTest(unittest.TestCase):
    """Unit test for our bytea format parser."""
    def setUp(self):
        try:
            self._cast = self._import_cast()
        except Exception as e:
            self._cast = None
            self._exc = e

    def _import_cast(self):
        """Use ctypes to access the C function.

        Raise any sort of error: we just support this where ctypes works as
        expected.
        """
        import ctypes
        lib = ctypes.cdll.LoadLibrary(psycopg2._psycopg.__file__)
        cast = lib.typecast_BINARY_cast
        cast.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.py_object]
        cast.restype = ctypes.py_object
        return cast

    def cast(self, buffer):
        """Cast a buffer from the output format"""
        l = buffer and len(buffer) or 0
        rv = self._cast(buffer, l, None)

        if rv is None:
            return None

        if sys.version_info[0] < 3:
            return str(rv)
        else:
            return rv.tobytes()

    def test_null(self):
        rv = self.cast(None)
        self.assertEqual(rv, None)

    def test_blank(self):
        rv = self.cast(b'')
        self.assertEqual(rv, b'')

    def test_blank_hex(self):
        # Reported as problematic in ticket #48
        rv = self.cast(b'\\x')
        self.assertEqual(rv, b'')

    def test_full_hex(self, upper=False):
        buf = ''.join(("%02x" % i) for i in range(256))
        if upper: buf = buf.upper()
        buf = '\\x' + buf
        rv = self.cast(b(buf))
        if sys.version_info[0] < 3:
            self.assertEqual(rv, ''.join(map(chr, list(range(256)))))
        else:
            self.assertEqual(rv, bytes(list(range(256))))

    def test_full_hex_upper(self):
        return self.test_full_hex(upper=True)

    def test_full_escaped_octal(self):
        buf = ''.join(("\\%03o" % i) for i in range(256))
        rv = self.cast(b(buf))
        if sys.version_info[0] < 3:
            self.assertEqual(rv, ''.join(map(chr, list(range(256)))))
        else:
            self.assertEqual(rv, bytes(list(range(256))))

    def test_escaped_mixed(self):
        import string
        buf = ''.join(("\\%03o" % i) for i in range(32))
        buf += string.ascii_letters
        buf += ''.join('\\' + c for c in string.ascii_letters)
        buf += '\\\\'
        rv = self.cast(b(buf))
        if sys.version_info[0] < 3:
            tgt = ''.join(map(chr, list(range(32)))) \
                + string.ascii_letters * 2 + '\\'
        else:
            tgt = bytes(list(range(32))) + \
                (string.ascii_letters * 2 + '\\').encode('ascii')

        self.assertEqual(rv, tgt)

def skip_if_cant_cast(f):
    @wraps(f)
    def skip_if_cant_cast_(self, *args, **kwargs):
        if self._cast is None:
            return self.skipTest("can't test bytea parser: %s - %s"
                % (self._exc.__class__.__name__, self._exc))

        return f(self, *args, **kwargs)

    return skip_if_cant_cast_

decorate_all_tests(ByteaParserTest, skip_if_cant_cast)

def test_suite():
    return unittest.TestLoader().loadTestsFromName(__name__)

if __name__ == "__main__":
    unittest.main()