text:
import chai, { expect } from 'chai';
import chaiPromised from 'chai-as-promised';

chai.use(chaiPromised);

import { EventStream } from '../src/eventstream';
import { Aggregation } from '../src/aggregation';

describe('Aggregation', () => {
    describe('constructor', () => {
        it('empty', () => {
            const ag = new Aggregation();
            expect(ag.scope).to.be.undefined;
            expect(ag.events).to.be.empty;
            expect(ag.commands).to.be.empty;
        });

        it('scope', () => {
            const ag = new Aggregation('domain1');
            expect(ag.scope).to.be.equals('domain1');
            expect(ag.events).to.be.empty;
            expect(ag.commands).to.be.empty;
        });

        it('events', () => {
            const ag = new Aggregation('domain1', {
                handler1() { },
                handler2() { }
            });
            expect(ag.scope).to.be.equals('domain1');
            expect(ag.events).to.be.deep.equals(['domain1.handler1', 'domain1.handler2']);
            expect(ag.commands).to.be.empty;
        });

        it('events with duplicates', () => {
            const ag = new Aggregation('domain1', {
                handler1() { },
                handler1() { }
            });
            expect(ag.scope).to.be.equals('domain1');
            expect(ag.events).to.be.deep.equals(['domain1.handler1']);
            expect(ag.commands).to.be.empty;
        });

        it('commands', () => {
            const ag = new Aggregation('domain1', { }, {
                command1() { },
                command2() { }
            });
            expect(ag.scope).to.be.equals('domain1');
            expect(ag.events).to.be.empty;
            expect(ag.commands).to.be.deep.equals(['domain1.command1', 'domain1.command2']);
        });

        it('commands with duplicates', () => {
            const ag = new Aggregation('domain1', { }, {
                command1() { },
                command1() { }
            });
            expect(ag.scope).to.be.equals('domain1');
            expect(ag.events).to.be.empty;
            expect(ag.commands).to.be.deep.equals(['domain1.command1']);
        });
    });

    describe('aggregate', () => {
        const aggregation = new Aggregation('ag', {
            created(state, { id, title }) {
                state.id = id;
                state.title = title;
            },
            updated(state, { title }) {
                state.title = title;
            },
            failed() {
                throw new Error('failed');
            }
        });

        it('no events', () => {
            const stream = new EventStream();
            const promise = aggregation.aggregate(stream);
            stream.end();
            return expect(promise).to.eventually.deep.equals({ state: { }, version: 0});
        });

        it('single event', () => {
            const stream = new EventStream();
            const promise = aggregation.aggregate(stream);
            stream.write({ name: 'ag.created', payload: { id: 'id1', title: 'title1' } });
            stream.end();
            return expect(promise).to.eventually.deep.equals({ state: { id: 'id1', title: 'title1' }, version: 1 });
        });

        it('two order events', () => {
            const stream = new EventStream();
            const promise = aggregation.aggregate(stream);
            stream.write({ name: 'ag.created', payload: { id: 'id1', title: 'title1' } });
            stream.write({ name: 'ag.updated', payload: { id: 'id2', title: 'title2' } });
            stream.end();
            return expect(promise).to.eventually.deep.equals({ state: { id: 'id1', title: 'title2' }, version: 2 });
        });

        it('version with unhandled events', () => {
            const stream = new EventStream();
            const promise = aggregation.aggregate(stream);
            stream.write({ name: 'ag.created', payload: { id: 'id1', title: 'title1' } });
            stream.write({ name: 'ag.destroyed', payload: { } });
            stream.end();
            return expect(promise).to.eventually.deep.equals({ state: { id: 'id1', title: 'title1' }, version: 2 });
        });

        it('throw error event', () => {
            const stream = new EventStream();
            const promise = aggregation.aggregate(stream);
            stream.write({ name: 'ag.failed', payload: { } });
            stream.end();
            return expect(promise).to.eventually.rejected;
        })
    });

    describe('command', () => {
        const aggregation = new Aggregation('ag', { }, {
            create(state, { id }, emit) {
                if (!id)
                    return emit('created', { id: 'idi' });
                if (state.id === id)
                    emit('stated', { stateId: state.id });
                return emit('existed', { id });
            }
        });

        it('emit on payload and return first', () => {
            expect(aggregation.command('ag.create', {}, {})).to.deep.equals([{ name: 'ag.created', payload: { id: 'idi' } }]);
        });

        it('emit on payload and return last', () => {
            expect(aggregation.command('ag.create', { id: 'idi'}, {})).to.deep.equals([{ name: 'ag.existed', payload: { id: 'idi' } }]);
        });

        it('emit double on payload and state', () => {
            expect(aggregation.command('ag.create', { id: 'idi' }, { id: 'idi' })).to.deep.equals([
                { name: 'ag.stated', payload: { stateId: 'idi' } },
                { name: 'ag.existed', payload: { id: 'idi' } }
            ]);
        });
    });
});


text:
"""
To run checks for this app, install "ar-healthchecks" and run "manage.py check activeusers"
"""

"""
A list of apps that need to be listed in INSTALLED_APPS.
Checks raise an error if a dependency is missing
"""
CHECK_INSTALLED_APPS = [
    # 'some_dependency',
]

"""
A list of settings that need to be explicitly set in the project's settings.py.
Checks raise an error if a setting is missing
"""
REQUIRED_SETTINGS = [
    # 'FAVORITE_FOOD',
]

"""
A list of path settings which need to be set to writeable paths (e.g. pdf directories).
Checks raise an error if a path is not writeable
"""
WRITEABLE_PATHS = [
    # 'PDF_DIR',
]

"""
Non-python executables which need to be installed for this app to work properly.
Checks raise an error if a dependency is missing
"""
NON_PYTHON_DEPENDENCIES = [
    # 'ruby',
]

"""
Place custom check functions below
"""

# @register()
# def example_check(app_configs, **kwargs):
#     warnings = []
#     # ... your check logic here
#     warnings.append(
#         Warning(
#             'a warning',
#             id='myapp.W001',
#         )
#     )
#     return warnings

redpajama_set_name: RedPajamaGithub


text:
Kalabox Pantheon appserver
===================

A container that approximates the appserver used on Pantheon.

```

# docker build -t kalabox/pantheon-appserver:mytag .

FROM kalabox/nginx:v0.10.0

RUN \
  apt-get update && \
  apt-get -y install php5-cli libgmp10 libpng12-0 libltdl7 libmcrypt4 libpq5 libicu48 libxslt1.1 && \
  apt-get -y install libmagickwand5 libmagickcore5 && \
  cd /tmp && \
  curl -L -O https://github.com/phpbrew/phpbrew/raw/master/phpbrew && \
  chmod +x /tmp/phpbrew && \
  mv /tmp/phpbrew /usr/bin/phpbrew && \
  phpbrew init && \
  echo "source /root/.phpbrew/bashrc" >> /root/.bashrc && \
  ln -s /.phpbrew /root/.phpbrew && \
  apt-get update -y && \
  apt-get clean -y && \
  apt-get autoclean -y && \
  apt-get autoremove -y && \
  rm -rf /var/lib/apt/* && rm -rf && rm -rf /var/lib/cache/* && rm -rf /var/lib/log/* && rm -rf /tmp/*

RUN \
  cd /root/.phpbrew && \
  curl -L "http://github.com/kalabox/phpbrewer/releases/download/pantheon-1/php.tar.gz" | tar -zvx && \
  rm /root/start.sh

ENV PHP_VERSION 5.3.29

COPY start.sh /root/start.sh
RUN chmod +x /root/start.sh

CMD ["/root/start.sh"]

EXPOSE 80
EXPOSE 443

```


text:
/**
 * Stack - Last-In-First-Out (LIFO) list
 */

function Stack() {

}

module.exports = Stack;


text:
import re
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase

class LookupModule(LookupBase):
    # pylint: disable=too-many-branches,too-many-statements,too-many-arguments

    def run(self, terms, variables=None, regions_enabled=True, short_version=None,
            deployment_type=None, **kwargs):

        predicates = []

        if short_version is None or deployment_type is None:
            if 'openshift' not in variables:
                raise AnsibleError("This lookup module requires openshift_facts to be run prior to use")

        if deployment_type is None:
            if 'common' not in variables['openshift'] or 'deployment_type' not in variables['openshift']['common']:
                raise AnsibleError("This lookup module requires that the deployment_type be set")

            deployment_type = variables['openshift']['common']['deployment_type']

        if short_version is None:
            if 'short_version' in variables['openshift']['common']:
                short_version = variables['openshift']['common']['short_version']
            elif 'openshift_release' in variables:
                release = variables['openshift_release']
                if release.startswith('v'):
                    short_version = release[1:]
                else:
                    short_version = release
                short_version = '.'.join(short_version.split('.')[0:2])
            elif 'openshift_version' in variables:
                version = variables['openshift_version']
                short_version = '.'.join(version.split('.')[0:2])
            else:
                # pylint: disable=line-too-long
                raise AnsibleError("Either OpenShift needs to be installed or openshift_release needs to be specified")
        if deployment_type == 'origin':
            if short_version not in ['1.1', '1.2', '1.3', '1.4', '1.5', '3.6', '3.7', 'latest']:
                raise AnsibleError("Unknown short_version %s" % short_version)
        elif deployment_type == 'openshift-enterprise':
            if short_version not in ['3.1', '3.2', '3.3', '3.4', '3.5', '3.6', '3.7', 'latest']:
                raise AnsibleError("Unknown short_version %s" % short_version)
        else:
            raise AnsibleError("Unknown deployment_type %s" % deployment_type)

        if deployment_type == 'origin':
            # convert short_version to enterprise short_version
            short_version = re.sub('^1.', '3.', short_version)

        if short_version == 'latest':
            short_version = '3.7'

        # Predicates ordered according to OpenShift Origin source:
        # origin/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go

        if short_version == '3.1':
            predicates.extend([
                {'name': 'PodFitsHostPorts'},
                {'name': 'PodFitsResources'},
                {'name': 'NoDiskConflict'},
                {'name': 'MatchNodeSelector'},
            ])

        if short_version == '3.2':
            predicates.extend([
                {'name': 'PodFitsHostPorts'},
                {'name': 'PodFitsResources'},
                {'name': 'NoDiskConflict'},
                {'name': 'NoVolumeZoneConflict'},
                {'name': 'MatchNodeSelector'},
                {'name': 'MaxEBSVolumeCount'},
                {'name': 'MaxGCEPDVolumeCount'}
            ])

        if short_version == '3.3':
            predicates.extend([
                {'name': 'NoDiskConflict'},
                {'name': 'NoVolumeZoneConflict'},
                {'name': 'MaxEBSVolumeCount'},
                {'name': 'MaxGCEPDVolumeCount'},
                {'name': 'GeneralPredicates'},
                {'name': 'PodToleratesNodeTaints'},
                {'name': 'CheckNodeMemoryPressure'}
            ])

        if short_version == '3.4':
            predicates.extend([
                {'name': 'NoDiskConflict'},
                {'name': 'NoVolumeZoneConflict'},
                {'name': 'MaxEBSVolumeCount'},
                {'name': 'MaxGCEPDVolumeCount'},
                {'name': 'GeneralPredicates'},
                {'name': 'PodToleratesNodeTaints'},
                {'name': 'CheckNodeMemoryPressure'},
                {'name': 'CheckNodeDiskPressure'},
                {'name': 'MatchInterPodAffinity'}
            ])

        if short_version in ['3.5', '3.6']:
            predicates.extend([
                {'name': 'NoVolumeZoneConflict'},
                {'name': 'MaxEBSVolumeCount'},
                {'name': 'MaxGCEPDVolumeCount'},
                {'name': 'MatchInterPodAffinity'},
                {'name': 'NoDiskConflict'},
                {'name': 'GeneralPredicates'},
                {'name': 'PodToleratesNodeTaints'},
                {'name': 'CheckNodeMemoryPressure'},
                {'name': 'CheckNodeDiskPressure'},
            ])

        if short_version in ['3.7']:
            predicates.extend([
                {'name': 'NoVolumeZoneConflict'},
                {'name': 'MaxEBSVolumeCount'},
                {'name': 'MaxGCEPDVolumeCount'},
                {'name': 'MaxAzureDiskVolumeCount'},
                {'name': 'MatchInterPodAffinity'},
                {'name': 'NoDiskConflict'},
                {'name': 'GeneralPredicates'},
                {'name': 'PodToleratesNodeTaints'},
                {'name': 'CheckNodeMemoryPressure'},
                {'name': 'CheckNodeDiskPressure'},
                {'name': 'NoVolumeNodeConflict'},
            ])

        if regions_enabled:
            region_predicate = {
                'name': 'Region',
                'argument': {
                    'serviceAffinity': {
                        'labels': ['region']
                    }
                }
            }
            predicates.append(region_predicate)

        return predicates


text:
> This is executed at your __Workstation__

Please make sure to execute all the steps found under this page and under the following pages as part of Drone Software Development Environment:

- PX4
- JMAVSim
- Ardupilot
- SITL Simulator
- DroneKit SITL
- QGroundControl
- MAVLink
- OpenCV
- Git Source Code Management

## Common Setup

# Sudoers

In case you are not "Sudoer"

```sh
user@workstation:~$ sudo adduser <user> sudo
user@workstation:~$ sudo usermod -a -G sudo <user>
```

```sh
user@workstation:~$ sudo nano /etc/sudoers
...
user    ALL=(ALL:ALL) ALL
...
```

# Packages

```sh
user@workstation:~$ sudo apt update
user@workstation:~$ sudo apt upgrade
user@workstation:~$ sudo apt install git
user@workstation:~$ sudo apt install unzip
user@workstation:~$ sudo apt install build-essential
```

# Packages :: Pip

```sh
user@workstation:~$ sudo apt install python-pip --upgrade
user@workstation:~$ pip install --upgrade pip
user@workstation:~$ sudo pip install virtualenv virtualenvwrapper
user@workstation:~$ sudo rm -rf ~/.cache/pip
user@workstation:~$ nano ~/.bashrc
# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
user@workstation:~$ source ~/.bashrc
user@workstation:~$ mkvirtualenv cv -p python3
(cv) user@workstation:~$ exit
```


text: I am a result containing a collection.


text:
package org.factcenter.fastgc.inchworm;

import org.factcenter.fastgc.YaoGC.Circuit;
import org.factcenter.fastgc.YaoGC.CircuitGlobals;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import test.categories.Slow;

import java.math.BigInteger;
import java.util.concurrent.Future;

import static org.junit.Assert.assertEquals;

public class UNMUX_K_NTest extends GenericOpTest {

    static class MuxParams {
        int blockSize; // K
        int numBlocks; // N
        int indexSize; // N <= 2^indexSize

        MuxParams(int blockSize, int numBlocks,  int indexSize) {
            this.blockSize = blockSize;
            this.numBlocks = numBlocks;
            this.indexSize = indexSize;
        }
    }

	@Override
    Circuit getTestCircuit(CircuitGlobals globals, boolean serverMode) {
		return null; // unused.
	}

    @Override
    Circuit getTestCircuit(CircuitGlobals globals, boolean serverMode, Object param) {
        MuxParams muxParams = (MuxParams) param;
        return new UNMUX_K_N(globals, muxParams.blockSize, muxParams.numBlocks, muxParams.indexSize);
    }

	@Override
	int getNumberOfInputs() {
		return 0; // unused
	}

    @Override
    int getNumberOfInputs(Object param) {
        MuxParams muxParams = (MuxParams) param;
        return (muxParams.blockSize * muxParams.numBlocks + muxParams.blockSize + muxParams.indexSize) / 2;
    }

    public void testRandom(int repeatCount, int blockSize, int numBlocks, int indexSize) throws Exception {
        MuxParams p = new MuxParams(blockSize, numBlocks, indexSize);

        int dataBits = blockSize * numBlocks;

        int partyBits = getNumberOfInputs(p);

        BigInteger mask = BigInteger.ONE.shiftLeft(partyBits).subtract(BigInteger.ONE);

        BigInteger blockMask = BigInteger.ONE.shiftLeft(blockSize).subtract(BigInteger.ONE);

        for (int i = 0; i < repeatCount; i++) {
            BigInteger randData = new BigInteger(dataBits, rand);
            BigInteger newBlock = new BigInteger(blockSize, rand);

            int controlIdx = rand.nextInt(numBlocks);
            BigInteger control = BigInteger.valueOf(controlIdx);

            BigInteger completeData = control.shiftLeft(blockSize).or(newBlock).shiftLeft(dataBits).or(randData);

            BigInteger clientData = completeData.shiftRight(partyBits);
            BigInteger serverData = completeData.and(mask);

            Future<BigInteger> clientThread = runClient(clientData, p);
            BigInteger result = runServer(serverData, p);
            clientThread.get();

            BigInteger expected = randData.andNot(blockMask.shiftLeft(controlIdx * blockSize)).
                    or(newBlock.shiftLeft(controlIdx * blockSize));

//            logger.debug("{}: complete=0x{} ({},0x{},0x{}), result=0x{}", i, completeData.toString(16),
//                    controlIdx, newBlock.toString(16), randData.toString(16), result.toString(16));
            assertEquals("" + i + ": x=0x" + completeData.toString(16), expected, result);

        }
    }

//    @Test
//    public void test_1024_16_4() throws Exception {
//        testRandom(5, 1024, 16, 4);
//    }
//
//    @Test
//    public void test_1024_8_4() throws Exception {
//        testRandom(5, 1024, 8, 4);
//    }
//
//    @Test
//    public void test_32_256_8() throws Exception {
//        testRandom(5, 32, 256, 8);
//    }

    @Test
    public void test_8_4_2() throws Exception {
        testRandom(5, 8, 4, 2);
   }

    @Test
    public void test_8_64_6() throws Exception {
        testRandom(5, 8, 64, 6);
    }

    @Test
    @Category({Slow.class})
    public void test_128_256_8() throws Exception {
        testRandom(5, 128, 256, 8);
    }

}


text:
function git_get_branch() {
  git symbolic-ref --short HEAD
}

# Show the commit message of the ref specified in argument
function git_commit_msg() {
  git show -s --pretty=format:%B "$@"
}

# Extract the release candidate number from the git notes
function get_release_candidate() {
  git notes --ref=release-candidate show "$@" 2>/dev/null | xargs echo || true
}

# Extract the release name from the git notes
function get_release_name() {
  git notes --ref=release show "$@" 2>/dev/null | xargs echo || true
}

# Returns the info from the branch of the release. It is the current branch
# but it errors out if the current branch is not a release branch. This
# method returns the tag of the release and the number of the current
# candidate in this release.
function get_release_branch() {
  local branch_name=$(git_get_branch)
  if [ -z "$(get_release_name)" -o -z "$(get_release_candidate)" ]; then
    echo "Not a release branch: ${branch_name}." >&2
    exit 1
  fi
  echo "${branch_name}"
}


text:
<?php namespace TeamAte\Ccrezqs\Models;

use Auth;
use Model;

/**
 * Model
 */
class Dog extends Model
{
    use \October\Rain\Database\Traits\Validation;

    /*
     * Validation
     */
    public $rules = [
    ];

    protected $jsonable = ['medical_info', 'general_info'];

    /**
     * @var string The database table used by the model.
     */
    public $table = 'teamate_ccrezqs_dogs';

    public $belongsTo = [
        'foster' => ['RainLab\User\Models\User'],
    ];

    public $morphMany = [
        'notes' => ['TeamAte\Ccrezqs\Models\Note', 'name' => 'target']
    ];

    public $attachMany = [
        'photos' => 'System\Models\File'
    ];

    public function scopeCurrentUser($query)
    {
        $userId = ($user = Auth::getUser()) ? $user->id : 0;
        return $query->where('foster_id', $userId);
    }

    public function scopeAvailable($query)
    {
        return $query->where('foster_id', null);
    }
}


text:
/************************************************************************
*
* CppSharp
* Licensed under the MIT license.
*
************************************************************************/

#pragma once

#include "Helpers.h"
#include "Sources.h"
#include "Types.h"
#include "Decl.h"
#include "Stmt.h"
#include "Expr.h"
#include <algorithm>

namespace CppSharp { namespace CppParser { namespace AST {

#pragma region Libraries

enum class ArchType
{
    UnknownArch,
    x86,
    x86_64
};

class CS_API NativeLibrary
{
public:
    NativeLibrary();
    ~NativeLibrary();
    std::string fileName;
    ArchType archType;
    VECTOR_STRING(Symbols)
    VECTOR_STRING(Dependencies)
};

#pragma endregion

#pragma region Comments

enum struct CommentKind
{
    FullComment,
    BlockContentComment,
    BlockCommandComment,
    ParamCommandComment,
    TParamCommandComment,
    VerbatimBlockComment,
    VerbatimLineComment,
    ParagraphComment,
    HTMLTagComment,
    HTMLStartTagComment,
    HTMLEndTagComment,
    TextComment,
    InlineContentComment,
    InlineCommandComment,
    VerbatimBlockLineComment
};

class CS_API CS_ABSTRACT Comment
{
public:
    Comment(CommentKind kind);
    CommentKind kind;
};

class CS_API BlockContentComment : public Comment
{
public:
    BlockContentComment();
    BlockContentComment(CommentKind Kind);
};

class CS_API FullComment : public Comment
{
public:
    FullComment();
    ~FullComment();
    VECTOR(BlockContentComment*, Blocks)
};

class CS_API InlineContentComment : public Comment
{
public:
    InlineContentComment();
    InlineContentComment(CommentKind Kind);
    bool hasTrailingNewline;
};

class CS_API ParagraphComment : public BlockContentComment
{
public:
    ParagraphComment();
    ~ParagraphComment();
    bool isWhitespace;
    VECTOR(InlineContentComment*, Content)
};

class CS_API BlockCommandComment : public BlockContentComment
{
public:
    class CS_API Argument
    {
    public:
        Argument();
        Argument(const Argument&);
        ~Argument();
        std::string text;
    };
    BlockCommandComment();
    BlockCommandComment(CommentKind Kind);
    ~BlockCommandComment();
    unsigned commandId;
    ParagraphComment* paragraphComment;
    VECTOR(Argument, Arguments)
};

class CS_API ParamCommandComment : public BlockCommandComment
{
public:
    enum PassDirection
    {
        In,
        Out,
        InOut
    };
    ParamCommandComment();
    PassDirection direction;
    unsigned paramIndex;
};

class CS_API TParamCommandComment : public BlockCommandComment
{
public:
    TParamCommandComment();
    VECTOR(unsigned, Position)
};

class CS_API VerbatimBlockLineComment : public Comment
{
public:
    VerbatimBlockLineComment();
    std::string text;
};

class CS_API VerbatimBlockComment : public BlockCommandComment
{
public:
    VerbatimBlockComment();
    ~VerbatimBlockComment();
    VECTOR(VerbatimBlockLineComment*, Lines)
};

class CS_API VerbatimLineComment : public BlockCommandComment
{
public:
    VerbatimLineComment();
    std::string text;
};

class CS_API InlineCommandComment : public InlineContentComment
{
public:
    enum RenderKind
    {
        RenderNormal,
        RenderBold,
        RenderMonospaced,
        RenderEmphasized,
        RenderAnchor
    };
    class CS_API Argument
    {
    public:
        Argument();
        Argument(const Argument&);
        ~Argument();
        std::string text;
    };
    InlineCommandComment();
    unsigned commandId;
    RenderKind commentRenderKind;
    VECTOR(Argument, Arguments)
};

class CS_API HTMLTagComment : public InlineContentComment
{
public:
    HTMLTagComment();
    HTMLTagComment(CommentKind Kind);
};

class CS_API HTMLStartTagComment : public HTMLTagComment
{
public:
    class CS_API Attribute
    {
    public:
        Attribute();
        Attribute(const Attribute&);
        std::string name;
        std::string value;
    };
    HTMLStartTagComment();
    std::string tagName;
    VECTOR(Attribute, Attributes)
};

class CS_API HTMLEndTagComment : public HTMLTagComment
{
public:
    HTMLEndTagComment();
    std::string tagName;
};

class CS_API TextComment : public InlineContentComment
{
public:
    TextComment();
    std::string text;
};

enum class RawCommentKind
{
    Invalid,
    OrdinaryBCPL,
    OrdinaryC,
    BCPLSlash,
    BCPLExcl,
    JavaDoc,
    Qt,
    Merged
};

class CS_API RawComment
{
public:
    RawComment();
    ~RawComment();
    RawCommentKind kind;
    std::string text;
    std::string briefText;
    FullComment* fullCommentBlock;
};

#pragma region Commands

#pragma endregion

#pragma endregion

} } }


text:
from __future__ import absolute_import, print_function

from celery.signals import task_postrun
from django.core.signals import request_finished
from django.db import models

from sentry.db.models import Model, FlexibleForeignKey, sane_repr
from sentry.db.models.fields import EncryptedPickledObjectField
from sentry.db.models.manager import BaseManager
from sentry.utils.cache import cache

class OrganizationOptionManager(BaseManager):
    def __init__(self, *args, **kwargs):
        super(OrganizationOptionManager, self).__init__(*args, **kwargs)
        self.__cache = {}

    def __getstate__(self):
        d = self.__dict__.copy()
        # we cant serialize weakrefs
        d.pop("_OrganizationOptionManager__cache", None)
        return d

    def __setstate__(self, state):
        self.__dict__.update(state)
        self.__cache = {}

    def _make_key(self, instance_id):
        assert instance_id
        return "%s:%s" % (self.model._meta.db_table, instance_id)

    def get_value_bulk(self, instances, key):
        instance_map = dict((i.id, i) for i in instances)
        queryset = self.filter(organization__in=instances, key=key)
        result = dict((i, None) for i in instances)
        for obj in queryset:
            result[instance_map[obj.organization_id]] = obj.value
        return result

    def get_value(self, organization, key, default=None):
        result = self.get_all_values(organization)
        return result.get(key, default)

    def unset_value(self, organization, key):
        try:
            inst = self.get(organization=organization, key=key)
        except self.model.DoesNotExist:
            return
        inst.delete()
        self.reload_cache(organization.id)

    def set_value(self, organization, key, value):
        self.create_or_update(organization=organization, key=key, values={"value": value})
        self.reload_cache(organization.id)

    def get_all_values(self, organization):
        if isinstance(organization, models.Model):
            organization_id = organization.id
        else:
            organization_id = organization

        if organization_id not in self.__cache:
            cache_key = self._make_key(organization_id)
            result = cache.get(cache_key)
            if result is None:
                result = self.reload_cache(organization_id)
            else:
                self.__cache[organization_id] = result
        return self.__cache.get(organization_id, {})

    def clear_local_cache(self, **kwargs):
        self.__cache = {}

    def reload_cache(self, organization_id):
        cache_key = self._make_key(organization_id)
        result = dict((i.key, i.value) for i in self.filter(organization=organization_id))
        cache.set(cache_key, result)
        self.__cache[organization_id] = result
        return result

    def post_save(self, instance, **kwargs):
        self.reload_cache(instance.organization_id)

    def post_delete(self, instance, **kwargs):
        self.reload_cache(instance.organization_id)

    def contribute_to_class(self, model, name):
        super(OrganizationOptionManager, self).contribute_to_class(model, name)
        task_postrun.connect(self.clear_local_cache)
        request_finished.connect(self.clear_local_cache)

class OrganizationOption(Model):
    """
    Organization options apply only to an instance of a organization.

    Options which are specific to a plugin should namespace
    their key. e.g. key='myplugin:optname'

    key: onboarding:complete
    value: { updated: datetime }
    """

    __core__ = True

    organization = FlexibleForeignKey("sentry.Organization")
    key = models.CharField(max_length=64)
    value = EncryptedPickledObjectField()

    objects = OrganizationOptionManager()

    class Meta:
        app_label = "sentry"
        db_table = "sentry_organizationoptions"
        unique_together = (("organization", "key"),)

    __repr__ = sane_repr("organization_id", "key", "value")


text:
<?php

define ('THEME_NAME',	"Sahifa" );
define ('THEME_FOLDER',	"sahifa" );
define ('THEME_VER', 	5 );

define( 'NOTIFIER_XML_FILE', "http://themes.tielabs.com/xml/".THEME_FOLDER.".xml" );
define( 'DOCUMENTATION_URL', "http://themes.tielabs.com/docs/".THEME_FOLDER );

if ( ! isset( $content_width ) ) $content_width = 618;

// Main Functions
require_once ( get_template_directory() . '/framework/functions/theme-functions.php');
require_once ( get_template_directory() . '/framework/functions/common-scripts.php');
require_once ( get_template_directory() . '/framework/functions/mega-menus.php');
require_once ( get_template_directory() . '/framework/functions/pagenavi.php');
require_once ( get_template_directory() . '/framework/functions/breadcrumbs.php');
require_once ( get_template_directory() . '/framework/functions/tie-views.php');
require_once ( get_template_directory() . '/framework/functions/translation.php');
require_once ( get_template_directory() . '/framework/widgets.php');
require_once ( get_template_directory() . '/framework/admin/framework-admin.php');
require_once ( get_template_directory() . '/framework/shortcodes/shortcodes.php');

if( tie_get_option( 'live_search' ) )
require_once ( get_template_directory() . '/framework/functions/search-live.php');

if( !tie_get_option( 'disable_arqam_lite' ) )
require_once ( get_template_directory() . '/framework/functions/arqam-lite.php');

?>


text:
require_relative '../lib/poker_dice'

describe PokerDice::Hand do
  def hand(*values)
    if values.length == 1 && values.first.kind_of?(String)
      values = values.first.split(/\s+/)
    end
    dice = values.map {|n| PokerDice::Die.new(n) }
    PokerDice::Hand.new(dice)
  end

  describe "scoring" do
    it "recognizes five of a kind" do
      expect( hand('9 9 9 9 9').description ).to eq( "Five of a kind" )
    end

    it "recognizes four of a kind" do
      expect( hand('9 9 10 9 9').description ).to eq( "Four of a kind" )
    end

    it "recognizes a full house" do
      expect( hand('10 10 J J J').description ).to eq( "Full house" )
    end

    it "recognizes a straight" do
      expect( hand('9 10 J Q K').description ).to eq( "Straight" )
      expect( hand('10 J Q K A').description ).to eq( "Straight" )
    end

    it "recognizes three of a kind" do
      expect( hand('J J 9 J K').description ).to eq( "Three of a kind" )
    end

    it "recognizes two pair(s, dammit)" do
      expect( hand('Q A A Q 9').description ).to eq( "Two pair" )
    end

    it "recognizes one pair" do
      expect( hand('10 K A 9 K').description ).to eq( "One pair" )
    end

    it "recognizes a bust (high card, no pair, no straight)" do
      expect( hand('9 10 J Q A').description ).to eq( "Bust" )
    end
  end

  describe "string representation" do
    it "works for five of a kind" do
      expect( hand(1, 1, 1, 1, 1).to_s ).to eq( "9 9 9 9 9" )
    end

    it "works for four of a kind" do
      expect( hand(1, 1, 2, 1, 1).to_s ).to eq( "9 9 10 9 9" )
    end

    it "works for a full house" do
      expect( hand(1, 1, 2, 2, 2).to_s ).to eq( "9 9 10 10 10" )
    end

    it "works for a straight" do
      expect( hand(1, 2, 3, 4, 5).to_s ).to eq( "9 10 J Q K" )
    end
  end

  describe "rerolling some dice" do
    it "is possible" do
      # Start with a straight
      loaded_dice = %w[ 9 10 J Q K ].map {|face_value|
        double("PokerDice::Die", { face_value: face_value })
      }
      hand = PokerDice::Hand.new(loaded_dice)

      expect( hand.to_s ).to eq("9 10 J Q K") # Sanity check

      d1, _, d3 = *loaded_dice

      # First, the hand should reroll dice #1 and #3
      expect(d1).to receive(:roll!).once.ordered
      expect(d3).to receive(:roll!).once.ordered

      # Then, the hand should ask *all* the dice for their face values again
      expect(d1).to receive(:face_value).and_return('10').ordered
      expect(d3).to receive(:face_value).and_return('10').ordered

      hand.reroll_dice(3, 1)

      # Dice #1 and #3 should now have new values
      expect( hand.to_s ).to eq("10 10 10 Q K")
    end
  end
end


text:
import {createTextVNode, linkEvent, render, version} from "inferno-compat";

/*
 * Inferno + inferno-compat without any Inferno specific optimizations
 * Optimization flags could be used, but the purpose is to track performance of slow code paths
 */

uibench.init('Inferno compat (simple)', version);

function TreeLeaf({children}) {
  return (

      {createTextVNode(children)}

  );
}

function shouldDataUpdate(lastProps, nextProps) {
  return lastProps !== nextProps;
}

function TreeNode({data}) {
  var length = data.children.length;
  var children = new Array(length);

  for (var i = 0; i < length; i++) {
    var n = data.children[i];
    var id = n.id;

    if (n.container) {
      children[i] = <TreeNode onComponentShouldUpdate={shouldDataUpdate} data={n} key={id}/>;
    } else {
      children[i] = <TreeLeaf onComponentShouldUpdate={shouldDataUpdate} key={id}>{id}</TreeLeaf>;
    }
  }

  return (

      {children}

  );
}

function tree(data) {
  return (

      <TreeNode data={data.root} onComponentShouldUpdate={shouldDataUpdate}/>

  );
}

function AnimBox({data}) {
  var time = data.time % 10;
  var style = 'border-radius:' + (time) + 'px;' +
    'background:rgba(0,0,0,' + (0.5 + ((time) / 10)) + ')';

  return (

  );
}

function anim(data) {
  var items = data.items;
  var length = items.length;
  var children = new Array(length);

  for (var i = 0; i < length; i++) {
    var item = items[i];

    // Here we are using onComponentShouldUpdate functional Component hook, to short circuit rendering process of AnimBox Component
    // When the data does not change
    children[i] = <AnimBox data={item} onComponentShouldUpdate={shouldDataUpdate} key={item.id}/>;
  }

  return (

      {children}

  );
}

function onClick(text, e) {
  console.log('Clicked', text);
  e.stopPropagation();
}

function TableCell({children}) {
  return (

      {createTextVNode(children)}

  );
}

function TableRow({data}) {
  var classes = 'TableRow';

  if (data.active) {
    classes = 'TableRow active';
  }
  var cells = data.props;
  var length = cells.length + 1;
  var children = new Array(length);

  children[0] = <TableCell onComponentShouldUpdate={shouldDataUpdate}>{'#' + data.id}</TableCell>;

  for (var i = 1; i < length; i++) {
    children[i] = <TableCell onComponentShouldUpdate={shouldDataUpdate}>{cells[i - 1]}</TableCell>;
  }

  return (

      {children}

  );
}

function table(data) {
  var items = data.items;
  var length = items.length;
  var children = new Array(length);

  for (var i = 0; i < length; i++) {
    var item = items[i];

    children[i] = <TableRow data={item} onComponentShouldUpdate={shouldDataUpdate} key={item.id}>{item}</TableRow>;
  }

  return (

      {children}

  );
}

var lastMainData;

function main(data) {
  lastMainData = data;
  var location = data.location;
  var section;

  if (location === 'table') {
    section = table(data.table);
  } else if (location === 'anim') {
    section = anim(data.anim);
  } else if (location === 'tree') {
    section = tree(data.tree);
  }

  return (

      {section}

  );
}

document.addEventListener('DOMContentLoaded', function(e) {
  var container = document.querySelector('#App');

  uibench.run(
    function(state) {
      render(main(state), container);
    },
    function(samples) {
      render(
{JSON.stringify(samples, null, ' ')}
, container);
    }
  );
});


text:
layout: post
title: building ubuntu kernels with debug symbols
date: '2015-10-02T08:53:52-0500'
author: arges
tags:
- linux
- ubuntu
modified_time: '2015-10-02T08:53:56-0500'

---

Occasionally it is useful to be able to build a kernel the Ubuntu way with
debug symbols. The following is how to install dependencies, clone the tree,
and finally build in such a way that ddeb packages get generated.

Here's how:

~~~bash
sudo apt-get build-dep linux-image-$(uname -r)
sudo apt-get install fakeroot pkg-config-dbgsym git
git clone git://git.launchpad.net/~ubuntu-kernel/ubuntu/+source/linux/+git/wily
cd wily
fakeroot debian/rules clean
debian/rules build-generic
fakeroot debian/rules binary-generic binary-headers skipdbg=false
~~~

Wait a bit and you should see a -dbgsym package get generated.


text:
namespace silifuzz {

// Returns true iff AVX-512 foundation instruction set is supported and
// registers zmm0-zmm31 and k0-k7 are accessible.
//
// This is in "C" namespace as this is called from assembly and it is easier to
// do so without function name mangling.
extern "C" bool HasAVX512Registers();

// Clears AVX-512 registers zmm16 to zmm31 and also opmask registers k0 to k7.
// This is part of AVX-512 state that can only be cleared using AVX-512F. The
// lower 16 AVX registers can be cleared using AVX instruction vzeroupper.
//
// REQUIRES: HasAVX512Registers() returns true.
//
// This cannot be called from C++ code. The x86_64 ABI specifies all AVX
// registers as caller-saved. A C++ caller saves all live AVX registers before
// calling this and restores those registers after call.
//
// This is in "C" namespace like HasAVX512Registers() above.
extern "C" void ClearAVX512OnlyState();

}  // namespace silifuzz

#endif  // __x86_64__
#endif  // THIRD_PARTY_SILIFUZZ_UTIL_AVX_H_


text:
/* */
var convert = require('./convert'),
    func = convert('sortedLastIndexOf', require('../sortedLastIndexOf'));
func.placeholder = require('./placeholder');
module.exports = func;


text:
package com.huihuan.jerrys.shiro.server.web.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.huihuan.jerrys.shiro.entity.Organization;
import com.huihuan.jerrys.shiro.server.service.OrganizationService;

@Controller
@RequestMapping("/organization")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @RequiresPermissions("organization:view")
    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model) {
        return "organization/index";
    }

    @RequiresPermissions("organization:view")
    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    public String showTree(Model model) {
        model.addAttribute("organizationList", organizationService.findAll());
        return "organization/tree";
    }

    @RequiresPermissions("organization:create")
    @RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.GET)
    public String showAppendChildForm(@PathVariable("parentId") Long parentId, Model model) {
        Organization parent = organizationService.findOne(parentId);
        model.addAttribute("parent", parent);
        Organization child = new Organization();
        child.setParentId(parentId);
        child.setParentIds(parent.makeSelfAsParentIds());
        model.addAttribute("child", child);
        model.addAttribute("op", "新增");
        return "organization/appendChild";
    }

    @RequiresPermissions("organization:create")
    @RequestMapping(value = "/{parentId}/appendChild", method = RequestMethod.POST)
    public String create(Organization organization) {
        organizationService.createOrganization(organization);
        return "redirect:/organization/success";
    }

    @RequiresPermissions("organization:update")
    @RequestMapping(value = "/{id}/maintain", method = RequestMethod.GET)
    public String showMaintainForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("organization", organizationService.findOne(id));
        return "organization/maintain";
    }

    @RequiresPermissions("organization:update")
    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(Organization organization, RedirectAttributes redirectAttributes) {
        organizationService.updateOrganization(organization);
        redirectAttributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/organization/success";
    }

    @RequiresPermissions("organization:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        organizationService.deleteOrganization(id);
        redirectAttributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/organization/success";
    }

    @RequiresPermissions("organization:update")
    @RequestMapping(value = "/{sourceId}/move", method = RequestMethod.GET)
    public String showMoveForm(@PathVariable("sourceId") Long sourceId, Model model) {
        Organization source = organizationService.findOne(sourceId);
        model.addAttribute("source", source);
        model.addAttribute("targetList", organizationService.findAllWithExclude(source));
        return "organization/move";
    }

    @RequiresPermissions("organization:update")
    @RequestMapping(value = "/{sourceId}/move", method = RequestMethod.POST)
    public String move(
            @PathVariable("sourceId") Long sourceId,
            @RequestParam("targetId") Long targetId) {
        Organization source = organizationService.findOne(sourceId);
        Organization target = organizationService.findOne(targetId);
        organizationService.move(source, target);
        return "redirect:/organization/success";
    }

    @RequiresPermissions("organization:view")
    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String success() {
        return "organization/success";
    }

}


text:
import tvm
from tvm import relay
import pytest

def make_rel(name, args, num_inputs=None, attrs=None):
    func = tvm.get_env_func("tvm.relay.type_relation." + name)
    if num_inputs is None:
        num_inputs = len(args) - 1
    return relay.ty.TypeRelation(func, args, num_inputs, attrs)

def make_solver():
    solver = relay._analysis._test_type_solver()
    solver.Solve = solver("Solve")
    solver.Unify = solver("Unify")
    solver.Resolve = solver("Resolve")
    solver.AddConstraint = solver("AddConstraint")

    def gen_type(name, args, out=None):
        out = out if out else relay.ty.IncompleteType()
        solver.AddConstraint(make_rel(name, args + [out]))
        return out

    solver.gen_type = gen_type
    return solver

def test_bcast():
    solver = make_solver()
    t0 = relay.ty.TensorType((10, 20), "float32")
    t1 = relay.ty.TensorType((10, 1), "float32")
    tc = relay.ty.TensorType((10, 1, 1), "float32")
    t2 = solver.gen_type("Broadcast", [t0, t1])
    t3 = solver.gen_type("Identity", [t2])
    t4 = solver.gen_type("Broadcast", [t3, tc])
    assert solver.Solve()
    assert solver.Resolve(t2) == relay.ty.TensorType((10, 20), "float32")
    assert solver.Resolve(t4) == relay.ty.TensorType((10, 10, 20), "float32")

def test_backward_solving():
    solver = make_solver()
    t0 = relay.ty.TensorType((10, 20), "float32")
    tc = relay.ty.TensorType((10, 1, 1), "float32")
    t1 = relay.ty.IncompleteType()
    t3 = solver.gen_type("Broadcast", [t0, t1])
    t2 = solver.gen_type("Identity", [t1], out=tc)
    assert solver.Solve()
    assert solver.Resolve(t3) == relay.ty.TensorType((10, 10, 20), "float32")

def test_unify_tuple():
    solver = make_solver()
    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()
    t3 = relay.ty.TensorType((10, 20), "float32")

    tup1 = relay.ty.TupleType([t1, t2])
    tup2 = relay.ty.TupleType([t3, t3])

    unified = solver.Unify(tup1, tup2)
    assert unified == tup2

def test_unify_global_type_var():
    # should only be able to unify if they're the same
    solver = make_solver()
    gtv = relay.GlobalTypeVar('gtv')
    unified = solver.Unify(gtv, gtv)
    assert unified == gtv

def test_unify_typecall():
    solver = make_solver()
    gtv = relay.GlobalTypeVar('gtv')

    # yeah, typecalls are shaped like tuples so the same
    # tests work out
    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()
    t3 = relay.ty.TensorType((10, 20), "float32")

    tc1 = relay.ty.TypeCall(gtv, [t1, t2])
    tc2 = relay.ty.TypeCall(gtv, [t3, t3])
    unified = solver.Unify(tc1, tc2)
    assert unified == tc2

def test_unify_functype():
    solver = make_solver()
    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()
    t3 = relay.ty.IncompleteType()

    unit = relay.ty.TupleType([])
    tensor1 = relay.ty.TensorType((10, 20), "float32")
    tensor2 = relay.ty.TensorType((10,), "float32")

    ft1 = relay.ty.FuncType([t1, t2], t3)
    ft2 = relay.ty.FuncType([tensor1, tensor2], unit)

    unified = solver.Unify(ft1, ft2)
    assert unified == ft2

def test_recursive_unify():
    solver = make_solver()
    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()
    t3 = relay.ty.IncompleteType()

    tensor1 = relay.ty.TensorType((10, 10, 20), "float32")
    tensor2 = relay.ty.TensorType((10, 20), "float32")
    tensor3 = relay.ty.TensorType((10,), "float32")

    tup1 = relay.ty.TupleType([relay.ty.TupleType([t1, t2]), t2])
    tup2 = relay.ty.TupleType([relay.ty.TupleType([tensor1, tensor2]), tensor2])

    ft1 = relay.ty.FuncType([tup1, t3], t3)
    ft2 = relay.ty.FuncType([tup2, tensor3], tensor3)

    unified = solver.Unify(ft1, ft2)
    assert unified == ft2

def test_unify_vars_under_tuples():
    solver = make_solver()
    t1 = relay.ty.IncompleteType()

    tup1 = relay.ty.TupleType([t1, t1])
    unified = solver.Unify(tup1, tup1)
    assert unified == tup1

    t2 = relay.ty.IncompleteType()
    tup2 = relay.ty.TupleType([t2, t2])

    tup3 = relay.ty.TupleType([t1, t2])
    tup4 = relay.ty.TupleType([t2, t1])
    unified = solver.Unify(tup3, tup4)
    assert (unified == tup1 or unified == tup2)

def test_binding_over_typevars():
    solver = make_solver()

    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()

    a = relay.ty.TypeVar('a')
    b = relay.ty.TypeVar('b')
    c = relay.ty.TypeVar('c')
    d = relay.ty.TypeVar('d')

    ft1 = relay.ty.FuncType([t1], t2, [c, d])
    ft2 = relay.ty.FuncType([a], b, [a, b])
    unified = solver.Unify(ft1, ft2)
    assert (unified == solver.Resolve(ft1))

def test_recursive_backward_solving():
    solver = make_solver()

    tensor1 = relay.ty.TensorType((10, 20), "float32")
    tensor2 = relay.ty.TensorType((10, 1, 1), "float32")
    tensor3 = relay.ty.TensorType((10,), "float32")

    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()
    t3 = relay.ty.IncompleteType()

    tup1 = relay.ty.TupleType([relay.ty.TupleType([tensor1, tensor2]), tensor3])
    tup2 = relay.ty.TupleType([relay.ty.TupleType([t1, t2]), t3])
    solver.gen_type("Identity", [tup1], out=tup2)

    assert solver.Solve()
    assert solver.Resolve(tup2) == tup1

def test_backward_solving_after_child_update():
    solver = make_solver()

    tensor1 = relay.ty.TensorType((10, 20), "float32")
    tensor2 = relay.ty.TensorType((10, 1, 1), "float32")

    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()
    t3 = relay.ty.IncompleteType()

    tup1 = relay.ty.TupleType([t1, t2])
    tup2 = relay.ty.TupleType([t1, t3])

    tup_concrete = relay.ty.TupleType([tensor1, tensor2])

    t4 = solver.gen_type("Identity", [tup1])
    t5 = solver.gen_type("Identity", [tup2])

    solver.gen_type("Identity", [t4], out=t5)
    assert solver.Solve()
    assert solver.Resolve(t3) == t3 or solver.Resolve(t3) == t2
    assert solver.Resolve(t4) == tup1 or solver.Resolve(t4) == tup2
    assert solver.Resolve(t5) == tup1 or solver.Resolve(t5) == tup2

    # updating the variables *inside* tup1 and tup2 should update t4 and t5
    solver.gen_type("Identity", [t1], out=tensor1)
    solver.gen_type("Identity", [t2], out=tensor2)
    assert solver.Solve()
    assert solver.Resolve(t4) == tup_concrete
    assert solver.Resolve(t5) == tup_concrete

@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)
def test_incompatible_tuple_unification():
    solver = make_solver()
    t1 = relay.ty.IncompleteType()
    t2 = relay.ty.IncompleteType()

    tensor1 = relay.ty.TensorType((1, 2, 3), "float32")
    tensor2 = relay.ty.TensorType((2, 3), "float32")
    tensor3 = relay.ty.TensorType((3,), "float32")

    tup1 = relay.ty.TupleType([relay.ty.TupleType([t1, t1]), t2])
    tup2 = relay.ty.TupleType([relay.ty.TupleType([tensor1, tensor2]), tensor3])
    solver.Unify(tup1, tup2)

@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)
def test_bad_recursive_unification():
    solver = make_solver()
    t1 = relay.ty.IncompleteType()
    solver.Unify(t1, relay.ty.TupleType([t1, t1]))

@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)
def test_unify_invalid_global_typevars():
    solver = make_solver()
    gtv1 = relay.GlobalTypeVar('gtv1')
    gtv2 = relay.GlobalTypeVar('gtv2')
    solver.Unify(gtv1, gtv2)

@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)
def test_incompatible_typecall_var_unification():
    solver = make_solver()
    gtv1 = relay.GlobalTypeVar('gtv1')
    gtv2 = relay.GlobalTypeVar('gtv2')

    t1 = relay.IncompleteType()
    t2 = relay.IncompleteType()

    tc1 = relay.TypeCall(gtv1, [t1])
    tc2 = relay.TypeCall(gtv2, [t2])
    solver.Unify(tc1, tc2)

@pytest.mark.xfail(raises=tvm._ffi.base.TVMError)
def test_incompatible_typecall_args_unification():
    solver = make_solver()
    gtv = relay.GlobalTypeVar('gtv1')
    t1 = relay.IncompleteType()
    t2 = relay.IncompleteType()

    tensor1 = relay.TensorType((1, 2, 3), "float32")
    tensor2 = relay.TensorType((2, 3), "float32")
    tensor3 = relay.TensorType((3,), "float32")

    tc1 = relay.TypeCall(gtv, [relay.TupleType([t1, t1]), t2])
    tc2 = relay.TypeCall(gtv, [relay.TupleType([tensor1, tensor2]), tensor3])
    solver.Unify(tc1, tc2)

if __name__ == "__main__":
    test_bcast()
    test_backward_solving()
    test_unify_tuple()
    test_unify_typecall()
    test_unify_functype()
    test_recursive_unify()
    test_unify_vars_under_tuples()
    test_recursive_backward_solving()
    test_backward_solving_after_child_update()
    test_incompatible_tuple_unification()
    test_bad_recursive_unification()
    test_incompatible_typecall_var_unification()
    test_incompatible_typecall_args_unification()


text:
import os, sys     # low level handling, such as command line stuff
import string      # string methods available
import re          # regular expressions
import getopt      # comand line argument handling
import math        # match functions
from low import *  # custom functions, written by myself

# =============================================================================
def show_help( ):
  """ displays the program parameter list and usage information """
  stdout( "usage: " + sys.argv[0] + " -f <path> " )
  stdout( " " )
  stdout( " option    description" )
  stdout( " -h        help (this text here)" )
  stdout( " -f        pfam_full file to parse" )
  stdout( " " )
  sys.exit(1)

# =============================================================================
def handle_arguments():
  """ verifies the presence of all necessary arguments and returns the data dir """
  if len ( sys.argv ) == 1:
    stderr( "no arguments provided." )
    show_help()

  try: # check for the right arguments
    keys, values = getopt.getopt( sys.argv[1:], "hf:" )
  except getopt.GetoptError:
    stderr( "invalid arguments provided." )
    show_help()

  args = {}
  for key, value in keys:
    if key == '-f': args['file'] = value

  if not args.has_key('file'):
    stderr( "import file argument missing." )
    show_help()
  elif not file_exists( args.get('file') ):
    stderr( "import file does not exist." )
    show_help()

  return args

# =============================================================================
def get_regex( args ):
  idhash = {}
  idhash['name'] = re.compile('^#=GF ID\s+(\S+)')
  idhash['acc'] = re.compile('^#=GF AC\s+(PF\S+)')
  idhash['descr'] = re.compile('^#=GF DE\s+(.*)$')
  idhash['comment'] = re.compile('^#=GF CC\s+(.*)$')
  idhash['pftype'] = re.compile('^#=GF TP\s+(\S+)')
  idhash['terminate'] = re.compile('^\\\\$')
  return idhash

# =============================================================================
class PfamEntry:
  def __init__(self):
    self.name = " "
    self.acc = " "
    self.descr = " "
    self.comment = " "
    self.pftype = " "

  def set_name(self, name):
    self.name = name

  def set_acc(self, acc):
    self.acc = acc

  def set_descr(self, descr):
    if self.descr == " ": self.descr = descr
    else: self.descr += " " + descr

  def set_comment(self, comment):
    if self.comment == " ": self.comment = comment
    else: self.comment += " " + comment

  def set_pftype(self, pftype):
    self.pftype = pftype

  def to_string(self):
    return string.join([self.name, self.acc, self.pftype, self.descr, self.comment], "\t")

# =============================================================================
# === MAIN ====================================================================
# =============================================================================
def main( args ):

  regex = get_regex( args )
  info("getting total number of entries...")
  sout, serr = catch_bash_cmd_output( "grep '^//' -c %s" %args.get('file') )
  total = int( sout )
  info("total number of entries: %s\n" %total)
  count = 0
  infomsg("entries found: %s" %total )
  print "#" + string.join(['abbrv', 'pfamid', 'pfamtype', 'description', 'comment'], "\t")

  fo = open( args.get('file') )
  entry = PfamEntry()
  for line in fo:
    line = line.rstrip()
    if line.startswith('//'):
      count += 1
      print entry.to_string()
      info( "  status:\t%01.2f%%\t%s/%s" %( 100.0*count/total, count, total ) )
      entry = PfamEntry()
    elif not line.startswith('#=GF'): continue
    elif re.match(regex['name'], line): entry.set_name( re.match(regex['name'], line).group(1) )
    elif re.match(regex['acc'], line): entry.set_acc( re.match(regex['acc'], line).group(1) )
    elif re.match(regex['pftype'], line): entry.set_pftype( re.match(regex['pftype'], line).group(1) )
    elif re.match(regex['descr'], line): entry.set_descr( re.match(regex['descr'], line).group(1) )
    elif re.match(regex['comment'], line): entry.set_comment( re.match(regex['comment'], line).group(1) )
  fo.close()
  info("\ndone.\n")

# =============================================================================
args = handle_arguments()
main( args )


text:
package com.healthmarketscience.sqlbuilder.custom;

import java.io.IOException;
import com.healthmarketscience.common.util.AppendableExt;
import com.healthmarketscience.sqlbuilder.ValidationContext;
import com.healthmarketscience.sqlbuilder.Expression;

/**
 * SqlObject expression which inserts a "named" parameter like {@code
 * ":<name>"}.  This syntax is used by various custom SQL or SQL-like
 * frameworks (e.g. Hibernate's HQL).
 *
 * @author James Ahlborn
 */
public class NamedParamObject extends Expression
{
  private String _name;

  public NamedParamObject(String name)
  {
    _name = name;
  }

  @Override
  protected void collectSchemaObjects(ValidationContext vContext) {
  }

  @Override
  public void appendTo(AppendableExt app) throws IOException {
    app.append(':').append(_name);
  }
}


text: ![image](/assets/images/screenshot.png)


text:
'use strict';

/**
 * @ngdoc function
 * @name frontendApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the frontendApp
 */
angular.module('frontendApp')
  .controller('MainCtrl', ['$scope', '$upload','$routeParams', '$location','$http',
  	function($scope, $upload, $routeParams, $location, $http) {
  		if (typeof $routeParams.url_id !== 'undefined' ){
  			$scope.url_id = $routeParams.url_id;
  			getChartConfig($scope,$http);
  		} else {
  			$scope.url_id = null;
  			$scope.fileUploaded = false;
  		}

  	 	$scope.gotoBottom = function() {
      	// set the location.hash to the id of
      	// the element you wish to scroll to

	  	var old = $location.hash();

      $location.hash('help');
      console.log("in scroll function");

      // call $anchorScroll()
      $anchorScroll();

      //reset to old to keep any additional routing logic from kicking in
      $location.hash(old);

    };

    $scope.onFileSelect = function($files) {

		//$files: an array of files selected, each file has name, size, and type.
		$scope.selectedFiles = $files;
		$scope.progress = [];
		for (var i = 0; i < $files.length; i++) {
			var file = $files[i];
			$scope.upload = $upload.upload({
				url: '/api/uploadChat',
				method: 'POST',
				data: {'url_id': $scope.url_id},
				file: file
			}).progress(function(evt) {
				$scope.progress[i-1] = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
			}).success(function(data, status, headers, config) {
				$scope.data = data;

				var label = 'Nr. of Messages: ' + $scope.data.number_of_messages + '; Nr. of People: ' + $scope.data.number_of_users;
				//adding GoogleAnalytics Event
			     ga('send', 'event', 'SuccesfullUpload', 'click', label);
				 console.log("Success");
				 $location.path('/'+data.url_id);
			}).then(function(){
				//Not sure any of this gets executed.
				$scope.selectedFiles = null;
				$scope.fileUploaded = true;
				setTimeout(function(){ 	$(window).resize();}, 500);
			});
		}
	}
}]);

function getChartConfig($scope,$http){
	$http.post('/api/getconfig',{'url_id':$scope.url_id})
	.success(function(data,status,headers,config){
		$scope.data = data;
		$scope.fileUploaded = true;
	})
	.error(function(data,status,headers,config){
		$scope.fileUploaded = false;
		console.log(data);
	});
}


text:
import nltk
import itertools
import time
import os
import library.helpers as h
from os.path import join as j
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def default_tokenize(sentence, SPLIT_TOKEN=['.', '"' , "'" , ',' , '(', ')', '!', '?', ';', ':', "\\" , '/', '[',']',"=","-",'_' ]):
    # decode and to lower
    sentence = sentence.lower()
    # add start and end token
    for char in SPLIT_TOKEN:
        sentence = sentence.replace(char, ' ' + char + ' ')
    # tokenize
    tokenized_logline = sentence.split(" ")[0:200] #nltk.word_tokenize(logline)
    return tokenized_logline

PAD_TOKEN_ID = '0'
UNK_TOKEN_ID = '1'
START_TOKEN_ID = '2'
STOP_TOKEN_ID = '3'

class Vocabulary(object):

    def __init__(self):
        self.unique_tokens_and_counts={}
        self.token_to_index = {"PAD_TOKEN":PAD_TOKEN_ID, "UNK_TOKEN":UNK_TOKEN_ID, "START_TOKEN":START_TOKEN_ID, "STOP_TOKEN":STOP_TOKEN_ID}
        self.index_to_token = {PAD_TOKEN_ID:"PAD_TOKEN", UNK_TOKEN_ID:"UNK_TOKEN", START_TOKEN_ID:"START_TOKEN", STOP_TOKEN_ID:"STOP_TOKEN"}
        self.split_function = None
        self.log_name=None
        self.suffix=None

    def _is_initialized(self):
        if not self.log_name is None or self.suffix is None or split_function is None:
            logger.warn("Vocabulary is probably not properly initialized")
            return False
        return True

    def token_to_idx(self, token): # token_to_idx("hello") => 12
        if token in self.token_to_index:
            return self.token_to_index[token]
        else:
            return UNK_TOKEN_ID

    def idx_to_token(self, idx): # token_to_idx(12) => "hello"
        idx = "%s"%idx
        if idx in self.index_to_token:
            return self.index_to_token[idx]
        else:
            return "UNK_TOKEN"

    def size(self):
        assert(len(self.token_to_index)==len(self.index_to_token))
        return len(self.index_to_token)

    def line_to_index_seq(self, line): #"the cat sat" => [14,12,15]
        return map(self.token_to_idx, self.split_function(line))

    def index_seq_to_line(self, index_seq): #[14,12,15] => "the cat sat"
        return " ".join(map(self.idx_to_token, index_seq ))

    def save(self):
        i2t_path = j("data", "vocabularies", "%s%s_idx2tok.json"%(self.log_name, self.suffix))
        t2i_path = j("data", "vocabularies", "%s%s_tok2idx.json"%(self.log_name, self.suffix))
        voc_path = j("data", "vocabularies", "%s%s_voc.json"%(self.log_name, self.suffix))

        h.save_to_json(self.unique_tokens_and_counts, voc_path)
        h.save_to_json(self.token_to_index, t2i_path)
        h.save_to_json(self.index_to_token, i2t_path)
        logger.info("Done saving vocabulary '%s%s'"%(self.log_name, self.suffix))

    def words(self):
        return self.token_to_index.keys()

    @classmethod
    def exists(cls,log_name,suffix=""):
        i2t_path = j("data", "vocabularies", "%s%s_idx2tok.json"%(log_name, suffix))
        t2i_path = j("data", "vocabularies", "%s%s_tok2idx.json"%(log_name, suffix))
        voc_path = j("data", "vocabularies", "%s%s_voc.json"%(log_name, suffix))
        if not os.path.exists(i2t_path): return False
        if not os.path.exists(t2i_path): return False
        if not os.path.exists(voc_path): return False
        return True

    @classmethod
    def create(cls, log_name,suffix="", max_words_in_vocabulary =-1,  split_function=default_tokenize):
        num_special_token=4
        new_vocabulary = Vocabulary()
        new_vocabulary.log_name=log_name
        new_vocabulary.suffix=suffix
        new_vocabulary.split_function=split_function

        log_path = j("data", "raw", "%s%s.log"%(log_name,suffix))
        logger.info("Creating vocabulary for '%s'", log_path)
        # get word_frequencies for split lines
        word_frequencies = nltk.FreqDist(itertools.chain(*[split_function(line) for line in open(log_path, "r")]))
        logger.info("Counting word frequencies done.")
        logger.info("%i unique words in vocabulary"%(len(word_frequencies)))
        # determine vocabulary
        if max_words_in_vocabulary==-1:
            max_words = len(word_frequencies.items())
        else:
            max_words = max_words_in_vocabulary - num_special_token # because we add pad_token and unk_token
        new_vocabulary.unique_tokens_and_counts = {# merge two dicts
            **new_vocabulary.unique_tokens_and_counts,
            **dict(word_frequencies.most_common(max_words))
        }
        logger.info("Using %i words of vocabulary"%(new_vocabulary.size()))

        for i, word in enumerate(new_vocabulary.unique_tokens_and_counts.keys()):
            new_vocabulary.index_to_token["%s"%(i+num_special_token)]=word # +2 because we added PAD_TOKEN and UNK_TOKEN
            new_vocabulary.token_to_index[word]="%s"%(i+num_special_token)
        logger.info("Indexing done, vocabulary loaded.")
        return new_vocabulary

    @classmethod
    def load(cls, log_name, suffix="", split_function=default_tokenize):
        restored_vocabulary = Vocabulary()

        restored_vocabulary.log_name=log_name
        restored_vocabulary.suffix=suffix
        restored_vocabulary.split_function=split_function

        i2t_path = j("data", "vocabularies", "%s%s_idx2tok.json"%(log_name, suffix))
        t2i_path = j("data", "vocabularies", "%s%s_tok2idx.json"%(log_name, suffix))
        voc_path = j("data", "vocabularies", "%s%s_voc.json"%(log_name, suffix))

        # restore vocabulary
        logger.debug("Loading '%s'"%(voc_path))
        restored_vocabulary.unique_tokens_and_counts = {# merge two dicts
            **restored_vocabulary.unique_tokens_and_counts,
            **h.load_from_json(voc_path)
        }

        # restore index2tokenb
        logger.debug("Loading '%s'"%(i2t_path))
        restored_vocabulary.index_to_token = {# merge two dicts
            **restored_vocabulary.index_to_token,
            **h.load_from_json(i2t_path)
        }

        # restore vocabulary
        logger.debug("Loading '%s'"%(t2i_path))
        restored_vocabulary.token_to_index = {# merge two dicts
            **restored_vocabulary.token_to_index,
            **h.load_from_json(t2i_path)
        }

        return restored_vocabulary


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

<title>Class Hierarchy</title>
<meta name="date" content="2017-04-27">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

com.github.sahasatvik.cli,

com.github.sahasatvik.struct,

examples

Class Hierarchy

java.lang.Object

com.github.sahasatvik.cli.ArgHandler

examples.ArgHandlerExample

com.github.sahasatvik.cli.Argument

com.github.sahasatvik.struct.LinkedList<T>

com.github.sahasatvik.struct.Queue<T>

com.github.sahasatvik.struct.Stack<T>

com.github.sahasatvik.struct.ListItem<T>

com.github.sahasatvik.cli.Option<T>

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

com.github.sahasatvik.cli.ArgHandlerException

com.github.sahasatvik.cli.ArgumentException

com.github.sahasatvik.cli.NoArgumentOfRequiredTypeFoundException

com.github.sahasatvik.cli.NoRemainingArgumentsException

com.github.sahasatvik.cli.OptionException

com.github.sahasatvik.cli.CannotParseValueOfOptionException

com.github.sahasatvik.cli.IncorrectOptionSyntaxException

com.github.sahasatvik.cli.InvalidOptionException

com.github.sahasatvik.cli.MissingOptionValueException

com.github.sahasatvik.cli.UnknownOptionValueTypeException

com.github.sahasatvik.struct.ListException

com.github.sahasatvik.struct.EmptyListException

com.github.sahasatvik.struct.ListIndexOutOfBoundsException

Interface Hierarchy

com.github.sahasatvik.cli.Parser<T>

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
import sys
from engine import *

# get input arguments
parser = argparse.ArgumentParser()
parser.add_argument("schema_files", nargs='+', type=str)
parser.add_argument("n_iterations", nargs=1, type=int,
                    help = 'n_samples from a given schema file')
parser.add_argument("n_consecutive_repeats", nargs=1, type=int,
                    help = 'n_consecutive_repeats of the same schema')

# process arguments
args = vars(parser.parse_args())
print(args)
input_fnames = args.get('schema_files')
n_iterations = args.get('n_iterations')[0]
n_repeats = args.get('n_consecutive_repeats')[0]

n_input_files = len(input_fnames)
names_concat = '_'.join(input_fnames)

# sample stories from schema
def main(rand_seed):
    # get a handle on the output file
    output_path = mkdir(names_concat, n_iterations, n_repeats)
    f_stories = open_output_file(output_path, names_concat, n_iterations, n_repeats)
    f_QA = open_output_file(output_path, names_concat + '_QA', n_iterations, n_repeats)
    # read all schema files
    schema_info = []
    for i in range(n_input_files):
        schema_info.append(read_schema_file(input_fnames[i]))

    # write stories with alternating schema info
    for i in range(n_input_files * n_iterations):
        f_idx = np.mod(i, n_input_files)
        # write to the output file
        rand_seed = write_stories(schema_info[f_idx],
                                  f_stories, f_QA,
                                  rand_seed, n_repeats)

    f_stories.close()
    f_QA.close()

if __name__ == "__main__":
    # if there is only one 1 schema file, repeat & iter are the same thing
    if n_input_files == 1:
        n_iterations = n_iterations * n_repeats
        n_repeats = 1
    main(0)


text:
namespace Syndicate { namespace Graphics {

IndexBuffer::IndexBuffer(GLushort* data, GLsizei count) :
	m_Count(count)
{
	glGenBuffers(1, &this->m_BufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->m_BufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * count, data, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

IndexBuffer::IndexBuffer(GLuint* data, GLsizei count) :
	m_Count(count)
{
	glGenBuffers(1, &this->m_BufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->m_BufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * count, data, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

IndexBuffer::~IndexBuffer()
{
	glDeleteBuffers(1, &this->m_BufferID);
}

} }


text:
@interface BRAppUser : NSObject

@property (nonatomic, readonly) BOOL newUser;
@property (nonatomic, readonly) BOOL authenticated;
@property (nonatomic, strong) NSString *authenticationToken;

@property (nonatomic, strong) NSString *recordId;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *website;
@property (nonatomic, strong) NSString *phone;
@property (nonatomic, strong) NSString *address;
@property (nonatomic, strong) NSString *email;
@property (nonatomic, strong) NSString *password;

+ (BRAppUser *)currentUser;

- (void)initializeWithDictionary:(NSDictionary *)dictionary;

- (void)clear;

- (void)setPreferencesValue:(id)value forKey:(NSString *)key;
- (id)preferencesValueForKey:(NSString *)key;

@end


text:
var fs = require('fs');
var md5 = require('MD5');

module.exports = function Cache(opts) {
	if (opts === undefined) opts = {};
	this.dir  = opts.dir  || './cache';
	this.life = opts.life === undefined ? 240 : opts.life;
	this.mode = opts.mode || 'json'; // json | string | raw
	self = this;

	this.get = function(key, fn) {
		if(fn === undefined) fn = function(err, data) {};
		self.getPath(key, function(err, path) {
			if(err) return fn(err, undefined);
			fs.exists(path, function(exists) {
				if(!exists) return fn(null, undefined);
				fs.stat(path, function(err, stats) {
					if(err) return fn(err, undefined);
					var fileTime = stats.mtime;
					var now = new Date();
					var diff = (now-fileTime)/60000;
					if(diff>self.life) return fn(null, undefined);
					fs.readFile(path, function(err, data) {
						if(err) return fn(err, undefined);
						var result = self.mode == 'json'
							? JSON.parse(data)
							: self.mode == 'string'
							? data.toString()
							: data;
						fn(null, result);
					});
				});
			});
		});
	}

	this.set = function(key, data, fn) {
		if(fn === undefined) fn = function(err) {};
		if (this.mode == 'json') data = JSON.stringify(data);
		self.getPath(key, function(err, path) {
			if(err) return fn(err);
			fs.writeFile(path, data, function(err) {
				if(fn !== undefined) fn(err);
			});
		});
	}

	this.getSync = function(key) {
		var path = this.getPathSync(key);
		if(!fs.existsSync(path)) return undefined;
		var fileTime = fs.statSync(path).mtime;
		var now = new Date();
		var diff = (now-fileTime)/60000;
		if(diff>this.life) return undefined;
		var data = fs.readFileSync(path);
		return self.mode == 'json'
			? JSON.parse(data)
			: self.mode == 'string'
			? data.toString()
			: data;
	}

	this.setSync = function(key, data) {
		if (this.mode == 'json') data = JSON.stringify(data);
		fs.writeFileSync(this.getPathSync(key), data)
	}

	this.getPathSync = function(key) {
		if(!fs.existsSync(this.dir)) {
			throw new Error('Cache directory does not exist: ' + this.dir);
		}
		return this.dir + '/' + this.getFilename(key)
	}

	this.getPath = function(key, fn) {
		if(fn === undefined) fn = function(err, path) {};
		fs.exists(self.dir, function(exists) {
			if(!exists) {
				var err = new Error('Cache directory does not exist: ' + self.dir);
				return fn(err, undefined);
			}
			fn(null, self.dir + '/' + self.getFilename(key));
		});
	}

	this.getFilename = function(key) {
		return md5(key);
	}
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.springioc;

import java.util.Random;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 *
 * @author jeff.huang
 */
public class MyBeanWithApplicationContextAware implements ApplicationContextAware{
    private ApplicationContext ctx;

    public void sayHello() {
        Random r = ctx.getBean("random", Random.class);
        MyBean bean = new MyBean("Application-Context-Aware " + r.nextInt());
        bean.sayHello();
    }

    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        this.ctx = ac;
    }

}


text:
all: node_modules
	bailey --bare ./ ./

node_modules:
	npm install


text:
<md-toolbar color="primary" class="fixed-toolbar"
            md-peekaboo [scroller]="content.parentElement"
            [break]="190"
            breakAction="show"
            [ngClass]="{hide:over}"
            [style.left]="sidenavWidth + 'px'"
            [style.right]="scrollWidth + 'px'">
</md-toolbar>
<md-toolbar color="primary" class="fixed-toolbar"
            [ngClass]="{hide:over}"
            [style.left]="sidenavWidth + 'px'"
            [style.right]="scrollWidth + 'px'">
  <button md-button
          class="md-hamburger md-icon-button"
          hide-gt-lg
          (click)="menu.open($event)"
          aria-label="Home">
    menu
  </button>
  ssssssssssssss
    Components –
    {{navigation?.currentTitle}}

</md-toolbar>

<md-sidenav-layout layout="row" fullscreen>
  <md-sidenav #menu class="app-menu" mode="over">
    <md-toolbar routerLink="/">

ng2-shop

    </md-toolbar>
    <md-list>
        <md-list-item>

            aaaaaaaaa
        </md-list-item>
        <md-list-item>

            aaaaaaaaa
        </md-list-item>
        <md-list-item>

            aaaaaaaaa
        </md-list-item>
        <md-list-item>

            aaaaaaaaa
        </md-list-item>
        <md-list-item>

            aaaaaaaaa
        </md-list-item>

    </md-list>

  </md-sidenav>

  <md-content #content>
    <md-toolbar color="primary" class="hero">

{{navigation?.currentTitle}}

    </md-toolbar>

      <md-content class="examples" md-scroll-y layout-padding>
        <router-outlet></router-outlet>
      </md-content>

    <docs-footer></docs-footer>

  </md-content>
</md-sidenav-layout>


text:
Pocket-API
=======================

[![Build Status](https://travis-ci.org/rakanalh/pocket-api.svg?branch=master)](https://travis-ci.org/rakanalh/pocket-api)

This package provides a wrapper class around [GetPocket](http://getpocket.com) V3 APIs.

Pocket-CLI
----------

You can checkout [pocket-cli](https://www.github.com/rakanalh/pocket-cli), which is an application for reading / listing /managing your pocket articles from the terminal

Installation
------------

		pip install pocket-api

Usage
--------

First, you have to [Create your consumer key](https://getpocket.com/developer/apps/new) from getpocket's developer console. To get the access token, you have to authorize the app on your own account. There are tools on the web that can automate this for you such as [fxneumann's OneClickPocket](http://reader.fxneumann.de/plugins/oneclickpocket/auth.php)

	from pocket import Pocket, PocketException

	p = Pocket(
		consumer_key='<Your Consumer Key>',
		access_token='<Your Access Token>'
	)

	# Fetch a list of articles
	try:
    	print(p.retrieve(offset=0, count=10))
	except PocketException as e:
    	print(e.message)

    # Add an article
    p.add('https://pymotw.com/3/asyncio/')

	# Start a bulk operation and commit
	p.archive(1186408060).favorite(1188103217).tags_add(
		1168820736, 'Python'
	).tags_add(
		1168820736, 'Web Development'
	).commit()

Methods
-------

* Add an article

		add(url, title, tags, tweet_id)

* Retrieve articles

	    retrieve(state, favorite, tag, contentType,
                 sort, detailType, search, domain,
                 since, count, offset)

Bulk Actions
------------
* Add an article to bulktime_of_action

		bulk_add(item_id, ref_id, tags, time_of_action, title, url)

* Archive article

	    archive(item_id, time_of_action)

* Reread an article

	    readd(item_id, time_of_action)

* Mark article as favorite

	    favorite(item_id, time_of_action)

* Remove favorite mark from article

	    unfavorite(item_id, time_of_action)

* Delete an article from list

	    delete(item_id, time_of_action)

* Add tag to article

	    tags_add(item_id, tags, time_of_action)

* Remove tag from article

	    tags_remove(item_id, tags, time_of_action)

* Replace tags on article

	    tags_replace(item_id, tags, time_of_action)

* Clear tags from article

	    tags_clear(item_id, time_of_action)

* Rename a tag

	    tag_rename(old_tag, new_tag, time_of_action)

* Reset bulk actions (removes all previously registered actions)

	    reset()

* Send request of all bulk items to getpocket

	    commit()


text:
package org.flowable.engine.test.cfg.executioncount;

import java.util.Random;

import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;

public class GenerateRandomValueActivity implements JavaDelegate {

  private static final long serialVersionUID = 1L;

  private static Random random = new Random();

  public void execute(DelegateExecution execution) {
    Integer value = random.nextInt(10);
    execution.setVariable("var", value);
  }

}


text:
import logging

# noinspection PyPackageRequirements
from django.http import HttpResponseBadRequest, JsonResponse, HttpResponseNotFound

from federation.hostmeta.generators import (
    RFC7033Webfinger, generate_nodeinfo2_document, MatrixClientWellKnown, MatrixServerWellKnown,
)
from federation.utils.django import get_configuration, get_function_from_config
from federation.utils.text import get_path_from_url

logger = logging.getLogger("federation")

def nodeinfo2_view(request, *args, **kwargs):
    try:
        nodeinfo2_func = get_function_from_config("nodeinfo2_function")
    except AttributeError:
        return HttpResponseBadRequest("Not configured")
    nodeinfo2 = nodeinfo2_func()

    return JsonResponse(generate_nodeinfo2_document(**nodeinfo2))

def matrix_client_wellknown_view(request, *args, **kwargs):
    try:
        matrix_config_func = get_function_from_config("matrix_config_function")
    except AttributeError:
        return HttpResponseBadRequest("Not configured")
    matrix_config = matrix_config_func()

    wellknown = MatrixClientWellKnown(
        homeserver_base_url=matrix_config["homeserver_base_url"],
        identity_server_base_url=matrix_config.get("identity_server_base_url"),
        other_keys=matrix_config.get("client_wellknown_other_keys"),
    )
    return JsonResponse(wellknown.render())

def matrix_server_wellknown_view(request, *args, **kwargs):
    try:
        matrix_config_func = get_function_from_config("matrix_config_function")
    except AttributeError:
        return HttpResponseBadRequest("Not configured")
    matrix_config = matrix_config_func()

    wellknown = MatrixServerWellKnown(
        homeserver_domain_with_port=matrix_config["homeserver_domain_with_port"],
    )
    return JsonResponse(wellknown.render())

def rfc7033_webfinger_view(request, *args, **kwargs):
    """
    Django view to generate an RFC7033 webfinger.
    """
    resource = request.GET.get("resource")
    if not resource:
        return HttpResponseBadRequest("No resource found")
    if not resource.startswith("acct:"):
        return HttpResponseBadRequest("Invalid resource")
    handle = resource.replace("acct:", "").lower()
    logger.debug(f"{handle} requested with {request}")
    profile_func = get_function_from_config("get_profile_function")

    try:
        profile = profile_func(handle=handle, request=request)
    except Exception as exc:
        logger.warning("rfc7033_webfinger_view - Failed to get profile by handle %s: %s", handle, exc)
        return HttpResponseNotFound()

    config = get_configuration()
    webfinger = RFC7033Webfinger(
        id=profile.id,
        handle=profile.handle,
        guid=profile.guid,
        base_url=config.get('base_url'),
        profile_path=get_path_from_url(profile.url),
        hcard_path=config.get('hcard_path'),
        atom_path=get_path_from_url(profile.atom_url),
        search_path=config.get('search_path'),
    )

    return JsonResponse(
        webfinger.render(),
        content_type="application/jrd+json",
    )