text:
/*jshint quotmark: false */

"use strict";

var rio = require("../lib/rio"),
    vows = require("vows"),
    assert = require("assert");

var isEnablePlaybackMode = process.env.CI === "true";

vows.describe("Image tests").addBatch({
    "first image test": {
        topic: function () {
            rio.enablePlaybackMode(isEnablePlaybackMode, {
                fileName: "test/dump/image-test.bin"
            });

            rio.evaluate("filename <- tempfile('plot', fileext = '.png')\n" +
                "png(filename)\n" +
                "plot(1:10)\n" +
                "dev.off()\n" +
                "image <- readBin(filename, 'raw', 29999)\n" +
                "unlink(filename)\n" +
                "image\n", {
                callback: this.callback
            });
        },

        "get image": function (err, topic) {
            if (!err) {
                // the length depends on graphics system used
                assert(topic.length >= 2259);
            }
        }
    }

}).export(module);


text:
<?php

namespace hipanel\site\widgets;

use Yii;
use yii\base\Widget;

class DomainAvailability extends Widget
{
    public $backgroundImageEn = 'https://ahnames.com/www/flat.skin/images/banner/afilias/en.jpg';

    public $backgroundImageRu = 'https://ahnames.com/www/flat.skin/images/banner/afilias/ru.jpg';

    public function init()
    {
        parent::init();
    }

    public function run()
    {
        $view = Yii::$app->view;
        $internationalizationImage = 'backgroundImage' . ucfirst(substr(Yii::$app->language, 0, 2));
        $view->registerCss(sprintf('.domainavailability { background-image: url(%s); }', $this->$internationalizationImage));

        return $this->render((new\ReflectionClass($this))->getShortName(), []);
    }
}

redpajama_set_name: RedPajamaGithub


text:
lie\_workflow\.tests package
============================

.. automodule:: lie_workflow.tests
    :members:
    :undoc-members:
    :show-inheritance:

Submodules
----------

lie\_workflow\.tests\.dummy\_task\_runners module
-------------------------------------------------

.. automodule:: lie_workflow.tests.dummy_task_runners
    :members:
    :undoc-members:
    :show-inheritance:

lie\_workflow\.tests\.module\_branched\_test module
---------------------------------------------------

.. automodule:: lie_workflow.tests.module_branched_test
    :members:
    :undoc-members:
    :show-inheritance:

lie\_workflow\.tests\.module\_breakpoint\_test module
-----------------------------------------------------

.. automodule:: lie_workflow.tests.module_breakpoint_test
    :members:
    :undoc-members:
    :show-inheritance:

lie\_workflow\.tests\.module\_io\_test module
---------------------------------------------

.. automodule:: lie_workflow.tests.module_io_test
    :members:
    :undoc-members:
    :show-inheritance:

lie\_workflow\.tests\.module\_linear\_test module
-------------------------------------------------

.. automodule:: lie_workflow.tests.module_linear_test
    :members:
    :undoc-members:
    :show-inheritance:


text:
import datetime

import django  # noqa
from django import forms
from django.db import models, migrations
from django.db.migrations.writer import MigrationWriter

import pytest

import olympia  # noqa
from olympia import amo
from olympia.amo.tests import addon_factory, TestCase, safe_exec
from olympia.access.models import Group, GroupUser
from olympia.addons.models import Addon, AddonUser
from olympia.bandwagon.models import Collection, CollectionWatcher
from olympia.reviews.models import Review
from olympia.users.models import (
    DeniedName, UserEmailField, UserProfile,
    UserForeignKey)
from olympia.users.utils import find_users

class TestUserProfile(TestCase):
    fixtures = ('base/addon_3615', 'base/user_2519', 'base/user_4043307',
                'users/test_backends')

    def test_is_developer(self):
        user = UserProfile.objects.get(id=4043307)
        assert not user.addonuser_set.exists()
        assert not user.is_developer

        addon = Addon.objects.get(pk=3615)
        addon.addonuser_set.create(user=user)

        assert not user.is_developer  # it's a cached property...
        del user.is_developer  # ... let's reset it and try again.
        assert user.is_developer

        addon.delete()
        del user.is_developer
        assert not user.is_developer

    def test_delete(self):
        u = UserProfile.objects.get(id='4043307')
        assert u.email == 'jbalogh@mozilla.com'
        u.delete()
        x = UserProfile.objects.get(id='4043307')
        assert x.email is None

    def test_groups_list(self):
        user = UserProfile.objects.get(email='jbalogh@mozilla.com')
        group1 = Group.objects.create(name='un')
        group2 = Group.objects.create(name='deux')
        GroupUser.objects.create(user=user, group=group1)
        GroupUser.objects.create(user=user, group=group2)
        assert user.groups_list == list(user.groups.all())
        assert len(user.groups_list) == 2

        # Remove the user from the groups, groups_list should not have changed
        # since it's a cached property.
        GroupUser.objects.filter(group=group1).delete()
        assert len(user.groups_list) == 2

    def test_welcome_name(self):
        u1 = UserProfile(username='sc')
        u2 = UserProfile(username='sc', display_name="Sarah Connor")
        u3 = UserProfile()
        assert u1.welcome_name == 'sc'
        assert u2.welcome_name == 'Sarah Connor'
        assert u3.welcome_name == ''

    def test_welcome_name_anonymous(self):
        user = UserProfile(
            username='anonymous-bb4f3cbd422e504080e32f2d9bbfcee0')
        assert user.welcome_name == 'Anonymous user bb4f3c'

    def test_welcome_name_anonymous_with_display(self):
        user = UserProfile(display_name='John Connor')
        user.anonymize_username()
        assert user.welcome_name == 'John Connor'

    def test_has_anonymous_username_no_names(self):
        user = UserProfile(display_name=None)
        user.anonymize_username()
        assert user.has_anonymous_username()

    def test_has_anonymous_username_username_set(self):
        user = UserProfile(username='bob', display_name=None)
        assert not user.has_anonymous_username()

    def test_has_anonymous_username_display_name_set(self):
        user = UserProfile(display_name='Bob Bobbertson')
        user.anonymize_username()
        assert user.has_anonymous_username()

    def test_has_anonymous_username_both_names_set(self):
        user = UserProfile(username='bob', display_name='Bob Bobbertson')
        assert not user.has_anonymous_username()

    def test_has_anonymous_display_name_no_names(self):
        user = UserProfile(display_name=None)
        user.anonymize_username()
        assert user.has_anonymous_display_name()

    def test_has_anonymous_display_name_username_set(self):
        user = UserProfile(username='bob', display_name=None)
        assert not user.has_anonymous_display_name()

    def test_has_anonymous_display_name_display_name_set(self):
        user = UserProfile(display_name='Bob Bobbertson')
        user.anonymize_username()
        assert not user.has_anonymous_display_name()

    def test_has_anonymous_display_name_both_names_set(self):
        user = UserProfile(username='bob', display_name='Bob Bobbertson')
        assert not user.has_anonymous_display_name()

    def test_add_admin_powers(self):
        user = UserProfile.objects.get(username='jbalogh')

        assert not user.is_staff
        assert not user.is_superuser
        GroupUser.objects.create(group=Group.objects.get(name='Admins'),
                                 user=user)
        assert user.is_staff
        assert user.is_superuser

    def test_dont_add_admin_powers(self):
        Group.objects.create(name='API', rules='API.Users:*')
        u = UserProfile.objects.get(username='jbalogh')

        GroupUser.objects.create(group=Group.objects.get(name='API'),
                                 user=u)
        assert not u.is_staff
        assert not u.is_superuser

    def test_remove_admin_powers(self):
        Group.objects.create(name='Admins', rules='*:*')
        u = UserProfile.objects.get(username='jbalogh')
        g = GroupUser.objects.create(
            group=Group.objects.filter(name='Admins')[0], user=u)
        g.delete()
        assert not u.is_staff
        assert not u.is_superuser

    def test_picture_url(self):
        """
        Test for a preview URL if image is set, or default image otherwise.
        """
        u = UserProfile(id=1234, picture_type='image/png',
                        modified=datetime.date.today())
        u.picture_url.index('/userpics/0/1/1234.png?modified=')

        u = UserProfile(id=1234567890, picture_type='image/png',
                        modified=datetime.date.today())
        u.picture_url.index('/userpics/1234/1234567/1234567890.png?modified=')

        u = UserProfile(id=1234, picture_type=None)
        assert u.picture_url.endswith('/anon_user.png')

    def test_review_replies(self):
        """
        Make sure that developer replies are not returned as if they were
        original reviews.
        """
        addon = Addon.objects.get(id=3615)
        u = UserProfile.objects.get(pk=2519)
        version = addon.find_latest_public_listed_version()
        new_review = Review(version=version, user=u, rating=2, body='hello',
                            addon=addon)
        new_review.save()
        new_reply = Review(version=version, user=u, reply_to=new_review,
                           addon=addon, body='my reply')
        new_reply.save()

        review_list = [r.pk for r in u.reviews]

        assert len(review_list) == 1
        assert new_review.pk in review_list, (
            'Original review must show up in review list.')
        assert new_reply.pk not in review_list, (
            'Developer reply must not show up in review list.')

    def test_num_addons_listed(self):
        """Test that num_addons_listed is only considering add-ons for which
        the user is marked as listed, and that only public and listed add-ons
        are counted."""
        user = UserProfile.objects.get(id=2519)
        addon = Addon.objects.get(pk=3615)
        AddonUser.objects.create(addon=addon, user=user, listed=True)
        assert user.num_addons_listed == 1

        extra_addon = addon_factory(status=amo.STATUS_NOMINATED)
        AddonUser.objects.create(addon=extra_addon, user=user, listed=True)
        extra_addon2 = addon_factory()
        AddonUser.objects.create(addon=extra_addon2, user=user, listed=True)
        self.make_addon_unlisted(extra_addon2)
        assert user.num_addons_listed == 1

        AddonUser.objects.filter(addon=addon, user=user).update(listed=False)
        assert user.num_addons_listed == 0

    def test_my_addons(self):
        """Test helper method to get N addons."""
        addon1 = Addon.objects.create(name='test-1', type=amo.ADDON_EXTENSION)
        AddonUser.objects.create(addon_id=addon1.id, user_id=2519, listed=True)
        addon2 = Addon.objects.create(name='test-2', type=amo.ADDON_EXTENSION)
        AddonUser.objects.create(addon_id=addon2.id, user_id=2519, listed=True)
        addons = UserProfile.objects.get(id=2519).my_addons()
        assert sorted(a.name for a in addons) == [addon1.name, addon2.name]

    def test_mobile_collection(self):
        u = UserProfile.objects.get(id='4043307')
        assert not Collection.objects.filter(author=u)

        c = u.mobile_collection()
        assert c.type == amo.COLLECTION_MOBILE
        assert c.slug == 'mobile'

    def test_favorites_collection(self):
        u = UserProfile.objects.get(id='4043307')
        assert not Collection.objects.filter(author=u)

        c = u.favorites_collection()
        assert c.type == amo.COLLECTION_FAVORITES
        assert c.slug == 'favorites'

    def test_get_url_path(self):
        assert UserProfile(username='yolo').get_url_path() == (
            '/en-US/firefox/user/yolo/')
        assert UserProfile(username='yolo', id=1).get_url_path() == (
            '/en-US/firefox/user/yolo/')
        assert UserProfile(id=1).get_url_path() == (
            '/en-US/firefox/user/1/')
        assert UserProfile(username='<yolo>', id=1).get_url_path() == (
            '/en-US/firefox/user/1/')

    def test_mobile_addons(self):
        user = UserProfile.objects.get(id='4043307')
        addon1 = Addon.objects.create(name='test-1', type=amo.ADDON_EXTENSION)
        addon2 = Addon.objects.create(name='test-2', type=amo.ADDON_EXTENSION)
        mobile_collection = user.mobile_collection()
        mobile_collection.add_addon(addon1)
        other_collection = Collection.objects.create(name='other')
        other_collection.add_addon(addon2)
        assert user.mobile_addons.count() == 1
        assert user.mobile_addons[0] == addon1.pk

    def test_favorite_addons(self):
        user = UserProfile.objects.get(id='4043307')
        addon1 = Addon.objects.create(name='test-1', type=amo.ADDON_EXTENSION)
        addon2 = Addon.objects.create(name='test-2', type=amo.ADDON_EXTENSION)
        favorites_collection = user.favorites_collection()
        favorites_collection.add_addon(addon1)
        other_collection = Collection.objects.create(name='other')
        other_collection.add_addon(addon2)
        assert user.favorite_addons.count() == 1
        assert user.favorite_addons[0] == addon1.pk

    def test_watching(self):
        user = UserProfile.objects.get(id='4043307')
        watched_collection1 = Collection.objects.create(name='watched-1')
        watched_collection2 = Collection.objects.create(name='watched-2')
        Collection.objects.create(name='other')
        CollectionWatcher.objects.create(user=user,
                                         collection=watched_collection1)
        CollectionWatcher.objects.create(user=user,
                                         collection=watched_collection2)
        assert len(user.watching) == 2
        assert tuple(user.watching) == (watched_collection1.pk,
                                        watched_collection2.pk)

    def test_cannot_set_password(self):
        user = UserProfile.objects.get(id='4043307')
        with self.assertRaises(NotImplementedError):
            user.set_password('password')

    def test_cannot_check_password(self):
        user = UserProfile.objects.get(id='4043307')
        with self.assertRaises(NotImplementedError):
            user.check_password('password')

    def test_get_session_auth_hash(self):
        user = UserProfile.objects.get(id=4043307)
        user.update(auth_id=None)
        assert user.get_session_auth_hash() is None

        user.update(auth_id=12345)
        hash1 = user.get_session_auth_hash()
        assert hash1

        user.update(auth_id=67890)
        hash2 = user.get_session_auth_hash()
        assert hash1 != hash2

class TestDeniedName(TestCase):
    fixtures = ['users/test_backends']

    def test_blocked(self):
        assert DeniedName.blocked('IE6Fan')
        assert DeniedName.blocked('IE6fantastic')
        assert not DeniedName.blocked('IE6')
        assert not DeniedName.blocked('testo')

class TestUserEmailField(TestCase):
    fixtures = ['base/user_2519']

    def test_success(self):
        user = UserProfile.objects.get(pk=2519)
        assert UserEmailField().clean(user.email) == user

    def test_failure(self):
        with pytest.raises(forms.ValidationError):
            UserEmailField().clean('xxx')

    def test_empty_email(self):
        UserProfile.objects.create(email='')
        with pytest.raises(forms.ValidationError) as exc_info:
            UserEmailField().clean('')

        assert exc_info.value.messages[0] == 'This field is required.'

class TestUserHistory(TestCase):

    def test_user_history(self):
        user = UserProfile.objects.create(email='foo@bar.com')
        assert user.history.count() == 0
        user.update(email='foopy@barby.com')
        assert user.history.count() == 1
        user.update(email='foopy@barby.com')
        assert user.history.count() == 1

    def test_user_find(self):
        user = UserProfile.objects.create(email='luke@jedi.com')
        # Checks that you can have multiple copies of the same email and
        # that we only get distinct results back.
        user.update(email='dark@sith.com')
        user.update(email='luke@jedi.com')
        user.update(email='dark@sith.com')
        assert [user] == list(find_users('luke@jedi.com'))
        assert [user] == list(find_users('dark@sith.com'))

    def test_user_find_multiple(self):
        user_1 = UserProfile.objects.create(username='user_1',
                                            email='luke@jedi.com')
        user_1.update(email='dark@sith.com')
        user_2 = UserProfile.objects.create(username='user_2',
                                            email='luke@jedi.com')
        assert [user_1, user_2] == list(find_users('luke@jedi.com'))

class TestUserManager(TestCase):
    fixtures = ('users/test_backends', )

    def test_create_user(self):
        user = UserProfile.objects.create_user("test", "test@test.com", 'xxx')
        assert user.pk is not None

    def test_create_superuser(self):
        user = UserProfile.objects.create_superuser(
            "test",
            "test@test.com",
        )
        assert user.pk is not None
        Group.objects.get(name="Admins") in user.groups.all()
        assert user.is_staff
        assert user.is_superuser

def test_user_foreign_key_supports_migration():
    """Tests serializing UserForeignKey in a simple migration.

    Since `UserForeignKey` is a ForeignKey migrations pass `to=` explicitly
    and we have to pop it in our __init__.
    """
    fields = {
        'charfield': UserForeignKey(),
    }

    migration = type(str('Migration'), (migrations.Migration,), {
        'operations': [
            migrations.CreateModel(
                name='MyModel', fields=tuple(fields.items()),
                bases=(models.Model,)
            ),
        ],
    })
    writer = MigrationWriter(migration)
    output = writer.as_string()

    # Just make sure it runs and that things look alright.
    result = safe_exec(output, globals_=globals())

    assert 'Migration' in result

def test_user_foreign_key_field_deconstruct():
    field = UserForeignKey()
    name, path, args, kwargs = field.deconstruct()
    new_field_instance = UserForeignKey()

    assert kwargs['to'] == new_field_instance.to


text:
require 'spec_helper'

describe RedisModel::Types::String do
  let(:klass) { dynamic_class(RedisModel::Base) }
  let(:object) { klass.new }

  before { klass.data_type :string }

  describe '#get' do
    context 'when no value was set before' do
      it { expect(object.get).to be_nil }
    end

    context 'when value was set before' do
      let(:value) { 'hi' }

      before { RedisModel::Base.connection.set(object.key_label, value) }

      it { expect(object.get).to eq(value) }
    end
  end

  describe '#set' do
    context 'when value was set before' do
      it { expect { object.set('value') }.to change { RedisModel::Base.connection.get object.key_label } }
    end
  end
end


text:
class Metronome : public QObject
{
    Q_OBJECT
    Q_PROPERTY(quint16 tempo READ tempo WRITE setTempo NOTIFY tempoChanged)
    Q_PROPERTY(quint8 numenator READ numenator WRITE setNumenator NOTIFY numenatorChanged)
    Q_PROPERTY(quint8 maximumNumenator READ maximumNumenator WRITE setMaximumNumenator NOTIFY maximumNumenatorChanged)
    Q_PROPERTY(quint8 denumenator READ denumenator WRITE setDenumenator NOTIFY denumenatorChanged)
    Q_PROPERTY(quint8 denumenatorPower READ denumenatorPower WRITE setDenumenatorPower NOTIFY denumenatorPowerChanged)
    Q_PROPERTY(bool playing READ playing WRITE setPlaying NOTIFY playingChanged)
    Q_PROPERTY(QString sound READ sound WRITE setSound NOTIFY soundChanged)
//    Q_PROPERTY(bool inFourths READ inFourths WRITE setInFourths NOTIFY inFourthsChanged)
public:
    explicit Metronome(QObject *parent = 0);
    ~Metronome();

    quint16 tempo();
    void setTempo (quint16 &newTempo);

    quint8 numenator();
    void setNumenator (quint8& newNumenator);

    quint8 denumenator();
    void setDenumenator (quint8& newDenumenator);

    quint8 denumenatorPower();
    void setDenumenatorPower(quint8& newDenumenatorPower);

    bool playing();
    void setPlaying(bool newPlaying);

    QString sound();
    void setSound(QString newSound);

    quint8 maximumNumenator();
    void setMaximumNumenator(quint8& newMaximumNumenator);

//    bool inFourths();
//    void setInFourths(bool newInFourths);

public slots:

    void updateCount();
    void updateSound();

private:
    quint16 _tempo;
    quint8 _numenator;
    quint8 _maximumNumenator;
    quint8 _denumenatorPower;
    quint8 _denumenator;
    bool _playing;
    QSoundEffect* _clickHigh;
    QSoundEffect* _clickLow;
    QTimer* _timer;
    quint8 currentBeat;
    QString* path;
    QString _sound;
//    bool _inFourths;

    void clickInsideThread();

signals:
    void tempoChanged();
    void numenatorChanged();
    void numenatorPowerChanged();
    void denumenatorPowerChanged();
    void denumenatorChanged();
    void playingChanged();
    void metronomeChanged();
    void soundChanged();
    void maximumNumenatorChanged();
//    void inFourthsChanged();

private slots:
    void click();
    void playStop();
    void updateMaximumNumenator();
};

#endif // METRONOME_H


text:
from setuptools import setup

setup(
    name="pyrax-identity-hubic",
    version='0.1',
    description="HubiC identity module for rackspace's pyrax",
    author="Gu1",
    author_email="gu1@aeroxteam.fr",
    url="https://github.com/rackspace/pyrax",
    keywords="hubic pyrax cloud openstack",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 2",
    ],
    install_requires=[
        'pyrax>=1.6.4',
    ],
    py_modules=['pyrax_identity_hubic'],
    test_suite='test_pyrax_identity_hubic'
)


text:
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h

#ifndef __C_VIDEO_NULL_H_INCLUDED__
#define __C_VIDEO_NULL_H_INCLUDED__

#include "IVideoDriver.h"
#include "IFileSystem.h"
#include "IGPUProgrammingServices.h"
#include "irr/asset/IMesh.h"
#include "irr/video/IGPUMeshBuffer.h"
#include "IMeshSceneNode.h"
#include "CFPSCounter.h"
#include "SExposedVideoData.h"
#include "FW_Mutex.h"

#ifdef _MSC_VER
#pragma warning( disable: 4996)
#endif

namespace irr
{
namespace io
{
	class IWriteFile;
	class IReadFile;
} // end namespace io
namespace video
{
	class IImageLoader;
	class IImageWriter;

	class CNullDriver : public IVideoDriver, public IGPUProgrammingServices
	{
    protected:
		//! destructor
		virtual ~CNullDriver();

	public:
        static FW_AtomicCounter ReallocationCounter;
        static int32_t incrementAndFetchReallocCounter();

		//! constructor
		CNullDriver(IrrlichtDevice* dev, io::IFileSystem* io, const core::dimension2d<uint32_t>& screenSize);

        inline virtual bool isAllowedVertexAttribFormat(asset::E_FORMAT _fmt) const override { return false; }
        inline virtual bool isColorRenderableFormat(asset::E_FORMAT _fmt) const override { return false; }
        inline virtual bool isAllowedImageStoreFormat(asset::E_FORMAT _fmt) const override { return false; }
        inline virtual bool isAllowedTextureFormat(asset::E_FORMAT _fmt) const override { return false; }
        inline virtual bool isHardwareBlendableFormat(asset::E_FORMAT _fmt) const override { return false; }

		//!
        virtual bool initAuxContext() {return false;}
        virtual bool deinitAuxContext() {return false;}

		virtual bool beginScene(bool backBuffer=true, bool zBuffer=true,
				SColor color=SColor(255,0,0,0),
				const SExposedVideoData& videoData=SExposedVideoData(),
				core::rect<int32_t>* sourceRect=0);

		virtual bool endScene();

		//!
		virtual void issueGPUTextureBarrier() {}

		//! sets transformation
		virtual void setTransform(const E_4X3_TRANSFORMATION_STATE& state, const core::matrix3x4SIMD& mat);
		virtual void setTransform(const E_PROJECTION_TRANSFORMATION_STATE& state, const core::matrix4SIMD& mat);

		//! sets a material
		virtual void setMaterial(const SGPUMaterial& material);

        //! GPU fence, is signalled when preceeding GPU work is completed
        virtual core::smart_refctd_ptr<IDriverFence> placeFence(const bool& implicitFlushWaitSameThread=false) {return nullptr;}

        core::smart_refctd_ptr<ITexture> createGPUTexture(const ITexture::E_TEXTURE_TYPE& type, const uint32_t* size, uint32_t mipmapLevels, asset::E_FORMAT format = asset::EF_B8G8R8A8_UNORM) override;

		//! A.
        virtual E_MIP_CHAIN_ERROR validateMipChain(const ITexture* tex, const core::vector<asset::CImageData*>& mipChain)
        {
            if (!tex)
                return EMCE_OTHER_ERR;

            if (mipChain.size()==0)
                return EMCE_NO_ERR;

            for (core::vector<asset::CImageData*>::const_iterator it = mipChain.begin(); it!=mipChain.end(); it++)
            {
                asset::CImageData* img = *it;
                if (!img)
                    return EMCE_INVALID_IMAGE;

                const uint32_t mipLevel = img->getSupposedMipLevel();
                if (mipLevel>=tex->getMipMapLevelCount())
                    return EMCE_MIP_LEVEL_OUT_OF_BOUND;

                core::vector3d<uint32_t> textureSizeAtThisMipLevel = *reinterpret_cast< const core::vector3d<uint32_t>* >(tex->getSize());
                textureSizeAtThisMipLevel /= core::vector3d<uint32_t>(0x1u<<mipLevel);
                if (textureSizeAtThisMipLevel.X==0)
                    textureSizeAtThisMipLevel.X = 1;
                if (textureSizeAtThisMipLevel.Y==0)
                    textureSizeAtThisMipLevel.Y = 1;
                if (textureSizeAtThisMipLevel.Z==0)
                    textureSizeAtThisMipLevel.Z = 1;

                core::aabbox3d<uint32_t> imgCube(core::vector3d<uint32_t>(img->getSliceMin()),core::vector3d<uint32_t>(img->getSliceMax()));
                if (!imgCube.isFullInside(core::aabbox3d<uint32_t>(core::vector3d<uint32_t>(0,0,0),textureSizeAtThisMipLevel)))
                    return EMCE_SUB_IMAGE_OUT_OF_BOUNDS;
            }

            return EMCE_NO_ERR;
        }

		//! Sets new multiple render targets.
		virtual bool setRenderTarget(IFrameBuffer* frameBuffer, bool setNewViewport=true);

		//! Clears the ZBuffer.
		/** Note that you usually need not to call this method, as it
		is automatically done in IVideoDriver::beginScene() or
		IVideoDriver::setRenderTarget() if you enable zBuffer. But if
		you have to render some special things, you can clear the
		zbuffer during the rendering process with this method any time.
		*/
		virtual void clearZBuffer(const float &depth=0.0);

		virtual void clearStencilBuffer(const int32_t &stencil);

		virtual void clearZStencilBuffers(const float &depth, const int32_t &stencil);

		virtual void clearColorBuffer(const E_FBO_ATTACHMENT_POINT &attachment, const int32_t* vals);
		virtual void clearColorBuffer(const E_FBO_ATTACHMENT_POINT &attachment, const uint32_t* vals);
		virtual void clearColorBuffer(const E_FBO_ATTACHMENT_POINT &attachment, const float* vals);

		virtual void clearScreen(const E_SCREEN_BUFFERS &buffer, const float* vals);
		virtual void clearScreen(const E_SCREEN_BUFFERS &buffer, const uint32_t* vals);

		virtual ITransformFeedback* createTransformFeedback() {return NULL;}

		//!
		virtual void bindTransformFeedback(ITransformFeedback* xformFeedback);

		virtual ITransformFeedback* getBoundTransformFeedback() {return NULL;}

        /** Only POINTS, LINES, and TRIANGLES are allowed as capture types.. no strips or fans!
        This issues an implicit call to bindTransformFeedback()
        **/
		virtual void beginTransformFeedback(ITransformFeedback* xformFeedback, const E_MATERIAL_TYPE& xformFeedbackShader, const asset::E_PRIMITIVE_TYPE& primType=asset::EPT_POINTS);

		//! A redundant wrapper call to ITransformFeedback::pauseTransformFeedback(), made just for clarity
		virtual void pauseTransformFeedback();

		//! A redundant wrapper call to ITransformFeedback::pauseTransformFeedback(), made just for clarity
		virtual void resumeTransformFeedback();

		virtual void endTransformFeedback();

		//! sets a viewport
		virtual void setViewPort(const core::rect<int32_t>& area);

		//! gets the area of the current viewport
		virtual const core::rect<int32_t>& getViewPort() const;

        virtual void drawMeshBuffer(const video::IGPUMeshBuffer* mb);

		//! Indirect Draw
		virtual void drawArraysIndirect( const asset::IMeshDataFormatDesc<video::IGPUBuffer>* vao,
                                         const asset::E_PRIMITIVE_TYPE& mode,
                                         const IGPUBuffer* indirectDrawBuff,
                                         const size_t& offset, const size_t& count, const size_t& stride);
		virtual void drawIndexedIndirect(const asset::IMeshDataFormatDesc<video::IGPUBuffer>* vao,
                                         const asset::E_PRIMITIVE_TYPE& mode,
                                         const asset::E_INDEX_TYPE& type,
                                         const IGPUBuffer* indirectDrawBuff,
                                         const size_t& offset, const size_t& count, const size_t& stride);

		//! draws an 2d image
		virtual void draw2DImage(const video::ITexture* texture, const core::position2d<int32_t>& destPos);

		//! draws a set of 2d images, using a color and the alpha
		/** channel of the texture if desired. The images are drawn
		beginning at pos and concatenated in one line. All drawings
		are clipped against clipRect (if != 0).
		The subtextures are defined by the array of sourceRects
		and are chosen by the indices given.
		\param texture: Texture to be drawn.
		\param pos: Upper left 2d destination position where the image will be drawn.
		\param sourceRects: Source rectangles of the image.
		\param indices: List of indices which choose the actual rectangle used each time.
		\param kerningWidth: offset on position
		\param clipRect: Pointer to rectangle on the screen where the image is clipped to.
		This pointer can be 0. Then the image is not clipped.
		\param color: Color with which the image is colored.
		Note that the alpha component is used: If alpha is other than 255, the image will be transparent.
		\param useAlphaChannelOfTexture: If true, the alpha channel of the texture is
		used to draw the image. */
		virtual void draw2DImageBatch(const video::ITexture* texture,
				const core::position2d<int32_t>& pos,
				const core::vector<core::rect<int32_t> >& sourceRects,
				const core::vector<int32_t>& indices,
				int32_t kerningWidth = 0,
				const core::rect<int32_t>* clipRect = 0,
				SColor color=SColor(255,255,255,255),
				bool useAlphaChannelOfTexture=false);

		//! Draws a set of 2d images, using a color and the alpha channel of the texture.
		/** All drawings are clipped against clipRect (if != 0).
		The subtextures are defined by the array of sourceRects and are
		positioned using the array of positions.
		\param texture Texture to be drawn.
		\param pos Array of upper left 2d destinations where the images
		will be drawn.
		\param sourceRects Source rectangles of the image.
		\param clipRect Pointer to rectangle on the screen where the
		images are clipped to.
		If this pointer is 0 then the image is not clipped.
		\param color Color with which the image is drawn.
		Note that the alpha component is used. If alpha is other than
		255, the image will be transparent.
		\param useAlphaChannelOfTexture: If true, the alpha channel of
		the texture is used to draw the image. */
		virtual void draw2DImageBatch(const video::ITexture* texture,
				const core::vector<core::position2d<int32_t> >& positions,
				const core::vector<core::rect<int32_t> >& sourceRects,
				const core::rect<int32_t>* clipRect=0,
				SColor color=SColor(255,255,255,255),
				bool useAlphaChannelOfTexture=false);

		//! Draws a 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
		virtual void draw2DImage(const video::ITexture* texture, const core::position2d<int32_t>& destPos,
			const core::rect<int32_t>& sourceRect, const core::rect<int32_t>* clipRect = 0,
			SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false);

		//! Draws a part of the texture into the rectangle.
		virtual void draw2DImage(const video::ITexture* texture, const core::rect<int32_t>& destRect,
			const core::rect<int32_t>& sourceRect, const core::rect<int32_t>* clipRect = 0,
			const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false);

		//! Draws a 2d rectangle
		virtual void draw2DRectangle(SColor color, const core::rect<int32_t>& pos, const core::rect<int32_t>* clip = 0);

		//! Draws a 2d rectangle with a gradient.
		virtual void draw2DRectangle(const core::rect<int32_t>& pos,
			SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
			const core::rect<int32_t>* clip = 0);

		//! Draws the outline of a 2d rectangle
		virtual void draw2DRectangleOutline(const core::recti& pos, SColor color=SColor(255,255,255,255));

		//! Draws a 2d line.
		virtual void draw2DLine(const core::position2d<int32_t>& start,
					const core::position2d<int32_t>& end,
					SColor color=SColor(255,255,255,255));

		//! get color format of the current color buffer
		virtual asset::E_FORMAT getColorFormat() const;

		//! get screen size
		virtual const core::dimension2d<uint32_t>& getScreenSize() const;

		//! get render target size
		virtual const core::dimension2d<uint32_t>& getCurrentRenderTargetSize() const;

		// get current frames per second value
		virtual int32_t getFPS() const;

		//! returns amount of primitives (mostly triangles) were drawn in the last frame.
		//! very useful method for statistics.
		virtual uint32_t getPrimitiveCountDrawn( uint32_t param = 0 ) const;

		//! \return Returns the name of the video driver. Example: In case of the DIRECT3D8
		//! driver, it would return "Direct3D8.1".
		virtual const wchar_t* getName() const;

		virtual void removeMultisampleTexture(IMultisampleTexture* tex);

		virtual void removeTextureBufferObject(ITextureBufferObject* tbo);

		virtual void removeFrameBuffer(IFrameBuffer* framebuf);

		virtual void removeAllMultisampleTextures();

		virtual void removeAllTextureBufferObjects();

		virtual void removeAllFrameBuffers();

		virtual void blitRenderTargets(IFrameBuffer* in, IFrameBuffer* out,
                                        bool copyDepth=true, bool copyStencil=true,
										core::recti srcRect=core::recti(0,0,0,0),
										core::recti dstRect=core::recti(0,0,0,0),
										bool bilinearFilter=false);

		//! Returns the maximum amount of primitives (mostly vertices) which
		//! the device is able to render with one drawIndexedTriangleList
		//! call.
		virtual uint32_t getMaximalIndicesCount() const;

		//! Enables or disables a texture creation flag.
		virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled);

		//! Returns if a texture creation flag is enabled or disabled.
		virtual bool getTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag) const;

	public:
		virtual void beginQuery(IQueryObject* query);
		virtual void endQuery(IQueryObject* query);
		virtual void beginQuery(IQueryObject* query, const size_t& index);
		virtual void endQuery(IQueryObject* query, const size_t& index);

		//! Only used by the engine internally.
		/** Used to notify the driver that the window was resized. */
		virtual void OnResize(const core::dimension2d<uint32_t>& size);

		//! Adds a new material renderer to the video device.
		virtual int32_t addMaterialRenderer(IMaterialRenderer* renderer,
				const char* name = 0);

		//! Returns driver and operating system specific data about the IVideoDriver.
		virtual const SExposedVideoData& getExposedVideoData();

		//! Returns type of video driver
		virtual E_DRIVER_TYPE getDriverType() const;

		//! Returns the transformation set by setTransform
		virtual const core::matrix3x4SIMD& getTransform(const E_4X3_TRANSFORMATION_STATE& state) override;

		virtual const core::matrix4SIMD& getTransform(const E_PROJECTION_TRANSFORMATION_STATE& state) override;

		//! Returns pointer to the IGPUProgrammingServices interface.
		virtual IGPUProgrammingServices* getGPUProgrammingServices();

		//! Returns pointer to material renderer or null
		virtual IMaterialRenderer* getMaterialRenderer(uint32_t idx);

		//! Returns amount of currently available material renderers.
		virtual uint32_t getMaterialRendererCount() const;

		//! Returns name of the material renderer
		virtual const char* getMaterialRendererName(uint32_t idx) const;

        virtual int32_t addHighLevelShaderMaterial(
            const char* vertexShaderProgram,
            const char* controlShaderProgram,
            const char* evaluationShaderProgram,
            const char* geometryShaderProgram,
            const char* pixelShaderProgram,
            uint32_t patchVertices=3,
            E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
            IShaderConstantSetCallBack* callback = 0,
            const char** xformFeedbackOutputs = NULL,
            const uint32_t& xformFeedbackOutputCount = 0,
            int32_t userData = 0,
            const char* vertexShaderEntryPointName="main",
            const char* controlShaderEntryPointName = "main",
            const char* evaluationShaderEntryPointName = "main",
            const char* geometryShaderEntryPointName = "main",
            const char* pixelShaderEntryPointName="main" );

        virtual int32_t addHighLevelShaderMaterialFromFiles(
            const io::path& vertexShaderProgramFileName,
            const io::path& controlShaderProgramFileName,
            const io::path& evaluationShaderProgramFileName,
            const io::path& geometryShaderProgramFileName,
            const io::path& pixelShaderProgramFileName,
            uint32_t patchVertices=3,
            E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
            IShaderConstantSetCallBack* callback = 0,
            const char** xformFeedbackOutputs = NULL,
            const uint32_t& xformFeedbackOutputCount = 0,
            int32_t userData = 0,
            const char* vertexShaderEntryPointName="main",
            const char* controlShaderEntryPointName = "main",
            const char* evaluationShaderEntryPointName = "main",
            const char* geometryShaderEntryPointName = "main",
            const char* pixelShaderEntryPointName="main");

        virtual int32_t addHighLevelShaderMaterialFromFiles(
            io::IReadFile* vertexShaderProgram,
            io::IReadFile* controlShaderProgram,
            io::IReadFile* evaluationShaderProgram,
            io::IReadFile* geometryShaderProgram,
            io::IReadFile* pixelShaderProgram,
            uint32_t patchVertices=3,
            E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
            IShaderConstantSetCallBack* callback = 0,
            const char** xformFeedbackOutputs = NULL,
            const uint32_t& xformFeedbackOutputCount = 0,
            int32_t userData = 0,
            const char* vertexShaderEntryPointName="main",
            const char* controlShaderEntryPointName = "main",
            const char* evaluationShaderEntryPointName = "main",
            const char* geometryShaderEntryPointName = "main",
            const char* pixelShaderEntryPointName="main");

        virtual bool replaceHighLevelShaderMaterial(const int32_t &materialIDToReplace,
            const char* vertexShaderProgram,
            const char* controlShaderProgram,
            const char* evaluationShaderProgram,
            const char* geometryShaderProgram,
            const char* pixelShaderProgram,
            uint32_t patchVertices=3,
            E_MATERIAL_TYPE baseMaterial=video::EMT_SOLID,
            IShaderConstantSetCallBack* callback=0,
            const char** xformFeedbackOutputs = NULL,
            const uint32_t& xformFeedbackOutputCount = 0,
            int32_t userData=0,
            const char* vertexShaderEntryPointName="main",
            const char* controlShaderEntryPointName="main",
            const char* evaluationShaderEntryPointName="main",
            const char* geometryShaderEntryPointName="main",
            const char* pixelShaderEntryPointName="main");

		//! Sets the name of a material renderer.
		virtual void setMaterialRendererName(int32_t idx, const char* name);

		//! Enable/disable a clipping plane.
		//! There are at least 6 clipping planes available for the user to set at will.
		//! \param index: The plane index. Must be between 0 and MaxUserClipPlanes.
		//! \param enable: If true, enable the clipping plane else disable it.
		virtual void enableClipPlane(uint32_t index, bool enable);

		//! Returns the graphics card vendor name.
		virtual std::string getVendorInfo() {return "Not available on this driver.";}

		//! Get the 2d override material for altering its values
		virtual SGPUMaterial& getMaterial2D();

		//! Enable the 2d override material
		virtual void enableMaterial2D(bool enable=true);

		//! Returns the maximum texture size supported.
		virtual const uint32_t* getMaxTextureSize(const ITexture::E_TEXTURE_TYPE& type) const;

		//!
		virtual uint32_t getRequiredUBOAlignment() const override {return 0u;}

		//!
		virtual uint32_t getRequiredSSBOAlignment() const override {return 0u;}

		//!
		virtual uint32_t getRequiredTBOAlignment() const override {return 0u;}

        virtual uint32_t getMaxComputeWorkGroupSize(uint32_t) const override { return 0u; }

        virtual uint64_t getMaxUBOSize() const override { return 0ull; }

        virtual uint64_t getMaxSSBOSize() const override { return 0ull; }

        virtual uint64_t getMaxTBOSize() const override { return 0ull; }

        virtual uint64_t getMaxBufferSize() const override { return 0ull; }

	protected:
        void addMultisampleTexture(IMultisampleTexture* tex);

        void addTextureBufferObject(ITextureBufferObject* tbo);

		//! returns a device dependent texture from a software surface (IImage)
		//! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES
		virtual core::smart_refctd_ptr<video::ITexture> createDeviceDependentTexture(const ITexture::E_TEXTURE_TYPE& type, const uint32_t* size, uint32_t mipmapLevels, const io::path& name, asset::E_FORMAT format = asset::EF_B8G8R8A8_UNORM);

		// adds a material renderer and drops it afterwards. To be used for internal creation
		int32_t addAndDropMaterialRenderer(IMaterialRenderer* m);

		//! deletes all material renderers
		void deleteMaterialRenders();

		// prints renderer version
		void printVersion();

    protected:
		struct SSurface
		{
			video::ITexture* Surface;

			bool operator < (const SSurface& other) const
			{
			    return Surface->getName()<other.Surface->getName();
			    /*
			    int res = strcmp(Surface->getName().getInternalName().c_str(),other.Surface->getName().getInternalName().c_str());
			    if (res<0)
                    return true;
                else if (res>0)
                    return false;
                else
                    return Surface < other.Surface;
                */
			}
		};

		struct SMaterialRenderer
		{
			core::stringc Name;
			IMaterialRenderer* Renderer;
		};

		class SDummyTexture : public ITexture
		{
                _IRR_INTERFACE_CHILD(SDummyTexture) {}

                core::dimension2d<uint32_t> size;
		    public:
                SDummyTexture(const io::path& name) : ITexture(IDriverMemoryBacked::SDriverMemoryRequirements{{0,0,0},0,0,0,0},name), size(0,0)
                {
                }

                //special override as this object is always placement new'ed
                static inline void operator delete(void* ptr) noexcept
                {
                    return;
                }

                virtual E_DIMENSION_COUNT getDimensionality() const {return EDC_TWO;}
                virtual E_TEXTURE_TYPE getTextureType() const {return ETT_2D;}
                virtual E_VIRTUAL_TEXTURE_TYPE getVirtualTextureType() const {return EVTT_OPAQUE_FILTERABLE;}
                virtual const uint32_t* getSize() const { return &size.Width; }
                virtual uint32_t getMipMapLevelCount() const {return 1;}
                virtual core::dimension2du getRenderableSize() const { return size; }
                virtual E_DRIVER_TYPE getDriverType() const { return video::EDT_NULL; }
                virtual asset::E_FORMAT getColorFormat() const { return asset::EF_A1R5G5B5_UNORM_PACK16; }
                virtual core::rational<uint32_t> getPitch() const { return {0u,1u}; }
                virtual void regenerateMipMapLevels() {}
                virtual bool updateSubRegion(const asset::E_FORMAT &inDataColorFormat, const void* data, const uint32_t* minimum, const uint32_t* maximum, int32_t mipmap=0, const uint32_t& unpackRowByteAlignment=0) {return false;}
                virtual bool resize(const uint32_t* size, const uint32_t& mipLevels=0) {return false;}

                virtual IDriverMemoryAllocation* getBoundMemory() {return nullptr;}
                virtual const IDriverMemoryAllocation* getBoundMemory() const {return nullptr;}
                virtual size_t getBoundMemoryOffset() const {return 0u;}
		};

		core::vector<IMultisampleTexture*> MultisampleTextures;
		core::vector<ITextureBufferObject*> TextureBufferObjects;

		core::vector<SMaterialRenderer> MaterialRenderers;

        IQueryObject* currentQuery[EQOT_COUNT][_IRR_XFORM_FEEDBACK_MAX_STREAMS_];

		io::IFileSystem* FileSystem;

		core::rect<int32_t> ViewPort;
		core::dimension2d<uint32_t> ScreenSize;

		uint32_t matrixModifiedBits;
		core::matrix4SIMD ProjectionMatrices[EPTS_COUNT];
		core::matrix3x4SIMD TransformationMatrices[E4X3TS_COUNT];

		CFPSCounter FPSCounter;

        video::IGPUMeshBuffer* boxLineMesh;

		uint32_t PrimitivesDrawn;

		uint32_t TextureCreationFlags;

		SExposedVideoData ExposedData;

		SGPUMaterial OverrideMaterial2D;
		SGPUMaterial InitMaterial2D;
		bool OverrideMaterial2DEnabled;

		uint32_t MaxTextureSizes[ITexture::ETT_COUNT][3];
	};

} // end namespace video
} // end namespace irr

#endif


text:
import {Injectable} from 'angular2/core';

@Injectable()
export class Logger {
    log(msg: any) { console.log(msg); }
    error(msg: any) { console.error(msg); }
    warn(msg: any) { console.warn(msg); }
}


text:
@interface PodsDummy_DMPickerView : NSObject
@end
@implementation PodsDummy_DMPickerView
@end


text:
try:
    import j2p2j
except ImportError:
    import sys, os
    sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
    import j2p2j
    from tornado import gen

class MyApp(j2p2j.Application):
    pass

class MyClient(j2p2j.Client):
    def __init__(self):
        super(MyClient, self).__init__()
        self.counter = 0
        self.boxes = []

    def register(self):
        registerEvents = {
            "method":"REGISTER",
            "events":[
                {"element":"#add_new_box", "event": "click","method":"addBox"},
                {"element":"#delete_last_box", "event": "click","method":"delete_last_box"},
                {"element":"#add_inputs", "event": "click","method":"addInputs"}
            ]
        }
        return registerEvents

    @gen.coroutine
    def addInputs(self):
        print("Getting input value")
        send = {"method": "READ"}
        send["location"] = ".inputs"
        send["toGet"] = "attribute"
        send["get"] = "value"
        result = yield self.get(send)
        addition = sum([int(x) for x in list(result)])
        send = {"method": "UPDATE"}
        send["location"] = "#total"
        send["toChange"] = "html"
        send["edit"] = addition
        print("Updating input")
        return send

    def addBox(self):
        print("adding box")
        send = {"method": "CREATE"}
        send["type"] = "input"
        send["location"] = "#boxes"
        send["attributes"] = {"type":"number","value":"0", "class":"inputs"}
        return send

    def delete_last_box(self):
        send = {"method": "DELETE"}
        send["location"] = "#boxes input:last-child"
        return send

if __name__ == '__main__':
    a = MyApp('appFiles/index.html', MyClient)
    a.run()


text:
#include "gfx.h"

#include <stdio.h>

/*
 * This demo demonstrates two ways to talk to multiple displays.
 *
 * Method 1 is the preferred way however Method 2 would be useful
 * when quickly converting existing single display applications.
 *
 * Note you can combine the methods using method 2 for the first display
 * and method 1 for any extra displays.
 */

#define USE_METHOD_1		FALSE

#if USE_METHOD_1
	int main(void) {
		coord_t		width, height;
		coord_t		display, i, j, cnt;
		font_t		f;
		GDisplay	*g;
		char		buf[16];

		/* Initialize and clear the display */
		gfxInit();

		/* Get a font to write with */
		f = gdispOpenFont("*");

		/* Cycle through each display */
		cnt = gdispGetDisplayCount();
		for(display = 0; display < cnt; display++) {

			// Get the specified display
			g = gdispGetDisplay(display);

			// Get the screen size
			width = gdispGGetWidth(g);
			height = gdispGGetHeight(g);

			/* Draw draw draw */
			sprintg(buf, "Display %u", display);
			if (width < 128) {
				gdispGDrawBox(g, 0, 0, width/2, height/2, Yellow);
				gdispGFillStringBox(g, 0, height/2, width, height/2, buf, f, Black, uBlue, justifyCenter);
			} else {
				gdispGDrawBox(g, 10, 10, width/2, height/2, Yellow);
				gdispGFillStringBox(g, width/2, height/2, width/2-10, height/2-10, buf, f, White, uBlue, justifyCenter);
			}
			gdispGDrawLine(g, 5, 30, width-50, height-40, uRed);

			for(i = 5, j = 0; i < width && j < height; i += 7, j += i/20)
				gdispGDrawPixel(g, i, j, White);
		}

		while(TRUE) {
			gfxSleepMilliseconds(500);
		}
	}
#else
	int main(void) {
		coord_t		width, height;
		coord_t		display, i, j, cnt;
		font_t		f;
		char		buf[16];

		/* Initialize and clear the display */
		gfxInit();

		/* Get a font to write with */
		f = gdispOpenFont("*");

		/* Cycle through each display */
		cnt = gdispGetDisplayCount();
		for(display = 0; display < cnt; display++) {

			// Set the default display to the specified display
			gdispSetDisplay(gdispGetDisplay(display));

			// Get the screen size
			width = gdispGetWidth();
			height = gdispGetHeight();

			/* Draw draw draw */
			sprintg(buf, "Display %u", display);
			if (width < 128) {
				gdispDrawBox(0, 0, width/2, height/2, Yellow);
				gdispFillStringBox(0, height/2, width, height/2, buf, f, Black, uBlue, justifyCenter);
			} else {
				gdispDrawBox(10, 10, width/2, height/2, Yellow);
				gdispFillStringBox(width/2, height/2, width/2-10, height/2-10, buf, f, White, uBlue, justifyCenter);
			}
			gdispDrawLine(5, 30, width-50, height-40, uRed);

			for(i = 5, j = 0; i < width && j < height; i += 7, j += i/20)
				gdispDrawPixel(i, j, White);
		}

		while(TRUE) {
			gfxSleepMilliseconds(500);
		}
	}
#endif


text:
We use an off-the-shelf component [cert-manager](https://github.com/jetstack/cert-manager) as an example to demonstrate
how [Config Sync](https://cloud.google.com/anthos-config-management/docs/config-sync-overview) syncs an unstructured repo to your cluster using Helm template.

To sync the Helm chart to your cluster, you can run `helm template` and commit the rendered manifest to your repo.

## Objectives
- Learn how to use Config Sync to install an off-the-shelf Helm component
- Learn how to use helm template to render manifests
- Demonstrate usage of [unstructured repos](https://cloud.google.com/anthos-config-management/docs/how-to/unstructured-repo)

## Before you begin
- You'll need a cluster that has Config Sync installed.
  Please follow the [instructions](https://cloud.google.com/anthos-config-management/docs/how-to/installing-config-sync)
  to install Config Sync if it is not set up yet.
- Install [Helm](https://helm.sh/) to render the manifests.
- [Install the `nomos` command](https://cloud.google.com/anthos-config-management/docs/how-to/nomos-command#installing)

## Preparing the Git repository

### Set up a git repository
You can fork the repository to your local workstation, or create a new one with the following steps:
- [Create a new repository](https://docs.github.com/en/github/getting-started-with-github/create-a-repo)
- Create a directory that contains the configuration that you want to sync to and add a README.md file in the directory.
  ```console
  mkdir manifests && touch manifests/README.md
  ```
- Create a namespace where you want to install the component.
  ```yaml
  # manifests/namespace-cert-manager.yaml
  apiVersion: v1
  kind: Namespace
  metadata:
   name: cert-manager
  ```

### Render the manifests using helm template.
You can download the helm chart locally and render the manifests upon your local chart.
```console
# Add the helm chart repository
helm repo add cert-manager https://charts.jetstack.io

# Download the chart and unpack it in the local directory.
helm pull cert-manager/cert-manager --version 1.3.0 --untar

# Render the template and write the rendered manifests into an output directory.
helm template my-cert-manager cert-manager --namespace cert-manager --output-dir manifests
```

### Commit the changes to the repository:
```console
git add .
git commit -m 'Set up cert-manager manifests.'
git push
```

## Configuring syncing from the Git repository

You can configure syncing from the Git repository using GCP console or gcloud.

### Using GCP Console

Following the console instructions for
[configuring Config Sync](https://cloud.google.com/anthos-config-management/docs/how-to/installing-config-sync#configuring-config-sync),
you need to

- Select **None** in the **Git Repository Authentication for ACM** section
- Select **Enable Config Sync** in the **ACM settings for your clusters** section
   - If you're using your forked repo, the **URL** should be the Git repository url for your fork: `https://github.com/<YOUR_ORGANIZATION>/anthos-config-management-samples.git`; otherwise the **URL** should be `https://github.com/GoogleCloudPlatform/anthos-config-management-samples.git`
   - the **Branch** should be `master`.
   - the **Tag/Commit** should be `HEAD`.
   - the **Source format** field should **unstructured**.
   - the **Policy directory** field should be `helm-component/manual-rendering/manifests`.

### Using gcloud

You can also configure the Git repository information in a config-management.yaml file and use a gcloud command to apply the file.

1.  Create a file named config-management.yaml and copy the following YAML file into it:
    ```yaml
    # config-management.yaml

    apiVersion: configmanagement.gke.io/v1
    kind: ConfigManagement
    metadata:
     name: config-management
    spec:
     sourceFormat: unstructured
     git:
       syncRepo: https://github.com/GoogleCloudPlatform/anthos-config-management-samples/
       syncBranch: master
       secretType: none
       policyDir: helm-component/manual-rendering/manifests
    ```
1.  Apply the config-management.yaml file:
    ```console
    gcloud alpha container hub config-management apply \
        --membership=CLUSTER_NAME \
        --config=CONFIG_YAML_PATH \
        --project=PROJECT_ID
    ```

   Replace the following:
   - CLUSTER_NAME: the name of the registered cluster that you want to apply this configuration to
   - CONFIG_YAML_PATH: the path to your config-management.yaml file
   - PROJECT_ID: your project ID

## Verifying the installation

### Using GCP Console
1. In the Cloud Console, go to the [Anthos Config Management](https://console.cloud.google.com/anthos/config_management) page.
1. View the **Status** column. A successful installation has a status of `Synced`.

### Using gcloud
Run the following command to get the status
```console
gcloud alpha container hub config-management status --project=PROJECT_ID
```
Replace `PROJECT_ID` with your project's ID.

A successful installation has a status of `SYNCED`.

### Using nomos
Run the following command to get the status
```console
nomos status
```

You can also check if the helm component is successfully installed by running
```console
kubectl get all -n cert-manager
```

## Uninstalling the component
In order to help prevent accidental deletion, Config Sync does not allow you to remove all namespaces or
cluster-scoped resources in a single commit.
Follow the instructions to gracefully uninstall the component and remove the namespace in separate commits.
- Remove the cert-manager component.
  ```console
  git rm -rf manifests/cert-manager && git commit -m "uninstall cert-manager" && git push origin init
  ````
- Delete the cert-manager namespace.
  ```console
  git rm manifests/namespace-cert-manager.yaml && git commit -m "remove the cert-manager namespace" && git push origin init
  ````
- Verify the namespace does not exist.
  ```console
  Kubectl get namespace cert-namespace
  ```


text:
//
// Sloth: An Energy-Efficient Activity Recognition System
// Copyright 2016 Pejman Ghorbanzade <pejman@ghorbanzade.com>
// Released under the terms of MIT License
// https://github.com/ghorbanzade/sloth/blob/master/LICENSE
//

package com.ghorbanzade.sloth;

import org.apache.log4j.Logger;

/**
 * This class defines a custom exception that is thrown to hint the main
 * thread that the program should be aborted.
 *
 * @author Pejman Ghorbanzade
 */
public final class FatalException extends RuntimeException {

  private static final Logger log = Logger.getLogger(FatalException.class);

  /**
   * A fatal exception updates the log file with the class name that caused it.
   *
   * @param cls the class from which this exception is thrown
   */
  public FatalException(Class<?> cls) {
    log.fatal("fatal exception occured in " + cls.getSimpleName() + " class");
  }

}


text:
package org.apache.activemq.artemis.tests.integration.stomp.util;

public interface StompFrameFactory
{

   ClientStompFrame createFrame(String data);

   ClientStompFrame newFrame(String command);

   ClientStompFrame newAnyFrame(String command);

}


text:
package tr.com.aliok.wpteb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tr.com.aliok.wpteb.protocol.Protocol;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Ali Ok (ali.ok@apache.org)
 *         11/08/2015 23:58
 */
@ServerEndpoint(value = "/backend", decoders = {CommandRequestDecoder.class}, encoders = {CommandAuthorizationEncoder.class})
public class Backend {
    private static final String ATTR_KEY_USERNAME = "ATTR_KEY_USERNAME";

    private static final Logger LOG = LoggerFactory.getLogger(Backend.class);

    // Backend class is stateless. that's why following two are static
    // in production code, you'd inject state!
    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
    private static final AtomicInteger indexOfLastUser = new AtomicInteger(0);

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        LOG.info("Connected: " + session.getId() + ". Number of sessions : " + sessions.size());

        final int userIndex = indexOfLastUser.getAndIncrement();
        final String userName = "User #" + userIndex;
        session.getUserProperties().put(ATTR_KEY_USERNAME, userName);

        final Protocol.CommandAuthorization commandAuthorization = Protocol.CommandAuthorization.newBuilder()
                .setActionType(Protocol.ActionType.USER_JOIN)
                .setTime(System.currentTimeMillis())
                .setUserName(userName)
                .setUserJoinAction(Protocol.UserJoinAction.newBuilder().setUserCount(sessions.size()))
                .build();

        this.sendCommandAuthorizationToAll(commandAuthorization);
    }

    @OnMessage
    public void onTextMessage(String message, Session session) {
        LOG.info("Text message from " + session.getId() + " : " + message);
    }

    @OnMessage
    public void onBinaryMessage(Protocol.CommandRequest commandRequest, Session session) {
        LOG.info("Command request from " + session.getId() + " : " + commandRequest);

        final Protocol.ActionType actionType = commandRequest.getActionType();
        if (actionType == null) {
            LOG.error("Action type is null for received binary message! Ignoring it.");
            return;
        }

        final String userName = (String) session.getUserProperties().get(ATTR_KEY_USERNAME);
        final Protocol.CommandAuthorization.Builder builder = Protocol.CommandAuthorization.newBuilder();
        builder.setTime(System.currentTimeMillis()).setUserName(userName);

        switch (actionType) {
            case ORDER_PIZZA: {
                final Protocol.CommandAuthorization commandAuthorization = builder
                        .setActionType(Protocol.ActionType.ORDER_PIZZA)
                        .setOrderPizzaAction(commandRequest.getOrderPizzaAction())
                        .build();
                this.sendCommandAuthorizationToAll(commandAuthorization);
                break;
            }
            case PLAY_VIDEO_GAME: {
                final Protocol.CommandAuthorization commandAuthorization = builder
                        .setActionType(Protocol.ActionType.PLAY_VIDEO_GAME)
                        .setPlayVideoGameAction(commandRequest.getPlayVideoGameAction())
                        .build();
                this.sendCommandAuthorizationToAll(commandAuthorization);
                break;
            }
            case DRINK_TEA: {
                final Protocol.CommandAuthorization commandAuthorization = builder
                        .setActionType(Protocol.ActionType.DRINK_TEA)
                        .setDrinkTeaAction(commandRequest.getDrinkTeaAction())
                        .build();
                this.sendCommandAuthorizationToAll(commandAuthorization);
                break;
            }
            default: {
                LOG.error("Unknown action type " + actionType);
                return;
            }
        }
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        LOG.info("Left: " + session.getId() + ". Number of remaining sessions : " + sessions.size());

        final String userName = (String) session.getUserProperties().get(ATTR_KEY_USERNAME);
        final Protocol.CommandAuthorization commandAuthorization = Protocol.CommandAuthorization.newBuilder()
                .setActionType(Protocol.ActionType.USER_LEAVE)
                .setTime(System.currentTimeMillis())
                .setUserName(userName)
                .setUserLeaveAction(Protocol.UserLeaveAction.newBuilder().setUserCount(sessions.size()))
                .build();

        sendCommandAuthorizationToAll(commandAuthorization);
    }

    private void sendCommandAuthorizationToAll(Protocol.CommandAuthorization commandAuthorization) {
        for (Session session : sessions) {
            this.sendCommandAuthorization(session, commandAuthorization);
        }
    }

    private void sendCommandAuthorization(Session session, Protocol.CommandAuthorization commandAuthorization) {
        // following is the sync option
        // session.getBasicRemote().sendBinary(ByteBuffer.wrap(commandAuthorization.toByteArray()));

        // btw, streaming doesn't make sense here because of async. it is not supported by async remote anyway!
        session.getAsyncRemote().sendObject(commandAuthorization);
    }

}


text:
using namespace std;

Motor::Motor() :
	StateMachine(ST_MAX_STATES),
	m_currentSpeed(0)
{
}

// set motor speed external event
void Motor::SetSpeed(MotorData* data)
{
	BEGIN_TRANSITION_MAP			              			// - Current State -
		TRANSITION_MAP_ENTRY (ST_START)						// ST_IDLE
		TRANSITION_MAP_ENTRY (CANNOT_HAPPEN)				// ST_STOP
		TRANSITION_MAP_ENTRY (ST_CHANGE_SPEED)				// ST_START
		TRANSITION_MAP_ENTRY (ST_CHANGE_SPEED)				// ST_CHANGE_SPEED
	END_TRANSITION_MAP(data)
}

// halt motor external event
void Motor::Halt()
{
	BEGIN_TRANSITION_MAP			              			// - Current State -
		TRANSITION_MAP_ENTRY (EVENT_IGNORED)				// ST_IDLE
		TRANSITION_MAP_ENTRY (CANNOT_HAPPEN)				// ST_STOP
		TRANSITION_MAP_ENTRY (ST_STOP)						// ST_START
		TRANSITION_MAP_ENTRY (ST_STOP)						// ST_CHANGE_SPEED
	END_TRANSITION_MAP(NULL)
}

// state machine sits here when motor is not running
STATE_DEFINE(Motor, Idle, NoEventData)
{
	cout << "Motor::ST_Idle" << endl;
}

// stop the motor
STATE_DEFINE(Motor, Stop, NoEventData)
{
	cout << "Motor::ST_Stop" << endl;
	m_currentSpeed = 0;

	// perform the stop motor processing here
	// transition to Idle via an internal event
	InternalEvent(ST_IDLE);
}

// start the motor going
STATE_DEFINE(Motor, Start, MotorData)
{
	cout << "Motor::ST_Start : Speed is " << data->speed << endl;
	m_currentSpeed = data->speed;

	// set initial motor speed processing here
}

// changes the motor speed once the motor is moving
STATE_DEFINE(Motor, ChangeSpeed, MotorData)
{
	cout << "Motor::ST_ChangeSpeed : Speed is " << data->speed << endl;
	m_currentSpeed = data->speed;

	// perform the change motor speed to data->speed here
}


text:
import proto  # type: ignore

from google.ads.googleads.v10.enums.types import combined_audience_status

__protobuf__ = proto.module(
    package="google.ads.googleads.v10.resources",
    marshal="google.ads.googleads.v10",
    manifest={
        "CombinedAudience",
    },
)

class CombinedAudience(proto.Message):
    r"""Describe a resource for combined audiences which includes
    different audiences.

    Attributes:
        resource_name (str):
            Immutable. The resource name of the combined audience.
            Combined audience names have the form:

            ``customers/{customer_id}/combinedAudience/{combined_audience_id}``
        id (int):
            Output only. ID of the combined audience.
        status (google.ads.googleads.v10.enums.types.CombinedAudienceStatusEnum.CombinedAudienceStatus):
            Output only. Status of this combined
            audience. Indicates whether the combined
            audience is enabled or removed.
        name (str):
            Output only. Name of the combined audience.
            It should be unique across all combined
            audiences.
        description (str):
            Output only. Description of this combined
            audience.
    """

    resource_name = proto.Field(
        proto.STRING,
        number=1,
    )
    id = proto.Field(
        proto.INT64,
        number=2,
    )
    status = proto.Field(
        proto.ENUM,
        number=3,
        enum=combined_audience_status.CombinedAudienceStatusEnum.CombinedAudienceStatus,
    )
    name = proto.Field(
        proto.STRING,
        number=4,
    )
    description = proto.Field(
        proto.STRING,
        number=5,
    )

__all__ = tuple(sorted(__protobuf__.manifest))


text:
import * as Sequelize from "sequelize";

export default function rental(sequelize) {
    const rental = sequelize.define("rental", {
	"rental_id": {
		"type": Sequelize.INTEGER,
		"allowNull": false,
		"primaryKey": true
	},
	"rental_date": {
		"type": Sequelize.DATE,
		"allowNull": false,
		"primaryKey": false
	},
	"inventory_id": {
		"type": Sequelize.INTEGER,
		"allowNull": false,
		"primaryKey": true
	},
	"customer_id": {
		"type": Sequelize.INTEGER,
		"allowNull": false,
		"primaryKey": true
	},
	"return_date": {
		"type": Sequelize.DATE,
		"allowNull": true,
		"primaryKey": false
	},
	"staff_id": {
		"type": Sequelize.INTEGER,
		"allowNull": false,
		"primaryKey": true
	},
	"last_update": {
		"type": Sequelize.DATE,
		"allowNull": false,
		"primaryKey": false
	}
},
    {
        timestamps:false,
        freezeTableName: true,
		classMethods:{
			getAccessDefinition:()=>{
				return {
					"GET":["STAFF"],
					"PUT":["STAFF"],
					"POST":["STAFF"],
					"DELETE":["STAFF"]
				}
			},
			associate:(models)=>{
				rental.belongsTo(models.inventory,{foreignKey:"inventory_id"});
				rental.belongsTo(models.staff,{foreignKey:"staff_id"});
				rental.belongsTo(models.customer,{foreignKey:"customer_id"});
				rental.hasOne(models.payment,{foreignKey:"rental_id"});
			}
		}
    });
    rental.sync();
    return rental;
};


text:
import TestUtils from 'react-addons-test-utils';
import { expect } from 'chai';
import { shallow } from 'enzyme';

import Img from '#img';

describe('img', function() {
    describe('basic', function() {
        it('exists', function() {
            expect(Img).to.exist;
        });

        it('is a component', function() {
            expect(TestUtils.isElement(Img())).to.be.true;
        });
    });

    describe('render', function() {
        describe('DOM', function() {
            it('initial', function() {
                const component = shallow(Img());

                expect(component).to.have.tagName('img');
                expect(component).to.be.a.block('img');
            });
        });
    });
});


text:
import json
from unittest import mock

from django.test import (
    TestCase,
    RequestFactory,
)

from . import views

class HealthcheckViewTestCase(TestCase):
    """
    Tests for .views.healthcheck_view
    """

    def setUp(self):
        self.factory = RequestFactory()

    @mock.patch('django.conf.settings.SLACK_VERIFICATION_TOKEN', 'test')
    def test_returns_403_if_invalid_credentials(self):
        request = self.factory.post(
            '/app/healthcheck/',
            data={'token': 'invalid'},
        )
        response = views.healthcheck_view(request)

        self.assertEqual(response.status_code, 200)

    @mock.patch('django.conf.settings.SLACK_VERIFICATION_TOKEN', 'test')
    def test_returns_greeting_if_valid_credentials(self):
        request = self.factory.post(
            '/app/healthcheck/',
            data={'token': 'test'},
        )

        response = views.healthcheck_view(request)

        expected_content = {
            'text': 'Hello! :wave:',
            'attachments': [],
            'blocks': [],
            'mrkdwn': True,
        }

        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content), expected_content)


text:
using std::map;
using std::string;
using std::pair;
using namespace GPULogger;

extern DCGPAProfiler g_Profiler;

#define MAX_LEN 100

KernelAssembly::KernelAssembly(void): m_bOutputASM(false)
{
    m_strFilePrefix = KERNEL_ASSEMBLY_FILE_PREFIX;
    m_pmutex = new AMDTMutex("KernelAssembly_mutex ");
    m_pD3DDisassemble = NULL;
}

KernelAssembly::~KernelAssembly(void)
{
    for (KernelMap::iterator it = kernelMap.begin(); it != kernelMap.end(); it++)
    {
        it->second.m_pAssemblyBlob->Release();
    }

    kernelMap.clear();

    if (m_pmutex != NULL)
    {
        delete m_pmutex;
    }
}

void KernelAssembly::AddComputeShader(ID3D11ComputeShader* pCS, const void* pShaderByteCode, SIZE_T BytecodeLength)
{
    AMDTScopeLock lock(m_pmutex);
    KernelMap::iterator kmIt = kernelMap.find(pCS);

    if (kmIt != kernelMap.end())
    {
        // shader already existed in table??
        Log(logWARNING, "KernelAssembly::AddComputeShader() shader already existed in table\n");
        return;
    }

    DCKernel dcKernel;
    // search through kernelNameMap
    KernelNameMap::iterator it = kernelNameMap.find(pShaderByteCode);
    string kernelName;
    kernelName.clear();

    if (it != kernelNameMap.end())
    {
        // found kernel name
        kernelName = it->second;
        // remove from kernel name table
        kernelNameMap.erase(it);
    }
    else
    {
        // name not found, no CompileShader* called before
        char cstr[MAX_LEN];
        sprintf_s(cstr, MAX_LEN, "Kernel%zd", kernelMap.size());
        kernelName = cstr;
    }

    ID3DBlob* pDisassembly;

    /// Get function pointer when needed
    if (m_pD3DDisassemble == NULL)
    {
        HMODULE hMod = LoadLibrary(L"D3DCompiler_43.dll");

        if (hMod != NULL)
        {
            m_pD3DDisassemble = (D3DDisassembleProc)GetProcAddress(hMod, "D3DDisassemble");
        }
    }

    if (m_pD3DDisassemble == NULL)
    {
        // If this failed, we can't get kernel name but it's not a fatal error. User can still get profile result.
        // This only happens when user didn't install DXSDK or DX runtime.
        Log(logERROR, "Failed to get D3DDisassemble function pointer.\n");
        return;
    }

    m_pD3DDisassemble(pShaderByteCode,
                      BytecodeLength,
                      0,
                      NULL,
                      &pDisassembly);

    dcKernel.m_pAssemblyBlob = pDisassembly;

    // write HLSL ASM when create shader

    string strOutputDir;

    if (!FileUtils::GetWorkingDirectory(g_Profiler.GetOutputFile(), strOutputDir))
    {
        strOutputDir.clear();
    }

    char chHandle[MAX_LEN];
    sprintf_s(chHandle, MAX_LEN, "_%8p", pCS);
    string strHandle(chHandle);
    kernelName += strHandle;

    dcKernel.m_strKernelName = kernelName;

    char* tmpBuf = new char[pDisassembly->GetBufferSize()];
    memcpy(tmpBuf, pDisassembly->GetBufferPointer(), pDisassembly->GetBufferSize());

    string strSrc(tmpBuf);
    size_t pos = strSrc.find("dcl_thread_group");
    UINT x, y, z;

    if (pos != string::npos)
    {
        std::stringstream ss(std::stringstream::in | std::stringstream::out);
        ss << strSrc;
        ss.seekg(pos + strlen("dcl_thread_group"));

        char chTmp;
        ss >> x >> chTmp >> y >> chTmp >> z;
        dcKernel.m_uiGroupSizeX = x;
        dcKernel.m_uiGroupSizeY = y;
        dcKernel.m_uiGroupSizeZ = z;
    }
    else
    {
        dcKernel.m_uiGroupSizeX = 0;
        dcKernel.m_uiGroupSizeY = 0;
        dcKernel.m_uiGroupSizeZ = 0;
    }

    delete [] tmpBuf;

    kernelMap.insert(pair<ID3D11ComputeShader*, DCKernel>(pCS, dcKernel));

    if (m_bOutputASM)
    {
        WriteAssembly(strOutputDir + m_strFilePrefix + kernelName + ".asm", pDisassembly);
    }
}

void KernelAssembly::AddKernelName(string kernelName, ID3DBlob* pBlob)
{
    AMDTScopeLock lock(m_pmutex);

    KernelNameMap::iterator it = kernelNameMap.find(pBlob->GetBufferPointer());

    //int checksum = GetChecksum(pBlob->GetBufferPointer(),pBlob->GetBufferSize());

    Log(traceMESSAGE, "Shader %s Added", kernelName.c_str());

    if (it == kernelNameMap.end())
    {
        kernelNameMap.insert(pair<const void*, string>(pBlob->GetBufferPointer(), kernelName));
    }
    else
    {
        // happens when the last Blob from CompileShader* get deleted and new Blob happens to have the same address
        // delete the old one
        kernelNameMap.erase(it);
        // replace it with new one
        kernelNameMap.insert(pair<const void*, string>(pBlob->GetBufferPointer(), kernelName));
    }
}

void KernelAssembly::GetKernelInformation(ID3D11ComputeShader* pCS,
                                          ID3DBlob** pBlob,
                                          string& kernelName,
                                          UINT& groupSizeX,
                                          UINT& groupSizeY,
                                          UINT& groupSizeZ) const
{
    KernelMap::const_iterator it = kernelMap.find(pCS);

    if (it == kernelMap.end())
    {
        // no information found
        // could happen in Heaven benchmark
        //Log(logWARNING,"KernelAssembly::GetKernelInformation() : No compute shader found\n");
        *pBlob = NULL;
        kernelName.clear();
        return;
    }

    *pBlob = it->second.m_pAssemblyBlob;
    kernelName = it->second.m_strKernelName;
    groupSizeX = it->second.m_uiGroupSizeX;
    groupSizeY = it->second.m_uiGroupSizeY;
    groupSizeZ = it->second.m_uiGroupSizeZ;
}

void KernelAssembly::WriteAssembly(string fileName, ID3DBlob* pBlob)
{
    if (pBlob == NULL)
    {
        Log(logERROR, "KernelAssembly::WriteAssembly() : NULL Pointer\n");
        return;
    }

    std::cout << "Writing to file: " << fileName << std::endl;

    FILE* f;
    fopen_s(&f, fileName.c_str(), "w");
    SpAssert(f);
    fwrite(pBlob->GetBufferPointer(), sizeof(char), pBlob->GetBufferSize(), f);
    fclose(f);
}

int KernelAssembly::GetChecksum(void* pBuff, UINT size) const
{
    int ret = 0;
    unsigned char* pByteBuf = (unsigned char*)pBuff;

    for (UINT i = 0; i < size; i++)
    {
        ret += pByteBuf[i];
    }

    return ret;
}


text:
from two.ol.base import FormHandler, applyrequest
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import login, authenticate

from django.utils.translation import ugettext_lazy as _
from django.utils.http import int_to_base36
from django.utils.http import base36_to_int

from django.contrib.sites.models import get_current_site
from django.core.mail import send_mail

from django.conf import settings

## more generically: password handler?

class ForgottenForm(forms.Form):
    username = forms.EmailField(label=_("Username"), max_length=75)

    def get_user(self, username):
        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            raise forms.ValidationError(_("No user is known with this username."))

    def clean_username(self):
        username = self.cleaned_data["username"].strip().lower()
        self.user = self.get_user(username)
        return self.user

class EmailForgottenForm(ForgottenForm):
    """ username is actually email address """
    def get_user(self, username):
        try:
            return User.objects.get(email=username)
        except User.DoesNotExist:
            raise forms.ValidationError(_("No user is known with this email address."))

def send_reset(handler, user, initial=False):
    remote_addr = handler.request.META.get('X_FORWARDED_FOR')
    if remote_addr is None:
        remote_addr = handler.request.META.get('REMOTE_ADDR')

    if initial:
        email_template_name = "initial_password_main.html"
        subject = "Registratie op %s"
    else:
        email_template_name = "reset_password_main.html"
        subject = "Wachtwoordherstel voor %s"

    from_email = settings.MAIL_SENDER
    token_generator = default_token_generator

    #if is_admin_site:
    #    opts = dict(opts, domain_override=request.META['HTTP_HOST'])
    current_site = get_current_site(handler.request)
    site_name = current_site.name
    domain = current_site.domain
    use_https = handler.request.is_secure()

    t = handler.render_template(email_template_name,
        email=user.email,
        domain=domain,
        site_name=site_name,
        uid=int_to_base36(user.id),
        user=user,
        token=token_generator.make_token(user),
        protocol=use_https and 'https' or 'http',
        remote_addr=remote_addr
    )

    send_mail(_(subject) % site_name, t, from_email, [user.email])

class ResetHandler(FormHandler):
    resetform = ForgottenForm
    formclass = None # SetPasswordForm
    template_ns = "two.userauth"

    def get_user(self, uidb36, token):
        try:
            uid_int = base36_to_int(uidb36)
            user = User.objects.get(id=uid_int)
            if user and default_token_generator.check_token(user, token):
                return user
        except (ValueError, User.DoesNotExist):
            pass
        return None

    @applyrequest
    def index(self, username="", redirect_to="/"):
        self.context['form'] = self.form = self.resetform(initial={'username':username})
        self.context['redirect_to'] = redirect_to or '/'
        return self.template("forgotten.html")

    @applyrequest
    def handle_forgotten(self, username, redirect_to="/"):
        self.context['form'] = self.form = self.resetform(data=self.request.POST)
        if self.form.is_valid():
            user = self.form.user
            send_reset(self, user)
            self.redirect(redirect_to or "/", success="Instructies om je wachtwoord te herstellen zijn per e-mail verstuurd.")

        return self.template("forgotten.html")

    @applyrequest
    def handle_confirm(self, uidb36, token, initial=False):
        user = self.get_user(uidb36, token)
        self.context['form'] = self.form = SetPasswordForm(user)
        return self.template("reset.html",
                             redirect_to="/manage/",
                             user=user,
                             validlink=(user is not None),
                             uidb36=uidb36,
                             token=token,
                             initial=initial)

    @applyrequest
    def process(self, uidb36, token, redirect_to="/", initial=False, auto_login=True):
        user = self.get_user(uidb36, token)
        self.context['form'] = self.form = SetPasswordForm(user, self.request.POST)
        if user is not None:
            if self.form.is_valid():
                self.form.save()
                if auto_login:
                    password = self.form.data['new_password1']
                    user = authenticate(username=user.username,
                                        password=password)
                    login(self.request, user)
                self.redirect(redirect_to, success="Wachtwoord is ingesteld.")
        ## XXX applyrequest/applicator can't handle positional arguments
        ## but it will hapilly apply the request variables again, anyway
        # return self.index(uidb36, token, initial)
        # return self.index(uidb36=uidb36, token=token, initial=initial)
        # return self.handle_confirm()
        return self.template("reset.html",
                             user=user,
                             redirect_to=redirect_to,
                             validlink=(user is not None),
                             uidb36=uidb36,
                             token=token,
                             initial=initial)

    def handle_complete(self):
        # XXX deprecated?
        return self.template("complete.html")

class EmailResetHandler(ResetHandler):
    resetform = EmailForgottenForm


text:
@interface KCAutoHeightTableViewController2 : KCTableViewController

@end


text:
package org.kuali.kra.iacuc.committee.print.service;

import org.kuali.coeus.common.questionnaire.framework.print.CorrespondencePrintingService;

public interface IacucCommitteeCorrespondencePrint extends CorrespondencePrintingService {

}


text:
package com.joshng.util.identity;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.joshng.util.blocks.F;
import com.joshng.util.concurrent.LazyReference;
import com.joshng.util.string.StringUtils;

import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * User: josh
 * Date: Jun 18, 2011
 * Time: 11:23:57 AM
 */
public enum ByteHash {
  MD5("MD5", Hashing.md5()),
  SHA1("SHA1", Hashing.sha1()),
  SHA256("SHA-256", Hashing.sha256());

  private static final Charset DEFAULT_CHARSET = Charsets.UTF_8;

  private String algorithm;
  private final HashFunction hashFunction;

  ByteHash(String algorithm, HashFunction hashFunction) {
    this.algorithm = algorithm;
    this.hashFunction = hashFunction;
  }

  public String digestHex(String of) {
    return StringUtils.toHexString(digestBytes(of));
  }

  public String digestHex(String of, Charset charset) {
    return StringUtils.toHexString(digestBytes(of, charset));
  }

  public String digestHex(byte[] bytes) {
    return StringUtils.toHexString(digestBytes(bytes));
  }

  public String digestHex(byte[] input, int offset, int len) {
    return StringUtils.toHexString(digestBytes(input, offset, len));
  }

  public String digestHex(File file) throws IOException {
    return StringUtils.toHexString(Files.hash(file, hashFunction).asBytes());
  }

  public byte[] digestBytes(String of) {
    return digestBytes(of, DEFAULT_CHARSET);
  }

  public byte[] digestBytes(String of, Charset charset) {
    return digestBytes(of.getBytes(charset));
  }

  public byte[] digestBytes(byte[] input) {
    return getJDKDigest().digest(input);
  }

  public byte[] digestBytes(byte[] input, int offset, int len) {
    return getDigest().append(input, offset, len).digest();
  }

  public MessageDigest getJDKDigest() {
    try {
      return MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
      throw Throwables.propagate(e);
    }
  }

  public Digest getDigest() {
    return getDigest(DEFAULT_CHARSET);
  }

  public Digest getDigest(Charset defaultCharset) {
    return new Digest(getJDKDigest(), defaultCharset);
  }

  public Digest start(String string) {
    return getDigest().append(string);
  }

  public Digest start(String string, Charset charset) {
    return getDigest().append(string, charset);
  }

  public Digest start(byte input) {
    return getDigest().append(input);
  }

  public Digest start(byte[] input, int offset, int len) {
    return getDigest().append(input, offset, len);
  }

  public Digest start(byte[] input) {
    return getDigest().append(input);
  }

  public Digest start(ByteBuffer input) {
    return getDigest().append(input);
  }

  public Digest join(String separator, Object first, Object second, Object... rest) {
    return getDigest().join(separator, first, second, rest);
  }

  public Digest join(String separator, Iterable<Object> values) {
    return getDigest().join(separator, values);
  }

  public HashingOutputStream newHashingOutputStream(OutputStream out) {
    return new HashingOutputStream(hashFunction.newHasher(), out);
  }

  public F<String, String> digestHexFunction() {
    return new F<String, String>() {
      @Override
      public String apply(String input) {
        return digestHex(input);
      }
    };
  }

  /**
   * a simple wrapper around an underlying JDK MessageDigest with extra utility:
   * append() is a chainable form of MessageDigest.update()
   * append() takes strings/encodings (with a default)
   * join(...) concatenates values with a separator, based on their {@link String#valueOf(Object)} representation
   */
  public static class Digest implements Appendable {
    private final MessageDigest delegate;
    private final Charset charset;

    private Digest(MessageDigest delegate, Charset charset) {
      this.delegate = delegate;
      this.charset = charset;
    }

    public Digest join(String separator, Iterable<Object> values) {
      try {
        return Joiner.on(separator).appendTo(this, values);
      } catch (IOException impossible) {
        throw Throwables.propagate(impossible);
      }
    }

    public Digest join(String separator, Object first, Object second, Object... rest) {
      try {
        return Joiner.on(separator).appendTo(this, first, second, rest);
      } catch (IOException impossible) {
        throw Throwables.propagate(impossible);
      }
    }

    public Digest append(String string) {
      return append(string, charset);
    }

    public Digest append(String string, Charset charset) {
      return append(string.getBytes(charset));
    }

    public Digest append(byte input) {
      delegate.update(input);
      return this;
    }

    public Digest append(byte[] input, int offset, int len) {
      delegate.update(input, offset, len);
      return this;
    }

    public Digest append(byte[] input) {
      delegate.update(input);
      return this;
    }

    public Digest append(ByteBuffer input) {
      delegate.update(input);
      return this;
    }

    public byte[] digest() {
      return delegate.digest();
    }

    public int digest(byte[] buf, int offset, int len) throws DigestException {
      return delegate.digest(buf, offset, len);
    }

    public byte[] digest(byte[] input) {
      return delegate.digest(input);
    }

    public String getAlgorithm() {
      return delegate.getAlgorithm();
    }

    public int getDigestLength() {
      return delegate.getDigestLength();
    }

    public void reset() {
      delegate.reset();
    }

    public String digestHex() {
      return StringUtils.toHexString(digest());
    }

    public Digest append(CharSequence csq) throws IOException {
      if (csq instanceof String) return append((String) csq);
      delegate.update(charset.encode(CharBuffer.wrap(csq)));
      return this;
    }

    public Digest append(CharSequence csq, int start, int end) throws IOException {
      delegate.update(charset.encode(CharBuffer.wrap(csq, start, end)));
      return this;
    }

    public Digest append(char c) throws IOException {
      delegate.update((byte) c);
      return this;
    }
  }

  public static class HashingOutputStream extends FilterOutputStream {
    private final Hasher hasher;
    private final LazyReference<HashCode> hashCode = new LazyReference<HashCode>() {
      @Override
      protected HashCode supplyValue() {
        return hasher.hash();
      }
    };

    public HashingOutputStream(Hasher hasher, OutputStream out) {
      super(out);
      this.hasher = hasher;
    }

    @Override
    public void write(int b) throws IOException {
      hasher.putByte((byte) b);
      super.write(b);
    }

    @Override
    public void write(byte[] b) throws IOException {
      hasher.putBytes(b);
      super.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
      hasher.putBytes(b, off, len);
      super.write(b, off, len);
    }

    public HashCode hash() {
      return hashCode.get();
    }

    public byte[] digestBytes() {
      return hash().asBytes();
    }

    public String digestHex() {
      return StringUtils.toHexString(digestBytes());
    }
  }
}


text:
package com.cyf.common.message.receive.shop;

import javax.jms.Destination;
import javax.jms.JMSException;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cyf.center.common.bean.MessageVo;
import com.cyf.center.common.business.service.MessageService;
import com.cyf.base.common.bean.UserVo;
import com.cyf.base.common.mqconfig.TestMQConfig;
import com.cyf.base.common.utils.JsonUtil;
import com.cyf.base.common.utils.LoggerWrapper;
import com.cyf.shop.message.bean.MessageConsume;
import com.cyf.shop.message.service.MessageConsumeService;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.messaging.Message;

import java.util.Date;

/**
 * shop服务的消息接受器
 */
@Component
public class MessagesReceiver {
	static final LoggerWrapper LOG = LoggerWrapper.getLoggerWrapper();

	@Reference
	MessageService messageService;
	@Reference
	MessageConsumeService messageConsumeService;

	//接收queue消息
	@JmsListener(containerFactory="defaultQueueLCFactory", destination = TestMQConfig.TEST_QUEUE, subscription = "queue_receiver")
	public void receiveQueue(final Message<String> sprMessage) throws JMSException {
		LOG.info("-----------receiveQueue start------------");

		MessageVo messageVo = new MessageVo();
		messageVo.setName(TestMQConfig.TEST_QUEUE);
		messageVo.setPayload(sprMessage.getPayload());
		messageVo.setType(1);
		createMessageConsume("receiveQueue", messageVo);

		LOG.info("-----------receiveQueue end------------");
	}

	//接受queue消息并发回响应消息
	@JmsListener(containerFactory="syncQueueLCFactory", destination = TestMQConfig.SEND_AND_GET_SYNC, subscription = "queue_response_receiver")
	public void receiveAndReply(final Message<String> sprMessage, javax.jms.Message message) throws Exception {
		LOG.info("-----------receiveAndReply start------------");
		UserVo user = new UserVo();
		user.setCreateTime(new Date());
		user.setPhone("13800138000");
		user.setId(12L);
		Destination replyTo = message.getJMSReplyTo();
		String messageJson = JsonUtil.toStringWithNull(user);
		LOG.info("-----------reply to common: " + messageJson);
		messageService.sendMessage2(replyTo, messageJson);

		MessageVo messageVo = new MessageVo();
		messageVo.setName(TestMQConfig.SEND_AND_GET_SYNC);
		messageVo.setPayload(sprMessage.getPayload());
		messageVo.setType(1);
		createMessageConsume("receiveAndReply", messageVo);
		LOG.info("-----------receiveAndReply end------------");
	}

	/**--------------------------------------------这两个方法订阅同一个topic消息-------------------------------------------*/
	//接收topic消息1
	@JmsListener(containerFactory="durableTopicLCFactory", destination = TestMQConfig.TEST_TOPIC, subscription = "topic_receiver_1")
	public void receiveTopic1(final Message<String> sprMessage) throws JMSException {
		LOG.info("-----------receiveTopic1 start------------");

		MessageVo messageVo = new MessageVo();
		messageVo.setName(TestMQConfig.TEST_TOPIC);
		messageVo.setPayload(sprMessage.getPayload());
		messageVo.setType(2);
		createMessageConsume("receiveTopic1", messageVo);

		LOG.info("-----------receiveTopic1 end------------");
	}

	//接收topic消息2
	@JmsListener(containerFactory="durableTopicLCFactory", destination = TestMQConfig.TEST_TOPIC, subscription = "topic_receiver_2")
	public void receiveTopic2(final Message<String> sprMessage) throws Exception {
		LOG.info("-----------receiveTopic2 start------------");

		MessageVo messageVo = new MessageVo();
		messageVo.setName(TestMQConfig.TEST_TOPIC);
		messageVo.setPayload(sprMessage.getPayload());
		messageVo.setType(2);
		createMessageConsume("receiveTopic2", messageVo);

		//测试消息重投
//		if(1==1){
//			throw new Exception("故意失败,测试消息重投!");
//		}
		LOG.info("-----------receiveTopic2 end------------");
	}

	//接收批量发送的queue消息
	@JmsListener(containerFactory="defaultQueueLCFactory", destination = TestMQConfig.BATCH_TEST_QUEUE, subscription = "batch_queue_receiver")
	public void receiveBatchQueue(final Message<String> sprMessage) throws JMSException {
		LOG.info("-----------receiveBatchQueue start------------");

		MessageVo messageVo = new MessageVo();
		messageVo.setName(TestMQConfig.BATCH_TEST_QUEUE);
		messageVo.setPayload(sprMessage.getPayload());
		messageVo.setType(1);
		createMessageConsume("receiveBatchQueue", messageVo);

		LOG.info("-----------receiveBatchQueue end------------");
	}

	//接收批量发送的topic消息
	@JmsListener(containerFactory="durableTopicLCFactory", destination = TestMQConfig.BATCH_TEST_TOPIC, subscription = "batch_topic_receiver")
	public void receiveBatchTopic(final Message<String> sprMessage) throws JMSException {
		LOG.info("-----------receiveBatchTopic start------------");

		MessageVo messageVo = new MessageVo();
		messageVo.setName(TestMQConfig.BATCH_TEST_TOPIC);
		messageVo.setPayload(sprMessage.getPayload());
		messageVo.setType(2);
		createMessageConsume("receiveBatchTopic", messageVo);

		LOG.info("-----------receiveBatchTopic end------------");
	}

	private void createMessageConsume(String methodName, MessageVo messageVo){
		MessageConsume messageConsume = new MessageConsume();
		messageConsume.setName(messageVo.getName());
		messageConsume.setType(messageVo.getType());
		messageConsume.setPayload(messageVo.getPayload());
		messageConsume.setConsumer(methodName);
		messageConsume.setIsTimer(2);
		messageConsumeService.createMessageConsume(messageConsume);
	}
}


text:
<?php

/**
 * (c) 2013 - ∞ Bernard
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bernard\BernardBundle\Handler;

use Bernard\Message\DefaultMessage;

abstract class InvokeMessageHandler
{
    public function __call($methodName, $arguments)
    {
        $className = get_class($this);
        if ($methodName == lcfirst($className)) {
            return $this->__invoke($arguments);
        }

        throw new \Exception('Wrong method called on message handler');
    }

    abstract public function __invoke(DefaultMessage $message);
}