text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="shortcut icon" href="/static/img/favicon.ico" />
        <title>Test Page - Chris Willingham</title>
        <meta name="author" content="Chris Willingham" />
        <meta name="description" content="Test Page" />
        <meta name="keywords" content="Test Page, Chris Willingham, others" />

        <meta content="0" property="fb:app_id">
        <meta content="Chris Willingham" property="og:site_name">

          <meta content="Test Page" property="og:title">

          <meta content="article" property="og:type">

          <meta content="My Personal Blog" property="og:description">

          <meta content="https://clwillingham.github.io//others/2015/06/04/test-page.html" property="og:url">

          <meta content="2015-06-04T09:50:39-04:00" property="article:published_time">
          <meta content="https://clwillingham.github.io//about/" property="article:author">

          <meta content="http://aboutashu.com/static/img/logo-high-resolution.png" property="og:image">

          <meta content="others" property="article:section">

        <meta name="twitter:card" content="summary">
        <meta name="twitter:site" content="@\#">
        <meta name="twitter:creator" content="@\#">

          <meta name="twitter:title" content="Test Page">

          <meta name="twitter:url" content="https://clwillingham.github.io//others/2015/06/04/test-page.html">

          <meta name="twitter:description" content="My Personal Blog">

        <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">

        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700" type="text/css">

        <link rel="stylesheet" href="https://use.fontawesome.com/74dfc6cf47.css">

        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://clwillingham.github.io//static/css/bootstrap-material-design.min.css">

        <link rel="stylesheet" href="https://clwillingham.github.io//static/css/syntax.css">

        <link rel="stylesheet" href="https://clwillingham.github.io/static/css/thickbox.css">
        <link rel="stylesheet" href="https://clwillingham.github.io/static/css/main.css">
        <link rel="stylesheet" href="https://clwillingham.github.io/static/css/projects.css">

Chris Willingham

Secret Ninja

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
              Toggle navigation

            </button>

Test Page

      04 Jun 2015

        » others

 Home

 About

 Projects

 Resume

 Github

 XML Feed

This is a test blog page where we can explore how to embedd images in the blog.

Image example 1

Here, I will embedd image from local assets which goes into assets directory in project's root directory. Choose a specific image, related to particular post. I chose to name the image test-page-image-1.jpg, which I will embedd as:

![my alternate text](/assets/test-page-image-1.jpg);

;

Ofcourse, you can load images from web as well. Just point to image direct URL. For ex, here is one placeholder image:

![my alternate text](http://lorempixel.com/400/200);

;

One cool thing about this is the fact that images adapt themselves to the screen size of device. Try to resize your browser window and check for yourself, Have fun.

    Share this on →
 Tweet

    Welcome to Jekyll! »

                    © Copyright text here

                    - Privacy link - Powered by Jekyll.


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\CustomizeLoadedData\Handler;

use Oro\Bundle\ApiBundle\Config\EntityDefinitionConfig;
use Oro\Bundle\ApiBundle\Config\Extra\EntityDefinitionConfigExtra;
use Oro\Bundle\ApiBundle\Processor\CustomizeLoadedData\CustomizeLoadedDataContext;
use Oro\Bundle\ApiBundle\Processor\CustomizeLoadedData\Handler\EntityHandler;
use Oro\Bundle\ApiBundle\Request\RequestType;
use Oro\Bundle\ApiBundle\Tests\Unit\Fixtures\Entity;
use Oro\Component\ChainProcessor\ActionProcessorInterface;
use Oro\Component\ChainProcessor\ParameterBagInterface;

class EntityHandlerTest extends \PHPUnit\Framework\TestCase
{
    /** @var \PHPUnit\Framework\MockObject\MockObject|ActionProcessorInterface */
    private $customizationProcessor;

    protected function setUp()
    {
        $this->customizationProcessor = $this->createMock(ActionProcessorInterface::class);
    }

    /**
     * @param array $data
     * @param array $context
     *
     * @return array
     */
    public function handlerCallback(array $data, array $context)
    {
        $data['callbackKey'] = sprintf('callbackValue for "%s" action', $context['action']);

        return $data;
    }

    public function testWithoutPreviousHandler()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) use (
                    $version,
                    $requestType,
                    $entityClass,
                    $config,
                    $configExtras,
                    $data
                ) {
                    self::assertEquals($version, $context->getVersion());
                    self::assertEquals($requestType, $context->getRequestType());
                    self::assertEquals($entityClass, $context->getClassName());
                    self::assertSame($config, $context->getConfig());
                    self::assertSame($configExtras, $context->getConfigExtras());
                    self::assertEquals($data, $context->getResult());
                    self::assertEquals('item', $context->getFirstGroup());
                    self::assertEquals('item', $context->getLastGroup());
                    self::assertFalse($context->isIdentifierOnly());

                    $contextData = $context->getResult();
                    $contextData['anotherKey'] = 'anotherValue';
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            ['key' => 'value', 'anotherKey' => 'anotherValue'],
            $handledData
        );
    }

    public function testWithPreviousHandlerThatIsRedundant()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\UserProfile::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $previousHandler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            Entity\User::class,
            $config,
            $configExtras,
            false
        );
        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false,
            $previousHandler
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    $contextData = $context->getResult();
                    $contextData['anotherKey'] = 'anotherValue';
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            ['key' => 'value', 'anotherKey' => 'anotherValue'],
            $handledData
        );
    }

    public function testWithSeveralPreviousHandlersAndMiddleLevelPreviousHandlerIsRedundant()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\UserProfile::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $previousHandler1 = [$this, 'handlerCallback'];
        $previousHandler2 = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            Entity\User::class,
            $config,
            $configExtras,
            false,
            $previousHandler1
        );
        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false,
            $previousHandler2
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    $contextData = $context->getResult();
                    $contextData['anotherKey'] = 'anotherValue';
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            [
                'key'         => 'value',
                'callbackKey' => 'callbackValue for "get" action',
                'anotherKey'  => 'anotherValue'
            ],
            $handledData
        );
    }

    public function testWithPreviousHandlerThatIsNotRedundantDueToVersion()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $previousHandler = new EntityHandler(
            $this->customizationProcessor,
            '1.0',
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false
        );
        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false,
            $previousHandler
        );

        $this->customizationProcessor->expects(self::exactly(2))
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::exactly(2))
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    $contextData = $context->getResult();
                    if ('1.2' === $context->getVersion()) {
                        $contextData['anotherKey'] = 'anotherValue';
                    } elseif ('1.0' === $context->getVersion()) {
                        $contextData['previousKey'] = 'previousValue';
                    }
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            ['key' => 'value', 'previousKey' => 'previousValue', 'anotherKey' => 'anotherValue'],
            $handledData
        );
    }

    public function testWithPreviousHandlerThatIsNotRedundantDueToRequestType()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $previousHandler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            new RequestType(['test1']),
            $entityClass,
            $config,
            $configExtras,
            false
        );
        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false,
            $previousHandler
        );

        $this->customizationProcessor->expects(self::exactly(2))
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::exactly(2))
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    $contextData = $context->getResult();
                    if ('test' === (string)$context->getRequestType()) {
                        $contextData['anotherKey'] = 'anotherValue';
                    } elseif ('test1' === (string)$context->getRequestType()) {
                        $contextData['previousKey'] = 'previousValue';
                    }
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            ['key' => 'value', 'previousKey' => 'previousValue', 'anotherKey' => 'anotherValue'],
            $handledData
        );
    }

    public function testWithPreviousHandlerThatIsNotRedundantDueToEntityClass()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $previousHandler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            Entity\Account::class,
            $config,
            $configExtras,
            false
        );
        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false,
            $previousHandler
        );

        $this->customizationProcessor->expects(self::exactly(2))
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::exactly(2))
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    $contextData = $context->getResult();
                    if (Entity\User::class === $context->getClassName()) {
                        $contextData['anotherKey'] = 'anotherValue';
                    } elseif (Entity\Account::class === $context->getClassName()) {
                        $contextData['previousKey'] = 'previousValue';
                    }
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            ['key' => 'value', 'previousKey' => 'previousValue', 'anotherKey' => 'anotherValue'],
            $handledData
        );
    }

    public function testWithPreviousHandlerThatIsNotRedundantDueToHandlerType()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $previousHandler = function (array $data) {
            $data['previousKey'] = 'previousValue';

            return $data;
        };
        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false,
            $previousHandler
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    $contextData = $context->getResult();
                    $contextData['anotherKey'] = 'anotherValue';
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            ['key' => 'value', 'previousKey' => 'previousValue', 'anotherKey' => 'anotherValue'],
            $handledData
        );
    }

    public function testForIdentifierOnly()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $data = ['key' => 'value'];
        $config = new EntityDefinitionConfig();
        $config->setIdentifierFieldNames(['id']);
        $config->addField('id');
        $configExtras = [new EntityDefinitionConfigExtra()];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    self::assertTrue($context->isIdentifierOnly());
                }
            );

        \call_user_func($handler, $data, $context);
    }

    public function testForIdentifierOnlyWithCompositeIdentifier()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $data = ['key' => 'value'];
        $config = new EntityDefinitionConfig();
        $config->setIdentifierFieldNames(['id1', 'id2']);
        $config->addField('id1');
        $config->addField('id2');
        $configExtras = [new EntityDefinitionConfigExtra()];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    self::assertTrue($context->isIdentifierOnly());
                }
            );

        \call_user_func($handler, $data, $context);
    }

    public function testForOneFieldThatIsNotIdentifier()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $data = ['key' => 'value'];
        $config = new EntityDefinitionConfig();
        $config->setIdentifierFieldNames(['id']);
        $config->addField('field1');
        $configExtras = [new EntityDefinitionConfigExtra()];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    self::assertFalse($context->isIdentifierOnly());
                }
            );

        \call_user_func($handler, $data, $context);
    }

    public function testForEntityWithoutIdentifier()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $data = ['key' => 'value'];
        $config = new EntityDefinitionConfig();
        $config->addField('field1');
        $configExtras = [new EntityDefinitionConfigExtra()];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            false
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) {
                    self::assertFalse($context->isIdentifierOnly());
                }
            );

        \call_user_func($handler, $data, $context);
    }

    public function testForCollectionHandler()
    {
        $version = '1.2';
        $requestType = new RequestType(['test']);
        $entityClass = Entity\User::class;
        $config = new EntityDefinitionConfig();
        $configExtras = [new EntityDefinitionConfigExtra()];
        $data = ['key' => 'value'];

        $sharedData = $this->createMock(ParameterBagInterface::class);
        $context = ['action' => 'get', 'sharedData' => $sharedData];

        $handler = new EntityHandler(
            $this->customizationProcessor,
            $version,
            $requestType,
            $entityClass,
            $config,
            $configExtras,
            true
        );

        $this->customizationProcessor->expects(self::once())
            ->method('createContext')
            ->willReturn(new CustomizeLoadedDataContext());
        $this->customizationProcessor->expects(self::once())
            ->method('process')
            ->willReturnCallback(
                function (CustomizeLoadedDataContext $context) use (
                    $version,
                    $requestType,
                    $entityClass,
                    $config,
                    $configExtras,
                    $data
                ) {
                    self::assertEquals($version, $context->getVersion());
                    self::assertEquals($requestType, $context->getRequestType());
                    self::assertEquals($entityClass, $context->getClassName());
                    self::assertSame($config, $context->getConfig());
                    self::assertSame($configExtras, $context->getConfigExtras());
                    self::assertEquals($data, $context->getResult());
                    self::assertEquals('collection', $context->getFirstGroup());
                    self::assertEquals('collection', $context->getLastGroup());
                    self::assertFalse($context->isIdentifierOnly());

                    $contextData = $context->getResult();
                    $contextData['anotherKey'] = 'anotherValue';
                    $context->setResult($contextData);
                }
            );

        $handledData = \call_user_func($handler, $data, $context);
        self::assertEquals(
            ['key' => 'value', 'anotherKey' => 'anotherValue'],
            $handledData
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
Titanium.include('/common/constant.js');
Titanium.include('style.js');
Titanium.include('event.js');

var win = Titanium.UI.currentWindow;

var lblTitle = Titanium.UI.createLabel(styles["lblTitle"]);
lblTitle.text = Titanium.Locale.getString("login_title");
win.add(lblTitle);

var lblLoginTitle = Titanium.UI.createLabel(styles["lblLoginTitle"]);
lblLoginTitle.text = Titanium.Locale.getString("login_titlesub");
win.add(lblLoginTitle);

var txtLogin = Titanium.UI.createTextField(styles["txtLogin"]);
win.add(txtLogin);

var btnLogin = Titanium.UI.createButton(styles["btnLogin"]);
btnLogin.title = Titanium.Locale.getString("login_btnlogin");
btnLogin.addEventListener(EVT_CLICK,executeTrans);
win.add(btnLogin);

var btnReset = Titanium.UI.createButton(styles["btnReset"]);
btnReset.title = Titanium.Locale.getString("login_btnReset");
btnReset.addEventListener(EVT_CLICK,clearText);
win.add(btnReset);

win.open();


text:
namespace HCEngine.DefaultImplementations.Language
{
    /// <summary>
    ///     Static class containing all of the default language keywords.
    /// </summary>
    /// <remarks>Should find better solution to allow diferent keywords for different engine instances.</remarks>
    public static class DefaultLanguageKeywords
    {
        /// <summary>
        ///     Symbol for declaring the beginning of a list.
        /// </summary>
        public static string ListBeginSymbol { get; set; } = "(";

        /// <summary>
        ///     Symbol for declaring the end of a list.
        /// </summary>
        public static string ListEndSymbol { get; set; } = ")";

        /// <summary>
        ///     Symbol for declaring a variable.
        /// </summary>
        public static string VariableFirstSymbol { get; set; } = "$";

        /// <summary>
        ///     Keyword for declaring a variable's type.
        /// </summary>
        public static string TypingKeyword { get; set; } = "is";

        /// <summary>
        ///     Keyword for declaring an input section.
        /// </summary>
        public static string InputKeyword { get; set; } = "input";

        /// <summary>
        ///     Keyword for declaring a loop.
        /// </summary>
        public static string LoopKeyword { get; set; } = "loop";

        /// <summary>
        ///     Keyword for declaring a while loop.
        /// </summary>
        public static string WhileKeyword { get; set; } = "while";

        /// <summary>
        ///     Keyword for declaring a each loop.
        /// </summary>
        public static string EachKeyword { get; set; } = "in";

        /// <summary>
        ///     Keyword for declaring a if section.
        /// </summary>
        public static string IfKeyword { get; set; } = "if";

        /// <summary>
        ///     Keyword for declaring a else block of a if section.
        /// </summary>
        public static string ElseKeyword { get; set; } = "else";

        /// <summary>
        ///     Keyword for declaring an assignation.
        /// </summary>
        public static string AssignationKeyword { get; set; } = "set";

        /// <summary>
        ///     Keyword for assigning a generic type argument.
        /// </summary>
        public static string GenericTypeArgumentKeyword { get; set; } = "of";
    }
}


text:
/**
 * For Skip Nav in Morpheus
 */

var setupSkipNav = function(){
  // function called from site.vm to enable skip links for all browsers
   $PBJQ('#skipNav a.Mrphs-skipNav__link').click(function(){
     var target = $PBJQ(this).attr('href');
    $PBJQ(target).attr('tabindex','-1').focus();
   });
};


text:
package com.google.moviestvsentiments.service.account;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import com.google.moviestvsentiments.model.Account;
import java.time.Instant;
import java.util.List;

/**
 * A high-level interface for querying the accounts database table.
 */
@Dao
public abstract class AccountDao {

    /**
     * Adds the given account name into the accounts table. If the name already exists,
     * it is ignored. The account record is created with is_current set to false.
     * @param name The name of the account to add.
     * @param timestamp The timestamp of the account to add.
     * @param isPending Whether the account needs to be synced with the server or not.
     */
    @Query("INSERT OR IGNORE INTO accounts_table (account_name, timestamp, is_pending) " +
            "VALUES (:name, :timestamp, :isPending)")
    public abstract void addAccount(String name, Instant timestamp, boolean isPending);

    /**
     * Adds all of the given accounts into the accounts table. If any already exist, they are
     * replaced.
     * @param accounts The accounts to insert into the table.
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public abstract void addAccounts(List<Account> accounts);

    /**
     * Returns a LiveData list of all accounts in alphabetical order.
     */
    @Query("SELECT * FROM accounts_table ORDER BY account_name ASC")
    public abstract LiveData<List<Account>> getAlphabetizedAccounts();

    /**
     * Returns a LiveData object containing the currently signed-in account or null if all accounts
     * are signed-out.
     */
    @Query("SELECT * FROM accounts_table WHERE is_current = 1")
    public abstract LiveData<Account> getCurrentAccount();

    /**
     * Updates the given account record's is_current value.
     * @param name The name of the account to update.
     * @param isCurrent The value to set is_current to.
     * @return True if the record exists and was updated successfully.
     */
    public boolean setIsCurrent(String name, boolean isCurrent) {
        int updated = setIsCurrentQuery(name, isCurrent);
        return updated > 0;
    }

    // Room update query methods can only have void or int return types, so this method exists
    // to allow the public API to return a boolean.
    @Query("UPDATE accounts_table SET is_current = :isCurrent WHERE account_name = :name")
    protected abstract int setIsCurrentQuery(String name, boolean isCurrent);

    /**
     * Returns a list of all accounts that have isPending set to true.
     */
    @Query("SELECT * FROM accounts_table WHERE is_pending = 1")
    public abstract List<Account> getPendingAccounts();

    /**
     * Sets isPending to false for each of the given Account names. This method should be used
     * when the pending accounts have been successfully synced with the server. The addAccounts
     * method cannot be used because the current account may have been pending, and the addAccounts
     * method would replace the database record, clearing its isCurrent flag.
     * @param accountNames The names of the Accounts whose isPending flag should be cleared.
     */
    @Query("UPDATE accounts_table SET is_pending = 0 WHERE account_name IN (:accountNames)")
    public abstract void clearIsPending(List<String> accountNames);
}


text:
class GiftsController < ApplicationController
  before_action :ensure_logged_in

  def index
    calendar  = Calendar.new(Gift.giftable_dates, current_user.gifts)

    render :index, locals: { calendar: calendar }
  end

  def new
    gift_form = GiftForm.new(gift:           current_user.new_gift,
                             pull_requests:  current_user.unspent_pull_requests,
                             giftable_dates: Gift.giftable_dates,
                             date:           params['date'])

    render :new, locals: { gift_form: gift_form }
  end

  def create
    gift = current_user.new_gift(gift_params)

    if gift.save
      gift.pull_request.post_tweet if tweet?
      gift_given
    else
      gift_failed(gift)
    end
  end

  def edit
    gift_form = GiftForm.new(gift:          gift,
                             pull_requests: current_user.unspent_pull_requests)

    render :new, locals: { gift_form: gift_form }
  end

  def update
    if gift.update_attributes(gift_params)
      gift_given
    else
      gift_failed(gift)
    end
  end

  def destroy
    gift.destroy

    redirect_to user_path(current_user), alert: 'Gift removed'
  end

  private

  def gift
    @gift ||= current_user.gift_for(params[:id])
  end

  def gift_params
    pull_request = current_user.pull_requests.year(current_year).find_by_id(pull_request_id)
    post_params.merge(pull_request: pull_request)
  end

  def gift_given
    flash[:notice] = 'Your code has been gifted.'
    redirect_to gifts_path
  end

  def gift_failed(gift)
    gift_form = GiftForm.new(gift:           gift,
                             pull_requests:  current_user.unspent_pull_requests,
                             giftable_dates: Gift.giftable_dates)

    render :new, locals: { gift_form: gift_form }
  end

  def pull_request_id
    gift_permitted_params[:pull_request_id]
  end

  def post_params
    gift_permitted_params
  end

  def gift_permitted_params
    params.require(:gift).permit(:pull_request_id, :date, :tweet)
  end

  def tweet?
    gift_permitted_params[:tweet] == 'true'
  end
end


text:
using System;

namespace MbDotNet.Exceptions
{
    [Serializable]
    public class MountebankException : Exception
    {
        public MountebankException(string message) : base(message) { }
        public MountebankException(string message, Exception innerException) : base(message, innerException) { }
    }
}


text:
from libsaas import http, parsers
from libsaas.services import base

from . import ads

class Advertiser(base.HierarchicalResource):

    path = 'advertisers'

    @base.resource(ads.TextAd)
    def textad(self, hash):
        """
        Return a resource corresponding to a single text ad.

        :var hash: A unique hash identifying this ad.
        :vartype hash: str
        """
        return ads.TextAd(self, hash)

    @base.resource(ads.DisplayAd)
    def displayad(self, hash):
        """
        Return a resource corresponding to a single display ad.

        :var hash: A unique hash identifying this ad.
        :vartype hash: str
        """
        return ads.DisplayAd(self, hash)

    @base.apimethod
    def summary(self):
        """
        Fetch the advertiser's summary.

        Upstream documentation: http://mixrank.com/api/documentation#advertiser
        """
        request = http.Request('GET', self.get_url())

        return request, parsers.parse_json

    @base.apimethod
    def textads(self, offset=None, page_size=None, min_avg_position=None,
                max_avg_position=None, min_times_seen=None,
                max_times_seen=None, first_seen_before=None,
                first_seen_after=None, last_seen_before=None,
                last_seen_after=None, sort_field=None, sort_order=None):
        """
        Fetch the Google Display Network text ads for this advertiser.

        Upstream documentation: http://mixrank.com/api/documentation#advertiser_textads
        """
        params = base.get_params(None, locals())
        url = self.get_url() + '/gdn/textads'
        request = http.Request('GET', url, params)

        return request, parsers.parse_json

    @base.apimethod
    def displayads(self, offset=None, page_size=None, min_times_seen=None,
                   max_times_seen=None, first_seen_before=None,
                   first_seen_after=None, last_seen_before=None,
                   last_seen_after=None, sort_field=None, sort_order=None):
        """
        Fetch the Google Display Network display ads for this advertiser.

        Upstream documentation: http://mixrank.com/api/documentation#advertiser_displayads
        """
        params = base.get_params(None, locals())
        url = self.get_url() + '/gdn/displayads'
        request = http.Request('GET', url, params)

        return request, parsers.parse_json

    @base.apimethod
    def publishers(self, offset=None, page_size=None, min_times_seen=None,
                   max_times_seen=None, min_monthly_uniques=None,
                   max_monthly_uniques=None, last_seen_before=None,
                   last_seen_after=None, sort_field=None, sort_order=None):
        """
        Fetch the Google Display Network publishers for this advertiser.

        Upstream documentation: http://mixrank.com/api/documentation#advertiser_publishers
        """
        params = base.get_params(None, locals())
        url = self.get_url() + '/gdn/publishers'
        request = http.Request('GET', url, params)

        return request, parsers.parse_json

    @base.apimethod
    def keywords(self, offset=None, page_size=None, min_times_seen=None,
                 max_times_seen=None, first_seen_before=None,
                 first_seen_after=None, last_seen_before=None,
                 last_seen_after=None, sort_field=None, sort_order=None):
        """
        Fetch the Google Display Network keywords for this advertiser.

        Upstream documentation: http://mixrank.com/api/documentation#advertiser_keywords
        """
        params = base.get_params(None, locals())
        url = self.get_url() + '/gdn/keywords'
        request = http.Request('GET', url, params)

        return request, parsers.parse_json


text:
#include "config.h"
#include "DeferredData.h"

#include "NetworkJob.h"

namespace WebCore {

DeferredData::DeferredData(NetworkJob& job)
    : m_job(job)
    , m_processDataTimer(this, &DeferredData::fireProcessDataTimer)
    , m_deferredStatusReceived(false)
    , m_status(0)
    , m_bytesSent(0)
    , m_totalBytesToBeSent(0)
    , m_deferredCloseStatus(BlackBerry::Platform::FilterStream::StatusSuccess)
    , m_deferredClose(false)
    , m_inProcessDeferredData(false)
{
}

void DeferredData::deferOpen(int status, const String& message)
{
    m_deferredStatusReceived = true;
    m_status = status;
    m_message = message;
}

void DeferredData::deferHeaderReceived(const String& key, const String& value)
{
    m_headerKeys.append(key);
    m_headerValues.append(value);
}

void DeferredData::deferMultipartHeaderReceived(const String& key, const String& value)
{
    m_multipartHeaderKeys.append(key);
    m_multipartheaderValues.append(value);
}

void DeferredData::deferDataSent(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
    m_bytesSent = bytesSent;
    m_totalBytesToBeSent = totalBytesToBeSent;
}

void DeferredData::deferDataReceived(const char* buf, size_t len)
{
    m_dataSegments.append(Vector<char>());
    m_dataSegments.rbegin()->append(buf, len);
}

void DeferredData::deferClose(int status)
{
    m_deferredCloseStatus = status;
    m_deferredClose = true;
}

bool DeferredData::processHeaders(Vector<String>& headerKeys, Vector<String>& headerValues, HandleHeadersFunction function)
{
    size_t numHeaders = headerKeys.size();
    ASSERT(headerValues.size() == numHeaders);
    for (size_t i = 0; i < numHeaders; ++i) {
        (m_job.*function)(headerKeys[i], headerValues[i]);

        if (m_job.isDeferringLoading()) {
            // Remove all the headers that have already been processed.
            headerKeys.remove(0, i + 1);
            headerValues.remove(0, i + 1);
            return false;
        }

        if (m_job.isCancelled()) {
            // Don't bother removing headers; job will be deleted.
            return false;
        }
    }
    headerKeys.clear();
    headerValues.clear();
    return true;
}

void DeferredData::processDeferredData()
{
    if (m_inProcessDeferredData)
        return;

    RecursionGuard guard(m_inProcessDeferredData);

    // Sending data to webkit causes it to be parsed and javascript executed,
    // which might cause it to cancel the job or set defersLoading again. So
    // to be safe, check this after every step.
    if (m_job.isDeferringLoading() || m_job.isCancelled())
        return;

    if (m_deferredStatusReceived) {
        m_job.handleNotifyStatusReceived(m_status, m_message);
        m_deferredStatusReceived = false;
        if (m_job.isDeferringLoading() || m_job.isCancelled())
            return;
    }

    if (!processHeaders(m_headerKeys, m_headerValues, &NetworkJob::handleNotifyHeaderReceived)
        || !processHeaders(m_multipartHeaderKeys, m_multipartheaderValues, &NetworkJob::handleNotifyMultipartHeaderReceived))
        return;

    // Only process 32k of data at a time to avoid blocking the event loop for too long.
    static const unsigned maxData = 32 * 1024;

    unsigned totalData = 0;
    while (!m_dataSegments.isEmpty()) {
        const Vector<char>& buffer = m_dataSegments.first();
        m_job.handleNotifyDataReceived(buffer.data(), buffer.size());
        totalData += buffer.size();

        if (m_job.isCancelled()) {
            // Don't bother removing segment; job will be deleted.
            return;
        }

        m_dataSegments.removeFirst();

        if (m_job.isDeferringLoading()) {
            // Stop processing until deferred loading is turned off again.
            return;
        }

        if (totalData >= maxData && !m_dataSegments.isEmpty()) {
            // Pause for now, and schedule a timer to continue after running the event loop.
            scheduleProcessDeferredData();
            return;
        }
    }

    if (m_totalBytesToBeSent) {
        m_job.handleNotifyDataSent(m_bytesSent, m_totalBytesToBeSent);
        m_bytesSent = 0;
        m_totalBytesToBeSent = 0;
    }

    if (m_deferredClose) {
        m_job.handleNotifyClose(m_deferredCloseStatus);
        m_deferredClose = false;
        if (m_job.isDeferringLoading() || m_job.isCancelled())
            return;
    }
}

void DeferredData::fireProcessDataTimer(Timer<DeferredData>*)
{
    processDeferredData();
}

} // namespace WebCore


text:
from image_scraper.cli.commands import cli

if __name__ == "__main__":
    cli()


text:
var test = require("tape")

var Stringify = require("../stringify")
var stringify = Stringify([
    require("../plugins/loose.js"),
    require("../plugins/fragment.js"),
    require("../plugins/raw.js")
])

var children = [
    "foo",
    { raw: "foo©" },
    null,
    ["span"],
    ["span", { raw: "foo©"} ],
    ["span", "foo"],
    ["span", { class: "foo" }]
]

var childrenString =
    "foo" +
    "foo©" +
    "" +
    "foo©" +
    "foo" +
    ""

var whiteChildrenString =
    "foo" +
    "foo©" +
    "" +
    "foo©" +
    "foo" +
    ""

test("String is valid", function (assert) {
    var html = stringify("foobar")

    assert.equal(html, "foobar")

    assert.end()
})

test("{ raw: String } is valid", function (assert) {
    var html = stringify({ raw: "foo©"})

    assert.equal(html, "foo©")

    assert.end()
})

test("{ fragment: Array<MaybeJsonML> } is valid", function (assert) {
    var html = stringify({ fragment: children })

    assert.equal(html, childrenString)

    assert.end()
})

test("[String] is valid", function (assert) {
    var html = stringify(["span"])

    assert.equal(html, "")

    assert.end()
})

test("[String, { raw: String }] is valid", function (assert) {
    var html = stringify(["span", { raw: "foo©" }])

    assert.equal(html, "foo©")

    assert.end()
})

test("[String, { fragment: Array<MaybeJsonML> }] is valid", function (assert) {
    var html = stringify(["span", { fragment: children }])

    assert.equal(html, "" + whiteChildrenString + "")

    assert.end()
})

test("[String, Object<String, String>] is valid", function (assert) {
    var html = stringify(["span", { class: "foobar" }])

    assert.equal(html, "")

    assert.end()
})

test("[String, String] is valid", function (assert) {
    var html = stringify(["span", "foo"])

    assert.equal(html, "foo")

    assert.end()
})

test("[String, Array<MaybeJsonML>] is valid", function (assert) {
    var html = stringify(["div", children])

    assert.equal(html, "
" + childrenString + "
")

    assert.end()
})

test("[String, Object, Array<MaybeJsonML>] is valid", function (assert) {
    var html = stringify(["div", { class: "bar" }, children])

    assert.equal(html, "
" + childrenString + "
")

    assert.end()
})

test("[String, Object, String] is valid", function (assert) {
    var html = stringify(["div", { class: "bar" }, "foo"])

    assert.equal(html, "
foo
")

    assert.end()
})
test("[String, Object, { fragment: Array<MaybeJsonML> }]", function (assert) {
    var html = stringify(["div", { class: "bar" }, { fragment: children }])

    assert.equal(html, "
" +
        whiteChildrenString + "
")

    assert.end()
})

test("[String, Object, { raw: String }] is valid", function (assert) {
    var html = stringify(["div", { class: "bar" }, { raw: "foo©" }])

    assert.equal(html, "
foo©
")

    assert.end()
})

test("[[String, Object]] throws an exception", function (assert) {
    assert.throws(function () {
        stringify([["div", {}]])
    }, /Selector is not a string/)

    assert.end()
})

test("[String, String, Array] throws an exception", function (assert) {
    assert.throws(function () {
        var res = stringify(["div", "some text", ["some more text"]])
        console.log("response what", res)
    }, /Properties is not an object/)

    assert.end()
})

test("[] throws an exception", function (assert) {
    assert.throws(function () {
        stringify([])
    }, /Empty array is not a valid elem/)

    assert.end()
})


text:
patchwork is part framework, part boilerplate and part mixed utilities,
extensions and third party libraries. Used correctly, it can help you
create awesome SilverStripe sites if you like its convention over
configuration philosophy. It can be used with or without the SilverStripe
CMS module, SilverStripe framework is however required for obvious reasons.

Theoretically speaking it might be better to split patchwork into smaller
and more logically related modules, practically speaking it saves time
to only worry about one module (maintenance, dependencies, and so on).

Disclaimer: This module is a work in progress, anything and everything may
change at any time right now. However, things are getting more and more
stable.

## Maintainer Contact

Redema AB, http://redema.se/

## Requirements

 * PHP: 5.3.1+ minimum.
 * Database: MySQL 5.5+ minimum.
 * SilverStripe framework: 3.1+ minimum (previous versions has never been tested).

## Recommendations

 * PHPUnit - https://github.com/sebastianbergmann/phpunit/
 * Additional SilverStripe modules:
   * CMS - https://github.com/silverstripe/silverstripe-cms
   * SortableGridField - https://github.com/UndefinedOffset/SortableGridField
   * GoogleSiteMaps - https://github.com/silverstripe-labs/silverstripe-googlesitemaps

## Getting started with a new project

 * Place this directory in the root of your SilverStripe installation. Make sure
   that the folder is named "patchwork".

 * Copy the example environment file and edit it, remove everything not
   needed in `mysite/_config.php`:
   * `www$ cp patchwork/_ss_environment.php.example _ss_environment.php`
   * `www$ ed _ss_environment.php`
   * `www$ ed mysite/_config.php`

 * Copy the standard Page template to mysite and create overrides for
   `Header.ss`, `Footer.ss` and `Page.ss`:
   * `www$ cp patchwork/templates/Page.ss mysite/templates/`
   * `www$ echo "" > mysite/templates/Includes/Header.ss`
   * `www$ echo "" > mysite/templates/Includes/Footer.ss`
   * `www$ echo "" > mysite/templates/Layout/Page.ss`

 * Copy the standard editor css to mysite and create the default
   project css files:
   * `www$ cp patchwork/css/editor.css mysite/css/`
   * `www$ echo "" > mysite/css/layout.css`
   * `www$ echo "" > mysite/css/form.css`
   * `www$ echo "" > mysite/css/typography.css`

 * Visit http://www.yoursite.example.com/dev/build?flush=all to rebuild the
   manifest and database (or import `patchwork/scripts/sql/DevEnv.sql` to
   a blank database and rebuild the manifest and template cache if necessary).

 * Visit http://www.yoursite.example.com/dev/test/module/patchwork to make
   sure that everything works as it should.

 * Visit http://www.yoursite.example.com/ and verify that you can see
   the example content from SilverStripe.

You should now be ready to start the actual work on the project.

## Usage Overview

patchwork provides a bunch of features which are very nice to have,
you can find some simple example for the most interesting parts below.

### Constraints for DataObjects.

Constraints can be specified for has_one-relations for DataObjects.
It is possible to use constraints for Versioned DataObjects too, provided
that both sides of the relation are Versioned and that only the stages
"Stage" and "Live" are used.

		class PageWidget extends DataObject {
			private static $db = array(
				'Title' => 'Text',
			);
			private static $has_one = array(
				'Page' => 'Page',
			);
			private static $constraints = array(
				'Page' => 'on delete cascade'
			);
        }

### Automatic publishing and unpublishing for related Versioned DataObjects.

Making sure that Versioned DataObjects connected to for example a Page
through a has_one-relation are published and unpublished when their
referenced Page will usually require quite a bit of code. Autoversioned
allows Versioned DataObjects sync their staging with their owner.

		class PageWidget extends DataObject {
			private static $db = array(
				'Title' => 'Text',
			);
			private static $has_one = array(
				'Page' => 'Page',
			);
			private static $autoversioned = array(
				'Page' => true
			);
			private static $extensions = array(
				"Versioned('Stage', 'Live')",
				"Autoversioned",
				"VersionedHooks",
				"VersionedStatus"
			);
        }

### A simple scheduled job abstraction for delayed execution of tasks.

It is often useful to be able to delay the execution of certain things. To
make this possible patchwork provides `ScheduledJob` and `DeferrableBuildTask`.
All deferrable tasks should inherit `DeferrableBuildTask` and they are
scheduled through `ScheduledJob::register(...)`.

`StagePageTask` and `UpdateMetaLabelsTask` are two examples on how deferrable
tasks can be implemented.

Remember to set up a cron tab entry for patchwork so that the scheduled jobs
will actually run. It is possible to run ScheduledJobTask either through a
HTTP request or using php-cli.

 * HTTP request: `wget http://www.example.com/dev/tasks/ScheduledJobTask`
 * Command line: `php framework/cli-script.php dev/tasks/ScheduledJobTask`

### Basic CAPTCHA fields for forms and userforms.

A few simple CAPTCHA fields are available. Do note that they are very
simplistic and not very accessible.

### A generalization of the PageHolder concept.

Every SilverStripe developer will be familiar with the PageHolder concept
which is quite common in SilverStripe. An example could be:

 * `NewsHolder`
   * `NewsPage`
   * `NewsPage`
   * `NewsPage`

This solution is very neat but comes with a few important limitations.
Usually it is only possible to create NewsPages under NewsHolder, which
can create problems when you want to do something out of the ordinary,
like for example have a userform as the latest news article. And even
if NewsHolder is updated to accept more children, there could arise issues
if the PageTypes lacks the necessary fields to display the summary on
NewsHolder.

patchwork aims to solve these kind of problems by introducing `PageAggregate`,
which is basically a PageHolder which can find and display all kinds of
Page types. `PageAggregate` is quite powerful and can work with the SiteTree,
tags and categories or a specific search term to find the pages it should
display. It can handle news sections and blogs out-of-the-box.

### Carousels made easy

`PageContentItem` makes implementing carousels and similar functionality
a breeze.

		class Page extends SiteTree {
			private static $has_many = array(
				'CarouselItems' => 'PageCarouselItem'
			);
			public function getCMSFields() {
				$fields = parent::getCMSFields();
				PageCarouselItem::addCMSFieldsTo($this, $fields, $this->CarouselItems());
				return $fields;
			}
		}
		class PageCarouselItem extends PageContentItem {
		}

It is then possible to use `PageCarousel.ss` in the template to render
a standard Bootstrap carousel.

		<% include PageCarousel ID='my-cool-carousel', Items=$CarouselItems %>

### Template goodies

patchwork provides a number useful template methods.

 * `$EnvironmentType` - get the current environment type (dev, test or live).
 * `$DateCacheBuster` - add to an URL to get a time() based cache buster.
 * `$MtimeCacheBuster` - get a file_mtime cache buster for a file.
 * `$Year` - get the current year.
 * `$Copyright` - print a copyright statement (including the current year).
 * `$PatchworkNavigator` - a slightly modified version of the default
   SilverStripe navigator.

### Custom javascript for specific page types

It is often necessary to write javascript specific for a certain page type
which does not have to be executed unless the page type is relevant. To make
this trivial, patchwork will try to execute two callbacks for each page load:

 * `function PageType_ready($) { ... }`
 * `function PageType_load($) { ... }`

`PageType_ready` will be called on `$(document).ready()`, `PageType_load` will
be called on `$(window).load()`. `PageType` should obviously be replaced with
the name of the page type. For example, if we have `HomePage`, then the
callbacks would be `HomePage_ready` and `HomePage_load`. It is not necessary to
implement empty callbacks for each page type, the callback is only called if
it exists.


text:
"""
    flask_security.decorators
    ~~~~~~~~~~~~~~~~~~~~~~~~~

    Flask-Security decorators module

    :copyright: (c) 2012 by Matt Wright.
    :license: MIT, see LICENSE for more details.
"""

from collections import namedtuple
from functools import wraps

from flask import current_app, Response, request, redirect, _request_ctx_stack
from flask_login import current_user, login_required  # pragma: no flakes
from flask_principal import RoleNeed, Permission, Identity, identity_changed
from werkzeug.local import LocalProxy

from . import utils

# Convenient references
_security = LocalProxy(lambda: current_app.extensions['security'])

_default_unauthorized_html = """

Unauthorized

The server could not verify that you are authorized to access the URL
    requested. You either supplied the wrong credentials (e.g. a bad password),
    or your browser doesn't understand how to supply the credentials required.

    """

BasicAuth = namedtuple('BasicAuth', 'username, password')

def _get_unauthorized_response(text=None, headers=None):
    text = text or _default_unauthorized_html
    headers = headers or {}
    return Response(text, 401, headers)

def _get_unauthorized_view():
    cv = utils.get_url(utils.config_value('UNAUTHORIZED_VIEW'))
    utils.do_flash(*utils.get_message('UNAUTHORIZED'))
    return redirect(cv or request.referrer or '/')

def _check_token():
    header_key = _security.token_authentication_header
    args_key = _security.token_authentication_key
    header_token = request.headers.get(header_key, None)
    token = request.args.get(args_key, header_token)
    if request.get_json(silent=True):
        if not isinstance(request.json, list):
            token = request.json.get(args_key, token)

    user = _security.login_manager.token_callback(token)

    if user and user.is_authenticated:
        app = current_app._get_current_object()
        _request_ctx_stack.top.user = user
        identity_changed.send(app, identity=Identity(user.id))
        return True

    return False

def _check_http_auth():
    auth = request.authorization or BasicAuth(username=None, password=None)
    user = _security.datastore.find_user(email=auth.username)

    if user and utils.verify_and_update_password(auth.password, user):
        _security.datastore.commit()
        app = current_app._get_current_object()
        _request_ctx_stack.top.user = user
        identity_changed.send(app, identity=Identity(user.id))
        return True

    return False

def http_auth_required(realm):
    """Decorator that protects endpoints using Basic HTTP authentication.
    The username should be set to the user's email address.

    :param realm: optional realm name"""

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            if _check_http_auth():
                return fn(*args, **kwargs)
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                r = _security.default_http_auth_realm if callable(realm) else realm
                h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
                return _get_unauthorized_response(headers=h)
        return wrapper

    if callable(realm):
        return decorator(realm)
    return decorator

def auth_token_required(fn):
    """Decorator that protects endpoints using token authentication. The token
    should be added to the request by the client by using a query string
    variable with a name equal to the configuration value of
    `SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
    the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER`
    """

    @wraps(fn)
    def decorated(*args, **kwargs):
        if _check_token():
            return fn(*args, **kwargs)
        if _security._unauthorized_callback:
            return _security._unauthorized_callback()
        else:
            return _get_unauthorized_response()
    return decorated

def auth_required(*auth_methods):
    """
    Decorator that protects enpoints through multiple mechanisms
    Example::

        @app.route('/dashboard')
        @auth_required('token', 'session')
        def dashboard():
            return 'Dashboard'

    :param auth_methods: Specified mechanisms.
    """
    login_mechanisms = {
        'token': lambda: _check_token(),
        'basic': lambda: _check_http_auth(),
        'session': lambda: current_user.is_authenticated
    }

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            h = {}
            mechanisms = [(method, login_mechanisms.get(method)) for method in auth_methods]
            for method, mechanism in mechanisms:
                if mechanism and mechanism():
                    return fn(*args, **kwargs)
                elif method == 'basic':
                    r = _security.default_http_auth_realm
                    h['WWW-Authenticate'] = 'Basic realm="%s"' % r
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                return _get_unauthorized_response(headers=h)
        return decorated_view
    return wrapper

def roles_required(*roles):
    """Decorator which specifies that a user must have all the specified roles.
    Example::

        @app.route('/dashboard')
        @roles_required('admin', 'editor')
        def dashboard():
            return 'Dashboard'

    The current user must have both the `admin` role and `editor` role in order
    to view the page.

    :param args: The required roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perms = [Permission(RoleNeed(role)) for role in roles]
            for perm in perms:
                if not perm.can():
                    if _security._unauthorized_callback:
                        return _security._unauthorized_callback()
                    else:
                        return _get_unauthorized_view()
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper

def roles_accepted(*roles):
    """Decorator which specifies that a user must have at least one of the
    specified roles. Example::

        @app.route('/create_post')
        @roles_accepted('editor', 'author')
        def create_post():
            return 'Create Post'

    The current user must have either the `editor` role or `author` role in
    order to view the page.

    :param args: The possible roles.
    """
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = Permission(*[RoleNeed(role) for role in roles])
            if perm.can():
                return fn(*args, **kwargs)
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                return _get_unauthorized_view()
        return decorated_view
    return wrapper

def anonymous_user_required(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if current_user.is_authenticated:
            return redirect(utils.get_url(_security.post_login_view))
        return f(*args, **kwargs)
    return wrapper


text:
package net.microscraper.client.applet;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;

import net.caustic.client.Scraper;

public class ScrapeRunnable implements Runnable {
	private final Scraper client;
	private final String instructionURI;
	private final Hashtable<String, String> defaults;

	public ScrapeRunnable(Scraper client, String instructionURI, Hashtable<String, String> defaults) {
		this.client = client;
		this.instructionURI = instructionURI;
		this.defaults = defaults;
	}

	@Override
	public void run() {
		try {
			AccessController.doPrivileged(new ScrapeAction());
		} catch(Throwable e) {
			//client.e(e);
		}
	}

	private class ScrapeAction implements PrivilegedAction<Void> {
		public Void run() {
			try {
				//client.scrapeWithURI(instructionURI, formEncodedDefaults);
				client.scrapeFromUri(instructionURI, defaults);
			} catch(Throwable e) {
				//client.e(e);
			}
			return null;
		}
	}
}


text:
package expvar

import (
	"strconv"
	"testing"

	"github.com/go-kit/kit/metrics/teststat"
)

func TestCounter(t *testing.T) {
	counter := NewCounter("expvar_counter").With("label values", "not supported").(*Counter)
	value := func() float64 { f, _ := strconv.ParseFloat(counter.f.String(), 64); return f }
	if err := teststat.TestCounter(counter, value); err != nil {
		t.Fatal(err)
	}
}

func TestGauge(t *testing.T) {
	gauge := NewGauge("expvar_gauge").With("label values", "not supported").(*Gauge)
	value := func() float64 { f, _ := strconv.ParseFloat(gauge.f.String(), 64); return f }
	if err := teststat.TestGauge(gauge, value); err != nil {
		t.Fatal(err)
	}
}

func TestHistogram(t *testing.T) {
	histogram := NewHistogram("expvar_histogram", 50).With("label values", "not supported").(*Histogram)
	quantiles := func() (float64, float64, float64, float64) {
		p50, _ := strconv.ParseFloat(histogram.p50.String(), 64)
		p90, _ := strconv.ParseFloat(histogram.p90.String(), 64)
		p95, _ := strconv.ParseFloat(histogram.p95.String(), 64)
		p99, _ := strconv.ParseFloat(histogram.p99.String(), 64)
		return p50, p90, p95, p99
	}
	if err := teststat.TestHistogram(histogram, quantiles, 0.01); err != nil {
		t.Fatal(err)
	}
}


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, user-scalable=no,
		shrink-to-fit=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />

	<title>Cordova Basic</title>

		<button class="back" onclick="history.back()">

		</button>

Basic Cordova

This app demonstrates basic Cordova functionality. For the app to work,
		you need to run it in the Evothings Client App, or build a native
		Cordova app yourself.

	<button class="blue" onclick="messagebox('Hello Evothings!')">
		NATIVE DIALOG
	</button>

	<button class="yellow" onclick="navigator.notification.vibrate(1000)">
		VIBRATE
	</button>

Compass

Status: Waiting for compass.


text:
    export default function(server) {
      server.createList('animal', 10);
      server.loadFixtures('groups');
      server.loadFixtures('things');
      server.loadFixtures('animal-groups');
    }


text:
using Microsoft.AspNet.Builder;
using Microsoft.Data.Entity;
using Barber.Models;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Configuration;

namespace Barber
{
    public class Startup
    {
        public IConfiguration Configuration { get; set; }

        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            // Setup configuration sources.
            var builder = new ConfigurationBuilder()
                .AddJsonFile("config.json");

            //builder.AddEntityFramework(options => options.UseSqlServer(config["Data:DefaultConnection:ConnectionString"]));
            builder.AddEnvironmentVariables();
            Configuration = builder.Build();

        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<BarberContext>(options => {
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
            });

            services.AddMvc()
                .AddJsonOptions(options => {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseDefaultFiles(new Microsoft.AspNet.StaticFiles.DefaultFilesOptions() { DefaultFileNames = new[] { "index.html" } });
            app.UseMvc();
        }

        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}


text:
layout: piece
title: Slowly
author: Yuan Changming
date: 2016-04-10 17:00:00
category: april2016
---
Let us take all the long time we need

To wake up from our overdue dreams

Get out of the bed, and stretch our

Limbs as far as possible for a new morning

Let us take all the long time we need

To listen to the first song of the birds

Watch the rise of this summer sun, feel

The breeze combing each tree with tenderness

Let us take all the long time we need

To enjoy being together with our beloved

Exchange a smile so that they can stay with

Us just a few seconds or even minutes longer

Yes, let's take all the long time we need

To drink this tea, to chat about this weather

To look back at the road we have travelled along

To think, to cry, and to die in lingering twilight


text:
#ifndef IVW_PYINVIWO_H
#define IVW_PYINVIWO_H

#include <modules/python3/python3moduledefine.h>
#include <modules/python3/pyinviwoobserver.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/singleton.h>
#include <inviwo/core/util/observer.h>
#include <modules/python3/pythonincluder.h>

// #ifndef PyObject_HEAD
// struct PyObject;
// #endif

namespace inviwo {
class PyModule;
class IVW_MODULE_PYTHON3_API PyInviwo : public Singleton<PyInviwo>,
                                        public Observable<PyInviwoObserver> {
public:
    PyInviwo();
    virtual ~PyInviwo();

    /**
    * \brief initialized python modules
    *
    * Initializes given python module. Can be used called from outside this python module.
    *
    * @param PyModule *pyModule class containing information and methods for python module
    */
    void registerPyModule(PyModule* pyModule);

    /**
    * \brief add a path for where ptyhon scripts will look for modules
    *
    * add a path for where ptyhon scripts will look for modules
    *
    * @param const std::string& path path to folder
    * @param PyMethodDef * module static array of registered classes in a module
    */
    void addModulePath(const std::string& path);
    PyObject* getMainDictionary() { return mainDict_; }
    PyObject* getModulesDictionary() { return modulesDict_; }

    std::vector<PyModule*> getAllPythonModules() { return registeredModules_; }

    void importModule(const std::string& moduleName);

protected:
    void initPythonCInterface();
    void initDefaultInterfaces();
    void initOutputRedirector();

private:
    bool isInit_;
    PyModule* inviwoPyModule_;
    PyModule* inviwoInternalPyModule_;

    PyObject* mainDict_;
    PyObject* modulesDict_;

    std::vector<PyModule*> registeredModules_;
};

}  // namespace

#endif  // IVW_PYINVIWO_H


text:
.codeField {
  font-family: Consolas, monaco, monospace !important;
}


text:
from __future__ import unicode_literals

import django.contrib.auth.models
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0003_user_junior'),
    ]

    operations = [
        migrations.AlterModelManagers(
            name='user',
            managers=[
                ('objects', django.contrib.auth.models.UserManager()),
            ],
        ),
    ]


text:
// -*- C++ -*-

//=============================================================================
/**
 * @file  Storable_Naming_Context_ReaderWriter.cpp
 *
 * $Id: Storable_Naming_Context_ReaderWriter.cpp 2179 2013-05-28 22:16:51Z mesnierp $
 *
 * @author Marina Spivak <marina@cs.wustl.edu>
 * @author Byron Harris <harrisb@ociweb.com>
 */
//=============================================================================

#include "orbsvcs/Naming/Storable_Naming_Context_ReaderWriter.h"
#include "orbsvcs/Naming/Storable_Naming_Context.h"
#include "orbsvcs/Naming/Storable.h"

#include "tao/Storable_Base.h"

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

TAO_Storable_Naming_Context_ReaderWriter::
TAO_Storable_Naming_Context_ReaderWriter (TAO::Storable_Base & stream)
  : stream_(stream)
{
}

void
TAO_Storable_Naming_Context_ReaderWriter::write (TAO_Storable_Naming_Context & context)
{
  TAO_NS_Persistence_Header header;

  header.size (static_cast<unsigned int> (context.storable_context_->current_size()));
  header.destroyed (context.destroyed_);

  this->write_header(header);

  if (0u == header.size ())
    return;

  ACE_Hash_Map_Iterator<TAO_Storable_ExtId,TAO_Storable_IntId,
                        ACE_Null_Mutex> it = context.storable_context_->map().begin();
  ACE_Hash_Map_Iterator<TAO_Storable_ExtId,TAO_Storable_IntId,
                        ACE_Null_Mutex> itend = context.storable_context_->map().end();

  ACE_Hash_Map_Entry<TAO_Storable_ExtId,TAO_Storable_IntId> ent = *it;

  while (!(it == itend))
  {
    TAO_NS_Persistence_Record record;

    ACE_CString name;
    CosNaming::BindingType bt = (*it).int_id_.type_;
    if (bt ==  CosNaming::ncontext)
      {
        CORBA::Object_var
          obj = context.orb_->string_to_object ((*it).int_id_.ref_.in ());
        if (obj->_is_collocated ())
          {
            // This is a local (i.e. non federated context) we therefore
            // store only the ObjectID (persistence filename) for the object.

            // The driving force behind storing ObjectIDs rather than IORs for
            // local contexts is to provide for a redundant naming service.
            // That is, a naming service that runs simultaneously on multiple
            // machines sharing a file system. It allows multiple redundant
            // copies to be started and stopped independently.
            // The original target platform was Tru64 Clusters where there was
            // a cluster address. In that scenario, clients may get different
            // servers on each request, hence the requirement to keep
            // synchronized to the disk. It also works on non-cluster system
            // where the client picks one of the redundant servers and uses it,
            // while other systems can pick different servers. (However in this
            // scenario, if a server fails and a client must pick a new server,
            // that client may not use any saved context IORs, instead starting
            // from the root to resolve names. So this latter mode is not quite
            // transparent to clients.) [Rich Seibel (seibel_r) of ociweb.com]

            PortableServer::ObjectId_var
              oid = context.poa_->reference_to_id (obj.in ());
            CORBA::String_var
              nm = PortableServer::ObjectId_to_string (oid.in ());
            const char
              *newname = nm.in ();
            name.set (newname); // The local ObjectID (persistance filename)
            record.type (TAO_NS_Persistence_Record::LOCAL_NCONTEXT);
          }
        else
          {
            // Since this is a foreign (federated) context, we can not store
            // the objectID (because it isn't in our storage), if we did, when
            // we restore, we would end up either not finding a permanent
            // record (and thus ending up incorrectly assuming the context was
            // destroyed) or loading another context altogether (just because
            // the contexts shares its objectID filename which is very likely).
            // [Simon Massey  (sma) of prismtech.com]

            name.set ((*it).int_id_.ref_.in ()); // The federated context IOR
            record.type (TAO_NS_Persistence_Record::REMOTE_NCONTEXT);
          }
      }
    else // if (bt == CosNaming::nobject) // shouldn't be any other, can there?
      {
        name.set ((*it).int_id_.ref_.in ()); // The non-context object IOR
        record.type (TAO_NS_Persistence_Record::OBJREF);
      }
    record.ref(name);

    const char *myid = (*it).ext_id_.id();
    ACE_CString id(myid);
    record.id(id);

    const char *mykind = (*it).ext_id_.kind();
    ACE_CString kind(mykind);
    record.kind(kind);

    write_record (record);
    it.advance();
  }

  context.write_occurred_ = 1;
}

int
TAO_Storable_Naming_Context_ReaderWriter::read (TAO_Storable_Naming_Context & context)
{
  // assume file already open for reading
  TAO_Storable_Bindings_Map *bindings_map;

  // create the new bindings map
  ACE_NEW_THROW_EX (bindings_map,
                    TAO_Storable_Bindings_Map (context.hash_table_size_, context.orb_.in()),
                    CORBA::NO_MEMORY ());

  // get the data for this bindings map from the file

  TAO_NS_Persistence_Header header;
  TAO_NS_Persistence_Record record;

  // we are only using the size from this header
  this->read_header(header);

  // reset the destroyed flag
  context.destroyed_ = header.destroyed();

  // read in the data for the map
  for (unsigned int i= 0u; i<header.size(); ++i)
    {
      this->read_record(record);

      if (TAO_NS_Persistence_Record::LOCAL_NCONTEXT == record.type ())
        {
          PortableServer::ObjectId_var
            id = PortableServer::string_to_ObjectId (record.ref ().c_str ());
          const char
            *intf = context.interface_->_interface_repository_id ();
          CORBA::Object_var
            objref = context.poa_->create_reference_with_id (id.in (), intf);
          bindings_map->bind ( record.id ().c_str (),
                               record.kind ().c_str (),
                               objref.in (),
                               CosNaming::ncontext );
        }
      else
        {
          CORBA::Object_var
            objref = context.orb_->string_to_object (record.ref ().c_str ());
          bindings_map->bind ( record.id ().c_str (),
                               record.kind ().c_str (),
                               objref.in (),
                               ((TAO_NS_Persistence_Record::REMOTE_NCONTEXT == record.type ())
                                ? CosNaming::ncontext    // REMOTE_NCONTEXT
                                : CosNaming::nobject )); // OBJREF
        }
    }
  context.storable_context_ = bindings_map;
  context.context_ = context.storable_context_;
  if (stream_.good ())
    return 0;
  else
    return -1;
}

void
TAO_Storable_Naming_Context_ReaderWriter::write_header (const TAO_NS_Persistence_Header & header)
{
  stream_.rewind();
  stream_ << header.size();
  stream_ << header.destroyed();
  stream_.flush();
}
void
TAO_Storable_Naming_Context_ReaderWriter::read_header (TAO_NS_Persistence_Header & header)
{
  unsigned int size;
  int destroyed;

  stream_.rewind();

  stream_ >> size;
  header.size(size);

  stream_ >> destroyed;
  header.destroyed(destroyed);
}

void
TAO_Storable_Naming_Context_ReaderWriter::write_record (const TAO_NS_Persistence_Record & record)
{
  TAO_NS_Persistence_Record::Record_Type type = record.type();
  stream_ << type;

  stream_ << record.id();
  stream_ << record.kind();
  stream_ << record.ref();

  stream_.flush();
}

void
TAO_Storable_Naming_Context_ReaderWriter::read_record (TAO_NS_Persistence_Record & record)
{
  int temp_type_in;
  stream_ >> temp_type_in;
  TAO_NS_Persistence_Record::Record_Type type =
    (TAO_NS_Persistence_Record::Record_Type) temp_type_in;
  record.type (type);

  ACE_CString record_id;
  stream_ >> record_id;
  record.id (record_id);

  ACE_CString record_kind;
  stream_ >> record_kind;
  record.kind (record_kind);

  ACE_CString record_ref;
  stream_ >> record_ref;
  record.ref (record_ref);
}

void
TAO_Storable_Naming_Context_ReaderWriter::write_global (const TAO_NS_Persistence_Global & global)
{
  stream_.rewind();
  stream_ << global.counter();
  stream_.flush();
}

void
TAO_Storable_Naming_Context_ReaderWriter::read_global (TAO_NS_Persistence_Global
                                                       & global)
{
  unsigned int counter = 0;

  stream_.rewind();
  // We expect an exception to be thrown with EOF state if the file is empty.
  try
    {
      stream_ >> counter;
    }
  catch (TAO::Storable_Read_Exception &ex)
    {
      if (ex.get_state() != TAO::Storable_Base::goodbit &&
          ex.get_state() != TAO::Storable_Base::eofbit)
        throw CORBA::INTERNAL ();
    }

  global.counter(counter);

}

TAO_END_VERSIONED_NAMESPACE_DECL


text: Rails.application.config.session_store :cookie_store, key: '_wicd_session'


text:
package org.bitcoins.wallet.models

import org.bitcoins.core.api.wallet.db.ScriptPubKeyDb
import org.bitcoins.core.protocol.script._
import org.bitcoins.core.script.constant.ScriptNumber
import org.bitcoins.core.script.reserved._
import org.bitcoins.crypto.{DoubleSha256Digest, ECPublicKey}
import org.bitcoins.testkit.fixtures.WalletDAOFixture
import scodec.bits.ByteVector

import java.sql.SQLException

class ScriptPubKeyDAOTest extends WalletDAOFixture {
  behavior of "ScriptPubKeyDAO"

  it must "be able to store and load spks" in { daos =>
    val scriptPubKeyDAO = daos.scriptPubKeyDAO

    val multisig = MultiSignatureScriptPubKey(
      2,
      Vector(ECPublicKey.freshPublicKey, ECPublicKey.freshPublicKey))

    val pkh = P2PKHScriptPubKey(ECPublicKey.freshPublicKey)

    val raw1 = RawScriptPubKey.fromAsmBytes(pkh.asmBytes)

    val raw2 = RawScriptPubKey.fromAsmBytes(multisig.asmBytes)

    val cltv = CLTVScriptPubKey(ScriptNumber.one, pkh)

    val spks = Vector(
      EmptyScriptPubKey,
      pkh,
      multisig,
      P2SHScriptPubKey(multisig),
      P2PKScriptPubKey(ECPublicKey.freshPublicKey),
      cltv,
      CSVScriptPubKey(ScriptNumber.one, pkh),
      NonStandardIfConditionalScriptPubKey(raw1, raw2),
      MultiSignatureWithTimeoutScriptPubKey(multisig, cltv),
      NonStandardNotIfConditionalScriptPubKey(raw1, raw2),
      P2PKWithTimeoutScriptPubKey(ECPublicKey.freshPublicKey,
                                  ScriptNumber.one,
                                  ECPublicKey.freshPublicKey),
      NonStandardScriptPubKey(Seq(OP_NOP)),
      P2WPKHWitnessSPKV0(ECPublicKey.freshPublicKey),
      P2WSHWitnessSPKV0(pkh),
      WitnessCommitment(
        DoubleSha256Digest(
          "0000000000000000000000000000000000000000000000000000000000000000"))
    ).map(spk => ScriptPubKeyDb(spk))

    for {
      _ <- scriptPubKeyDAO.createAll(spks)
      fromDb <- scriptPubKeyDAO.findAll()
    } yield {
      val actual = fromDb.sortBy(_.id)
      assert(actual.size == spks.size)
      assert(actual.map(_.scriptPubKey) == spks.map(_.scriptPubKey))
    }

  }

  it must "fail inserting non unique scripts" in { daos =>
    val scriptPubKeyDAO = daos.scriptPubKeyDAO
    val pkh = P2PKHScriptPubKey(ECPublicKey.freshPublicKey)
    val insertF = for {
      _ <- scriptPubKeyDAO.create(ScriptPubKeyDb(pkh))
      _ <- scriptPubKeyDAO.create(ScriptPubKeyDb(pkh))
    } yield {
      ()
    }
    recoverToSucceededIf[SQLException](insertF)
  }

  it must "be able to create new scripts if they don't exist" in { daos =>
    val scriptPubKeyDAO = daos.scriptPubKeyDAO
    val pkh = P2PKHScriptPubKey(ECPublicKey.freshPublicKey)
    for {
      db1 <- scriptPubKeyDAO.createIfNotExists(ScriptPubKeyDb(pkh))
      db2 <- scriptPubKeyDAO.createIfNotExists(ScriptPubKeyDb(pkh))
    } yield {
      assert(db1 == db2)
    }
  }

  it must "find a scriptPubKey" in { daos =>
    val scriptPubKeyDAO = daos.scriptPubKeyDAO
    val pkh = P2PKHScriptPubKey(ECPublicKey.freshPublicKey)
    val notInDb = P2PKHScriptPubKey(ECPublicKey.freshPublicKey)
    for {
      _ <- scriptPubKeyDAO.createIfNotExists(ScriptPubKeyDb(pkh))
      found <- scriptPubKeyDAO.findScriptPubKeys(Vector(pkh, notInDb))
    } yield {
      assert(found.length == 1)
      assert(found.head.scriptPubKey == pkh)
    }
  }

  it must "be able to store and find big spks" in { daos =>
    val scriptPubKeyDAO = daos.scriptPubKeyDAO

    val Size = 840011 // the size of the biggest script on testnet

    val big1 = RawScriptPubKey.fromAsmBytes(ByteVector.fill(Size)(0x55))
    assert(big1.bytes.size == Size + 5)

    val big2 = RawScriptPubKey.fromAsmBytes(ByteVector.fill(Size * 2)(0xaa))
    assert(big2.bytes.size == Size * 2 + 5)

    val multisig = MultiSignatureScriptPubKey(
      2,
      Vector(ECPublicKey.freshPublicKey, ECPublicKey.freshPublicKey))

    val pkh = P2PKHScriptPubKey(ECPublicKey.freshPublicKey)

    val spks = Vector(
      EmptyScriptPubKey,
      pkh,
      big1,
      multisig,
      big2
    ).map(spk => ScriptPubKeyDb(spk))

    for {
      _ <- scriptPubKeyDAO.createAll(spks)
      fromDb <- scriptPubKeyDAO.findAll()
      fromDb1 <- scriptPubKeyDAO.findScriptPubKeys(fromDb.map(_.scriptPubKey))
    } yield {
      assert(fromDb.sortBy(_.id) == fromDb1.sortBy(_.id))
      val actual = fromDb1.sortBy(_.id)
      assert(actual.size == spks.size)
      assert(actual.map(_.scriptPubKey) == spks.map(_.scriptPubKey))
    }
  }
}


text:
package com.ukefu.webim.util.server.message;

public class ChatObject {
    private String userName;
    private String message;

    public ChatObject() {
    }

    public ChatObject(String userName, String message) {
        super();
        this.userName = userName;
        this.message = message;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}


text:
///////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright 1996 by Autodesk, Inc.
//
// The information contained herein is confidential, proprietary
// to Autodesk,  Inc.,  and considered a trade secret as defined
// in section 499C of the penal code of the State of California.
// Use of  this information  by  anyone  other  than  authorized
// employees of Autodesk, Inc.  is granted  only under a written
// non-disclosure agreement,  expressly  prescribing  the  scope
// and manner of such use.
//
// CREATED BY:  Jiri Kripac                     January-1-1996
//
// DESCRIPTION:
//
// Declaration of a class Plane, keeping a definition of an oriented plane in
// 3D. The plane is defined by its (unit) normal vector and parameter 'd',
// which is the signed distance of the plane from the origin of the coordinate
// system.
//
// For all points on the plane holds:
//
//   normal * point + d = 0
//
// The plane parameters are accessed via public data members 'normal' and 'd'.
//
// If the plane is invalid (cannot be constructed), the plane normal is set to
// a null vector.
//
///////////////////////////////////////////////////////////////////////////////

#include "point3d.h"

AMODELER_NAMESPACE_BEGIN

class DllImpExp Plane
{
public:

    Plane()                                 : normal(Vector3d::kNull), d(0) {}
    Plane(Vector3d nn, double dd)           : normal(nn), d(dd)             {}
    Plane(Point3d, Vector3d);
    Plane(const Point3d&, const Point3d&,  const Point3d&);
    Plane(const Point3d&, const Vector3d&, const Vector3d&);

    // Create plane from a polygon of vertices (n >=3). All polygon vertices
    // are used to calculate the plane coefficients to make the formula
    // symetrical.
    //
    Plane(const Point3d plg[], int n);

    // The plane normal is given, just calculate the 'd' parameter from all
    // polygon vertices.
    //
    Plane(const Point3d plg[], int n, const Vector3d& normal);

    Plane    operator -()                const { return Plane(-normal, -d); }
    double   dist      (Point3d p)       const { return p % normal + d; }
    Point3d  project   (const Point3d& ) const;
    Vector3d project   (const Vector3d&) const;
    Line3d   project   (const Line3d&  ) const;

    Point3d  operator* (const Line3d&  ) const;

    bool     isValid   () const { return fabs(normal.length() - 1) < epsNor(); }

    bool     isEqual   (Plane) const;

    void     orthoPlane(int& i1, int& i2)          const;
    void     orthoPlane(int& i1, int& i2, int& i3) const;

    // Public data members
    //
    Vector3d normal;
    double   d;

}; // class Plane

inline Plane::Plane(Point3d p, Vector3d norm)
  : normal(norm)
{
    normal = normal.normalize();
    d = -p % normal;
}

inline bool Plane::isEqual(Plane pla) const
{
    return normal.isEqual(pla.normal) && fabs(d-pla.d) <= epsAbs();
}

AMODELER_NAMESPACE_END
#endif


text:
package com.sixsq.slipstream.util;

import com.sixsq.slipstream.exceptions.ValidationException;
import com.sixsq.slipstream.persistence.Module;

/**
 * Utilities to manipulate the resource URLs. The methods consistently do NOT
 * have a slash at the end of the returned URLs.
 *
 * Terminology - uri: /module/<parent>/<module>/<version> - shortName: if
 * <module> = project1/image1: shortName = image1 - resourceUri: uri - version:
 * <version> - parent:
 *
 * Unit test see
 *
 * @see ModuleUriUtilTest
 *
 */
public class ModuleUriUtil {

	private static int DEFAULT_VERSION = Module.DEFAULT_VERSION;

	public static String extractShortNameFromResourceUri(String resourceUri) {
		String[] slices = resourceUri.split("/");
		int version = extractVersion(resourceUri);
		int index;
		String last = slices[slices.length - 1];
		if (version != DEFAULT_VERSION
				|| last.equals(Integer.toString(DEFAULT_VERSION))) {
			index = slices.length - 2;
		} else {
			index = slices.length - 1;
		}
		return slices[index];
	}

	public static String extractVersionLessResourceUri(String resourceUri)
			throws ValidationException {
		String parentUri = extractParentUriFromResourceUri(resourceUri);
		String shortName = extractShortNameFromResourceUri(resourceUri);
		String sep = parentUri.endsWith("/") ? "" : "/";
		return parentUri + sep + shortName;
	}

	private static int extractVersion(String resourceUri) {
		String[] slices = resourceUri.split("/");
		String last = slices[slices.length - 1];
		int version = DEFAULT_VERSION;
		try {
			version = Integer.parseInt(last);
		} catch (NumberFormatException e) {
		}
		return version;
	}

	public static int extractVersionFromResourceUri(String resourceUri) {
		return extractVersion(resourceUri);
	}

	public static String extractModuleUriFromResourceUri(String resourceUri) {
		return resourceUri;
	}

	public static String extractModuleNameFromResourceUri(String resourceUri) {

		if (Module.RESOURCE_URI_PREFIX.replace("/", "").equals(resourceUri)
				|| Module.RESOURCE_URI_PREFIX.equals(resourceUri)) {
			return "";
		}

		Integer version = extractVersion(resourceUri);
		int startIndex = (resourceUri.startsWith(Module.RESOURCE_URI_PREFIX) ? Module.RESOURCE_URI_PREFIX
				.length() : 0);

		int endIndex;
		String defaultVersionPostFix = "/" + Module.DEFAULT_VERSION;
		if (resourceUri.endsWith(defaultVersionPostFix)) {
			endIndex = resourceUri.length() - defaultVersionPostFix.length();
		} else {
			endIndex = (version != DEFAULT_VERSION) ? resourceUri.length()
					- version.toString().length() - 1 : resourceUri.length();
		}
		if (resourceUri.endsWith("/")) {
			endIndex = resourceUri.length() - 1;
		}

		return (endIndex <= startIndex ? "" : resourceUri.substring(startIndex,
				endIndex));
	}

	public static String extractParentUriFromResourceUri(String resourceUri)
			throws ValidationException {
		if (!resourceUri.startsWith(Module.RESOURCE_URI_PREFIX)) {
			throw (new ValidationException("Resource URI not starting with "
					+ Module.RESOURCE_URI_PREFIX));
		}

		String strippedResourceUri = stripDefaultVersionIfPresent(resourceUri);

		boolean hasParent = (resourceUri.split("/").length > 2);
		String moduleUrl = extractModuleUriFromResourceUri(strippedResourceUri);
		if (!hasParent) {
			return Module.RESOURCE_URI_PREFIX;
		}
		boolean hasVersion = (extractVersion(resourceUri) != -1);
		String moduleName = (hasVersion ? moduleUrl.substring(0,
				moduleUrl.lastIndexOf('/')) : strippedResourceUri);
		return moduleName.substring(0, moduleName.lastIndexOf('/'));
	}

	private static String stripDefaultVersionIfPresent(String resourceUri) {
		String defaultEnd = "/" + String.valueOf(DEFAULT_VERSION);
		String strippedResourceUri = resourceUri.endsWith(defaultEnd) ? resourceUri
				.substring(0, resourceUri.length() - defaultEnd.length())
				: resourceUri;
		return strippedResourceUri;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0.1 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Flyweight Documentation - Tutorial - Basics</title>
<link rel="stylesheet" href="../style.css" type="text/css">
<link rel="start" href="../index.html">
<link rel="prev" href="index.html">
<link rel="up" href="index.html">
<link rel="next" href="key_value.html">

Boost.Flyweight Tutorial: Basics

Boost.Flyweight tutorial

Boost.Flyweight tutorial

Key-value flyweights

Contents

Introduction

Flyweight requirements

Introduction

Suppose we are writing a massive multiplayer online game
which has to maintain hundreds of thousands or millions of instances
of the following class in memory:

struct user_entry
{
  std::string first_name;
  std::string last_name;
  int         age;
  ...
};

In this kind of environments memory resources are precious, so we are seeking
ways to make user_entry as compact as possible. Typically, there
exists a very high level of repetition of first and last names among
the community users, so an obvious optimization consists in moving
user_entry::first_name and user_entry::last_name
objects to a common repository where duplicates are avoided, and leaving
references to these inside user_entry. This is precisely what
Boost.Flyweight does in the simplest possible way for the programmer:

#include <boost/flyweight.hpp>

struct user_entry
{
  flyweight<std::string> first_name;
  flyweight<std::string> last_name;
  int                    age;
  ...
};

Boost.Flyweight automatically performs the optimization just described behind
the scenes, so that the net effect of this change is that the memory
usage of the program decreases by a factor proportional to the level of
redundancy among user names.

flyweight<std::string> behaves in many ways like
std::string; for instance, the following code works
unchanged after the redefinition of user_entry:

// flyweight<T> can be constructed in the same way as T objects can,
// even with multiple argument constructors

user_entry::user_entry(const char* f,const char* l,int a,...):
  first_name(f),
  last_name(l),
  age(a),
  ...
{}

// flyweight classes have relational operators replicating the
// semantics of the underyling type

bool same_name(const user_entry& user1,const user_entry& user2)
{
  return user1.first_name==user2.first_name &&
         user1.last_name==user2.last_name;
}

// flyweight<T> provides operator<< and operator>> internally
// forwarding to T::operator<< and T::operator>>

std::ostream& operator<<(std::ostream& os,const user_entry& user)
{
  return os<<user.first_name<<" "<<user.last_name<<" "<<user.age;
}

std::istream& operator>>(std::istream& is,user_entry& user)
{
  return is>>user.first_name>>user.last_name>>user.age;
}

Besides, flyweight<T> is convertible to
const T&, either implicitly or through the get
member function:

std::string full_name(const user_entry& user)
{
  std::string full;

  full.reserve(
    user.first_name.get().size()+   // get() returns the underlying
    user.last_name.get().size()+1); // const std::string&

  full+=user.first_name;            // implicit conversion is used here
  full+=" ";
  full+=user.last_name;

  return full;
}

The most important restriction to take into account when replacing a class
with an equivalent flyweight is the fact that flyweights are not
mutable: since several flyweight objects can share the same representation
value, modifying this value is not admissible. On the other hand, flyweight
objects can be assigned new values:

void change_name(
  user_entry& user,
  const std::string& f,const std::string& l)
{
  user.first_name=f;
  user.last_name=l;
}

In general, flyweight<T> interface is designed to make
the transition from plain T as straightforward as possible.
Check the reference for
further details on the interface of the class template flyweight.
The examples section explores
some common usage scenarios of Boost.Flyweight.

Flyweight requirements

For flyweight<T> to be instantiable, T must
be Assignable,
Equality
Comparable and must interoperate with
Boost.Hash.
The first requirement is probably met without any extra effort by the user,
not so the other two, except for the most common basic types of C++
and the standard library. Equality and hashing of T are used
internally by flyweight<T> internal factory to maintain the
common repository of unique T values referred to by the flyweight
objects. Consult the Boost.Hash documentation
section on extending
that library for custom data types.

As we have seen, equality and hash requirements on T are
imposed by the particular type of flyweight factory internally used by
flyweight<T>. We will see later how the user can customize
this factory to use equality and hash predicates other than the default,
or even switch to an entirely different kind of factory which may impose
another requirements on T, as described in the section on
configuring Boost.Flyweight.

Boost.Flyweight tutorial

Boost.Flyweight tutorial

Key-value flyweights

Revised December 2nd 2008

© Copyright 2006-2008 Joaquín M López Muñoz.
Distributed under the Boost Software
License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('workshops', '0009_merge'),
        ('workshops', '0008_auto_20150522_1304'),
    ]

    operations = [
    ]


text:
db.messages.find(
	{"headers.From": "email", "headers.To":"email"}
).count()