text:
<?php

namespace Enhavo\Bundle\NewsletterBundle\Tests\Storage;

use Doctrine\ORM\EntityManagerInterface;
use Enhavo\Bundle\BlockBundle\Model\NodeInterface;
use Enhavo\Bundle\MediaBundle\Model\FileInterface;
use Enhavo\Bundle\NewsletterBundle\Entity\Group;
use Enhavo\Bundle\NewsletterBundle\Entity\LocalSubscriber;
use Enhavo\Bundle\NewsletterBundle\Entity\Newsletter;
use Enhavo\Bundle\NewsletterBundle\Entity\Receiver;
use Enhavo\Bundle\NewsletterBundle\Exception\NoGroupException;
use Enhavo\Bundle\NewsletterBundle\Factory\LocalSubscriberFactory;
use Enhavo\Bundle\NewsletterBundle\Factory\LocalSubscriberFactoryInterface;
use Enhavo\Bundle\NewsletterBundle\Model\NewsletterInterface;
use Enhavo\Bundle\NewsletterBundle\Model\Subscriber;
use Enhavo\Bundle\NewsletterBundle\Model\SubscriberInterface;
use Enhavo\Bundle\NewsletterBundle\Storage\Storage;
use Enhavo\Bundle\NewsletterBundle\Storage\Type\LocalStorageType;
use Enhavo\Bundle\NewsletterBundle\Storage\Type\StorageType;
use Enhavo\Bundle\NewsletterBundle\Tests\Mocks\GroupAwareSubscriberMock;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Sylius\Component\Resource\Repository\RepositoryInterface;

class LocalTypeStorageTest extends TestCase
{
    private function createDependencies(): LocalTypeStorageTestDependencies
    {
        $dependencies = new LocalTypeStorageTestDependencies();
        $dependencies->entityManager = $this->getMockBuilder(EntityManagerInterface::class)->getMock();
        $dependencies->subscriberRepository = $this->getMockBuilder(RepositoryInterface::class)->getMock();
        $dependencies->groupRepository = $this->getMockBuilder(RepositoryInterface::class)->getMock();
        $dependencies->subscriberFactory = $this->getMockBuilder(LocalSubscriberFactoryInterface::class)->getMock();
        return $dependencies;
    }

    private function createInstance($type, $parents, $options): Storage
    {
        return new Storage($type, $parents, $options);
    }

    public function testAddSubscriber()
    {
        $dependencies = $this->createDependencies();
        $localSubscriber = new LocalSubscriber();
        $localSubscriber->setEmail('to@enhavo.com');
        $localSubscriber->setSubscription('default');
        $group = new Group();
        $group->setCode('local');
        $dependencies->subscriberRepository->expects($this->once())->method('findOneBy')->willReturn($localSubscriber);
        $dependencies->subscriberFactory->expects($this->never())->method('createFrom');
        $dependencies->groupRepository->expects($this->once())->method('findOneBy')->willReturnCallback(function ($criteria) use ($group) {
            $this->assertEquals(['code' => 'local'], $criteria);
            if ($criteria['code'] !== 'local') {
                return null;
            }
            return $group;
        });
        $dependencies->entityManager->expects($this->once())->method('persist');
        $dependencies->entityManager->expects($this->once())->method('flush');
        $storage = $this->createInstance(new LocalStorageType($dependencies->entityManager, $dependencies->subscriberRepository, $dependencies->groupRepository, $dependencies->subscriberFactory), [new StorageType()], [
            'groups' => [
                'local'
            ]
        ]);
        /** @var SubscriberInterface|MockObject $subscriberMock */
        $subscriberMock = $this->getMockBuilder(SubscriberInterface::class)->getMock();
        $subscriberMock->method('getEmail')->willReturn('to@enhavo.com');
        $subscriberMock->method('getSubscription')->willReturn('default');

        $storage->saveSubscriber($subscriberMock);

        $dependencies = $this->createDependencies();
        $dependencies->subscriberRepository->expects($this->once())->method('findOneBy')->willReturn(null);
        $dependencies->subscriberFactory = new LocalSubscriberFactory(LocalSubscriber::class, $dependencies->groupRepository);
        $dependencies->groupRepository->expects($this->once())->method('findOneBy')->willReturn($group);
        $dependencies->entityManager->expects($this->once())->method('persist')->willReturnCallback(function ($subscriber) {
            /** @var $subscriber LocalSubscriber */
            $this->assertInstanceOf(LocalSubscriber::class, $subscriber);
            $this->assertEquals('to@enhavo.com', $subscriber->getEmail());
            $this->assertEquals('default', $subscriber->getSubscription());
            $this->assertNotNull($subscriber->getCreatedAt());
        });
        $storage = $this->createInstance(new LocalStorageType($dependencies->entityManager, $dependencies->subscriberRepository, $dependencies->groupRepository, $dependencies->subscriberFactory), [new StorageType()], [
            'groups' => [$group]
        ]);

        $storage->saveSubscriber($subscriberMock);

        $dependencies = $this->createDependencies();
        $dependencies->subscriberRepository->expects($this->once())->method('findOneBy')->willReturn(null);
        $dependencies->subscriberFactory->expects($this->once())->method('createFrom')->willReturn($localSubscriber);
        $storage = $this->createInstance(new LocalStorageType($dependencies->entityManager, $dependencies->subscriberRepository, $dependencies->groupRepository, $dependencies->subscriberFactory), [new StorageType()], [
            'groups' => []
        ]);
        $this->expectException(NoGroupException::class);
        $storage->saveSubscriber($subscriberMock);
    }

    public function testExists()
    {
        $dependencies = $this->createDependencies();
        $localSubscriber = new LocalSubscriber();
                $localSubscriber->setEmail('to@enhavo.com');
        $localSubscriber->setSubscription('default');
        $group = new Group();
        $group->setCode('local');
        $localSubscriber->addGroup($group);
        $dependencies->subscriberRepository->expects($this->exactly(3))->method('findOneBy')->willReturn($localSubscriber);
        $dependencies->subscriberFactory->expects($this->never())->method('createFrom');
        $dependencies->groupRepository->expects($this->exactly(2))->method('findOneBy')->willReturnCallback(function ($criteria) use ($group) {
            $this->assertEquals(['code' => 'local'], $criteria);
            if ($criteria['code'] !== 'local') {
                return null;
            }
            return $group;
        });

        $storage = $this->createInstance(new LocalStorageType($dependencies->entityManager, $dependencies->subscriberRepository, $dependencies->groupRepository, $dependencies->subscriberFactory), [new StorageType()], [
            'groups' => [
                'local'
            ]
        ]);
        /** @var SubscriberInterface|MockObject $subscriberMock */
        $subscriberMock = $this->getMockBuilder(SubscriberInterface::class)->getMock();
        $subscriberMock->method('getEmail')->willReturn('to@enhavo.com');
        $subscriberMock->method('getSubscription')->willReturn('default');

        $this->assertTrue($storage->exists($subscriberMock));

        $localSubscriber->removeGroup($group);
        $this->assertFalse($storage->exists($subscriberMock));

        $localSubscriber->addGroup(new Group());
        $this->assertFalse($storage->exists($subscriberMock));
    }

    public function testGetReceivers()
    {
        $dependencies = $this->createDependencies();

        $storage = $this->createInstance(new LocalStorageType($dependencies->entityManager, $dependencies->subscriberRepository, $dependencies->groupRepository, $dependencies->subscriberFactory), [new StorageType()], [
            'groups' => [
                'local'
            ]
        ]);

        $newsletter = new Newsletter();
        $group = new Group();
        $group->setCode('local');
        $subscriber = new LocalSubscriber();
        $subscriber->setEmail('to@enhavo.com');
        $subscriber->setSubscription('default');
        $subscriber->setToken('__TOKEN__');
        $group->addSubscriber($subscriber);
        $newsletter->addGroup($group);

        $receivers = $storage->getReceivers($newsletter);
        $this->assertCount(1, $receivers);
        /** @var Receiver $receiver */
        $receiver = $receivers[0];
        $this->assertEquals($receiver->getEmail(), $subscriber->getEmail());
        $this->assertEquals([
            'token' => $subscriber->getToken(),
            'type' => $subscriber->getSubscription(),
        ], $receiver->getParameters());
        $this->assertEquals($subscriber->getEmail(), $receiver->getEmail());

        $this->expectException(\InvalidArgumentException::class);
        $storage->getReceivers(new NotNewsletter());
    }

    public function testRemoveSubscriber()
    {
        $group = new Group();
        $group->setCode('local');

        $dependencies = $this->createDependencies();
        $dependencies->groupRepository->expects($this->once())->method('findOneBy')->willReturn($group);
        $dependencies->entityManager->expects($this->once())->method('remove');
        $dependencies->entityManager->expects($this->exactly(2))->method('flush');
        $dependencies->subscriberRepository->expects($this->exactly(3))->method('findOneBy')->willReturnCallback(function ($criteria) use ($group) {
            if ($criteria['subscription'] === 'missing') {
                return null;
            } else if ($criteria['subscription'] === 'found') {
                return new LocalSubscriber();

            } else if ($criteria['subscription'] === 'groups') {
                $subscriber = new LocalSubscriber();
                $subscriber->addGroup($group);
                return $subscriber;
            }
        });

        $storage = $this->createInstance(new LocalStorageType($dependencies->entityManager, $dependencies->subscriberRepository, $dependencies->groupRepository, $dependencies->subscriberFactory), [new StorageType()], [
            'groups' => []
        ]);

//        $storage = $this->createInstance(new LocalStorageType($dependencies->entityManager, $dependencies->subscriberRepository, $dependencies->groupRepository, $dependencies->subscriberFactory), [new StorageType()], [
//            'groups' => [
//                'local'
//            ]
//        ]);

        $subscriber = new Subscriber();
        $subscriber->setEmail('to@enhavo.com');
        $subscriber->setSubscription('missing');

        $result = $storage->removeSubscriber($subscriber);
        $this->assertEquals(false, $result);

        $subscriber->setSubscription('found');

        $result = $storage->removeSubscriber($subscriber);
        $this->assertEquals(true, $result);

        $subscriber = new GroupAwareSubscriberMock();
        $subscriber->setEmail('to@enhavo.com');
        $subscriber->setSubscription('groups');
        $subscriber->addGroup($group);
        $result = $storage->removeSubscriber($subscriber);
        $this->assertEquals(true, $result);

    }

}

class NotNewsletter implements NewsletterInterface
{

    public function getId()
    {
    }

    public function getSlug()
    {
    }

    public function setSlug($slug)
    {
    }

    public function setSubject($subject)
    {
    }

    public function getSubject()
    {
    }

    public function setContent(NodeInterface $content)
    {

    }

    public function getContent()
    {
    }

    public function getTemplate(): ?string
    {
        return null;
    }

    public function setTemplate(?string $template)
    {

    }

    public function isPrepared()
    {

    }

    public function isSent()
    {

    }

    public function getState()
    {

    }

    public function setState(string $state)
    {

    }

    public function addReceiver(Receiver $receiver)
    {

    }

    public function removeReceiver(Receiver $receiver)
    {

    }

    public function getReceivers()
    {
        return [];
    }

    public function addAttachment(FileInterface $attachments)
    {

    }

    public function removeAttachment(FileInterface $attachments)
    {

    }

    public function getAttachments()
    {
        return [];
    }

    public function getStartAt(): ?\DateTime
    {
        return new \DateTime();
    }

    public function setStartAt(?\DateTime $startAt): void
    {

    }

    public function getFinishAt(): ?\DateTime
    {
        return new \DateTime();
    }

    public function setFinishAt(?\DateTime $finishAt): void
    {

    }
}

class LocalTypeStorageTestDependencies
{
    /**
     * @var EntityManagerInterface|MockObject
     */
    public  $entityManager;

    /**
     * @var RepositoryInterface|MockObject
     */
    public  $subscriberRepository;

    /**
     * @var RepositoryInterface|MockObject
     */
    public  $groupRepository;

    /** @var LocalSubscriberFactoryInterface|MockObject */
    public $subscriberFactory;
}


text:
namespace blink {

using WebPermissionCallback = WebCallbacks<WebPermissionStatus, void>;
using WebPermissionsCallback = WebCallbacks<WebPassOwnPtr<WebVector<WebPermissionStatus>>, void>;

class WebPermissionObserver;
class WebURL;

// This client is expected to do general permission handling. From simple
// permission query to requesting new permissions.
class WebPermissionClient {
public:
    // Query the permission status of a given origin for a specific permission.
    virtual void queryPermission(WebPermissionType, const WebURL&, WebPermissionCallback*) { }

    // Request a specific permission for a given origin.
    virtual void requestPermission(WebPermissionType, const WebURL&, WebPermissionCallback*) { }

    // Request some permissions for a given origin.
    virtual void requestPermissions(const WebVector<WebPermissionType>&, const WebURL&, WebPermissionsCallback*) { }

    // Revoke a specific permission for a given origin.
    virtual void revokePermission(WebPermissionType, const WebURL&, WebPermissionCallback*) { }

    // Listen for permission changes for a given origin and inform the observer
    // when they happen. The observer is not owned by the WebPermissionClient.
    // The client should expect stopListening() to be called when the observer
    // will be destroyed.
    virtual void startListening(WebPermissionType, const WebURL&, WebPermissionObserver*) { }

    // Stop listening to all the permission changes associated with the given
    // observer.
    virtual void stopListening(WebPermissionObserver*) { }

protected:
    virtual ~WebPermissionClient() { }
};

} // namespace blink

#endif // WebPermissionClient_h

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.beans.propertyeditors;

import junit.framework.TestCase;
import org.springframework.test.AssertThrows;
import org.springframework.util.ClassUtils;

import java.beans.PropertyEditor;
import java.net.URL;

/**
 * Unit tests for the {@link URLEditor} class.
 *
 * @author Rick Evans
 */
public final class URLEditorTests extends TestCase {

	public void testSunnyDay() throws Exception {
		PropertyEditor urlEditor = new URLEditor();
		urlEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class");
		Object value = urlEditor.getValue();
		assertTrue(value instanceof URL);
		URL url = (URL) value;
		assertEquals(url.toExternalForm(), urlEditor.getAsText());
	}

	public void testGetAsTextReturnsEmptyStringIfValueNotSet() throws Exception {
		PropertyEditor urlEditor = new URLEditor();
		assertEquals("", urlEditor.getAsText());
	}

	public void testWithNonExistentResource() throws Exception {
		new AssertThrows(IllegalArgumentException.class) {
			public void test() throws Exception {
				PropertyEditor urlEditor = new URLEditor();
				urlEditor.setAsText("gonna:/freak/in/the/morning/freak/in/the.evening");
			}
		}.runTest();
	}

	public void testCtorWithNullResourceEditor() throws Exception {
		new AssertThrows(IllegalArgumentException.class) {
			public void test() throws Exception {
				new URLEditor(null);
			}
		}.runTest();
	}

}


text:
<!doctype html>

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

		<title>Inward UX, by Matthew Reidsma</title>

		 <link href="https://fonts.googleapis.com/css?family=Archivo+Black|Montserrat:400,600i|Raleway:100" rel="stylesheet">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/black.css">

Inward UX

Matthew Reidsma // Grand Valley State University

Pick a Partner

Plan a Party

“Yes, but”

Adapted from Design Thinking for Museums

Plan a Party

“Yes, but”

Adapted from Design Thinking for Museums

Plan a Party

“Yes, and”

Adapted from Design Thinking for Museums

Plan a Party

“Yes, and”

Adapted from Design Thinking for Museums

How are the parties different?

Adapted from Design Thinking for Museums

Envisioning Work

Making Work

Improving Work

Karen Cross on Atlassian's Culture

What Kind of Workplace do you want?

Making the Workplace We Want from Getty Museums, CC-BY 4.0

Understand Your Needs

Making the Workplace We Want from Getty Museums, CC-BY 4.0

Examples

Joy

Integrity

Community

Trust

Empathy

Inclusion

Order

More from Needs Inventory from the Center for Nonviolent Communication

Examples

Joy

Integrity

Community

Trust

Empathy

Inclusion

Order

Making the Workplace We Want from Getty Museums, CC-BY 4.0

How Might We?

Making the Workplace We Want from Getty Museums, CC-BY 4.0

How Might We?

Making the Workplace We Want from Getty Museums, CC-BY 4.0

Switch with your Partner

Brainstorm Solutions

Name + Description

Making the Workplace We Want from Getty Museums, CC-BY 4.0

Making the Workplace We Want from Getty Museums, CC-BY 4.0

Brainstorm Solutions

Name + Description

Making the Workplace We Want from Getty Museums, CC-BY 4.0

Get Feedback

“Yes, and”

Get Feedback

“Yes, and”

(Switch) Get Feedback

“Yes, and”

Prototype One Thing

Examples

Website

Email

Policy

Poster

Agenda

Gift Basket

Examples

Website

Email

Policy

Poster

Agenda

Gift Basket

Get Feedback

“Yes, and”

Get Feedback

“Yes, and”

(Switch) Get Feedback

“Yes, and”

Did this Work?


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.smash.smash"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="24" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.smash.smash.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.smash.smash.permission.C2D_MESSAGE" />

    <application
        android:name="com.smash.smash.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/STheme" >
        <meta-data
            android:name="DATABASE"
            android:value="store_database.db" />
        <meta-data
            android:name="VERSION"
            android:value="1" />
        <meta-data
            android:name="QUERY_LOG"
            android:value="true" />
        <meta-data
            android:name="DOMAIN_PACKAGE_NAME"
            android:value="com.smash.smash.Models" />

        <activity
            android:name="com.smash.smash.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name="com.smash.smash.Helpers.MusicService"
            android:exported="true" >
            <intent-filter>
                <action android:name="com.smash.smash.start" />
                <action android:name="com.smash.smash.stop" />
                <action android:name="com.smash.smash.play" />
                <action android:name="com.smash.smash.pause" />
                <action android:name="com.smash.smash.next" />
                <action android:name="com.smash.smash.prev" />
            </intent-filter>
        </service>

        <receiver android:name="com.smash.smash.Helpers.RemoteControlReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </receiver>

        <activity
            android:name="com.smash.smash.AlbumActivity"
            android:label="Album" />
        <activity
            android:name="com.smash.smash.PlayerActivity"
            android:label="Reproduzindo..." />

        <service android:name="com.smash.smash.Helpers.SmashMessagingService" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name="com.smash.smash.Helpers.MyIdService" >
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service
            android:name="com.google.firebase.messaging.FirebaseMessagingService"
            android:exported="true" >
            <intent-filter android:priority="-500" >
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <receiver
            android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.smash.smash" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
            android:exported="false" />

        <service
            android:name="com.google.firebase.iid.FirebaseInstanceIdService"
            android:exported="true" >
            <intent-filter android:priority="-500" >
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <provider
            android:name="com.google.firebase.provider.FirebaseInitProvider"
            android:authorities="com.smash.smash.firebaseinitprovider"
            android:exported="false"
            android:initOrder="100" />

        <receiver
            android:name="com.google.android.gms.measurement.AppMeasurementReceiver"
            android:enabled="true"
            android:exported="false" >
        </receiver>
        <receiver
            android:name="com.google.android.gms.measurement.AppMeasurementInstallReferrerReceiver"
            android:enabled="true"
            android:permission="android.permission.INSTALL_PACKAGES" >
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.google.android.gms.measurement.AppMeasurementService"
            android:enabled="true"
            android:exported="false" />

        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
    </application>

</manifest>


text:
package fr.logica.domain.objects;

import java.io.Serializable;

import fr.logica.business.Action.*;
import fr.logica.business.Entity;
import fr.logica.business.EntityField.SqlTypes;
import fr.logica.business.Key;
import fr.logica.business.KeyModel;
import fr.logica.business.context.RequestContext;
import fr.logica.db.DB;
import fr.logica.domain.annotations.*;
import fr.logica.domain.constants.ShopListLArticleConstants;

/**
 * Entity ShopListLArticle definition
 *
 * @author CGI
 */
@EntityDef(dbName = "SHOP_LIST_L_ARTICLE", primaryKey = { "listId", "articleId" })
@Links({
	@Link(name = "shopListLArticleLList", targetEntity = "shopList", fields = { "listId" }),
	@Link(name = "shopListLArticleLArticle", targetEntity = "shopArticle", fields = { "articleId" })
})
@Actions({
	@Action(code = 0, nextAction = 51, input = Input.NONE, persistence = Persistence.INSERT),
	@Action(code = 51, nextAction = 0, input = Input.NONE, persistence = Persistence.INSERT),
	@Action(code = 70, input = Input.NONE, persistence = Persistence.UPDATE, ui = UserInterface.NONE, process = fr.logica.business.Action.Process.CUSTOM),
	@Action(code = 71, pageName = "SHOP_LIST_L_ARTICLE_SCAN", input = Input.NONE, persistence = Persistence.INSERT, process = fr.logica.business.Action.Process.CUSTOM),
	@Action(code = 2, persistence = Persistence.UPDATE),
	@Action(code = 20, pageName = "SHOP_LIST_L_ARTICLE_DELETE", input = Input.MANY, persistence = Persistence.DELETE, ui = UserInterface.READONLY, process = fr.logica.business.Action.Process.CUSTOM),
	@Action(code = 60, persistence = Persistence.UPDATE, ui = UserInterface.NONE, process = fr.logica.business.Action.Process.CUSTOM)
})
public class ShopListLArticle extends Entity implements Serializable {
	/** serialVersionUID */
	public static final long serialVersionUID = 1L;

	/** Liste */
	@EntityField(sqlName = "LIST_ID", sqlType = SqlTypes.INTEGER, sqlSize = 10, isMandatory = true)
	private Integer listId;

	/** Article */
	@EntityField(sqlName = "ARTICLE_ID", sqlType = SqlTypes.INTEGER, sqlSize = 10, isMandatory = true)
	private Integer articleId;

	/** Quantité */
	@EntityField(sqlName = "QUANTITY", sqlType = SqlTypes.INTEGER, sqlSize = 3, isMandatory = true)
	private Integer quantity = 1;

	/** Statut */
	@EntityField(sqlName = "STATUS", sqlType = SqlTypes.VARCHAR2, sqlSize = 5, defaultValue = "BUY")
	@DefinedValues({
			@DefinedValue(code = "BUY", label = "shopListLArticle.status.BUY", value = "BUY", isDefault = true), // A acheter
			@DefinedValue(code = "DONE", label = "shopListLArticle.status.DONE", value = "DONE") // Acheté
	})
	private String status;

	/** Récapitulatif */
	@EntityField(sqlName = "DELETE_INFOS", sqlType = SqlTypes.VARCHAR2, sqlSize = 1000, memory = fr.logica.business.EntityField.Memory.ALWAYS)
	private String deleteInfos;

	/** Ean13 */
	@EntityField(sqlName = "ITEM_EAN13", sqlType = SqlTypes.VARCHAR2, sqlSize = 13, memory = fr.logica.business.EntityField.Memory.NEVER)
	private String itemEan13;

	/**
	 * Initialize a new ShopListLArticle.

	 * The fields with initial value will be populated.
	 */
	public ShopListLArticle() {
		// Default constructor
		super();
	}

	/**
	 * Initialize a new domain with its primary key.

	 * This method does not load a bean from database.

	 * This method does not call the logic method dbPostLoad().
	 *
	 * @param listId Liste
	 * @param articleId Article

	 */
	public ShopListLArticle(Integer listId, Integer articleId) {
		super();
		Key primaryKey = buildPrimaryKey(listId, articleId);
		setPrimaryKey(primaryKey);
	}

	/**
	 * Initialize a new ShopListLArticle from an existing ShopListLArticle.

	 * All fields value are copied.
	 */
	public ShopListLArticle(ShopListLArticle pShopListLArticle) {
		super(pShopListLArticle);
	}

	/**
	 * Generate a primary key for the entity
	 */
	public static synchronized Key buildPrimaryKey(Integer listId, Integer articleId) {
		KeyModel pkModel = new KeyModel(ShopListLArticleConstants.ENTITY_NAME);
		// FIXME : Récupérer la PK ...
		Key key = new Key(pkModel);
		key.setValue("listId", listId);
		key.setValue("articleId", articleId);

		return key;
	}

	/** Entity name */
	@Override
	public String name() {
		return ShopListLArticleConstants.ENTITY_NAME;
	}

	/** Entity description */
	@Override
	public String description() {
		return null;
	}

	/**
	 * Get the value from field ListId.
	 *
	 * @return the value
	 */
	public Integer getListId() {
		return this.listId;
	}

	/**
	 * Set the value from field ListId.
	 *
	 * @param listId : the value to set
	 */
	public void setListId(final Integer listId) {
		this.listId = listId;
	}

	/**
	 * Get the value from field ArticleId.
	 *
	 * @return the value
	 */
	public Integer getArticleId() {
		return this.articleId;
	}

	/**
	 * Set the value from field ArticleId.
	 *
	 * @param articleId : the value to set
	 */
	public void setArticleId(final Integer articleId) {
		this.articleId = articleId;
	}

	/**
	 * Get the value from field Quantity.
	 *
	 * @return the value
	 */
	public Integer getQuantity() {
		return this.quantity;
	}

	/**
	 * Set the value from field Quantity.
	 *
	 * @param quantity : the value to set
	 */
	public void setQuantity(final Integer quantity) {
		this.quantity = quantity;
	}

	/**
	 * Get the value from field Status.
	 *
	 * @return the value
	 */
	public String getStatus() {
		return this.status;
	}

	/**
	 * Set the value from field Status.
	 *
	 * @param status : the value to set
	 */
	public void setStatus(final String status) {
		this.status = status;
	}

	/**
	 * Get the value from field DeleteInfos.
	 *
	 * @return the value
	 */
	public String getDeleteInfos() {
		return this.deleteInfos;
	}

	/**
	 * Set the value from field DeleteInfos.
	 *
	 * @param deleteInfos : the value to set
	 */
	public void setDeleteInfos(final String deleteInfos) {
		this.deleteInfos = deleteInfos;
	}

	/**
	 * Get the value from field ItemEan13.
	 *
	 * @return the value
	 */
	public String getItemEan13() {
		return this.itemEan13;
	}

	/**
	 * Set the value from field ItemEan13.
	 *
	 * @param itemEan13 : the value to set
	 */
	public void setItemEan13(final String itemEan13) {
		this.itemEan13 = itemEan13;
	}

	/**
	 * Instance of ShopList matching the link ShopListLArticleLList based on foreign key values.

	 * Warning : This method does not cache its results and each call imply a database access !!!
	 *
	 * @param ctx Current context
	 * @return Instance of ShopList matching the link pays if any, null otherwise.
	 */
	public ShopList getRef_ShopListLArticleListFk(RequestContext ctx) {
		return (ShopList) DB.getRef(this, ShopListLArticleConstants.Links.LINK_SHOP_LIST_L_ARTICLE_L_LIST, ctx);
	}

	/**
	 * This method sets all variables of foreign key in the current ShopListLArticle object to match the primary key of the ShopList instance.

	 * If the ShopList instance is null, all foreign key variables will be set to null.

	 * This method does not access database and won't automatically update database link.
	 *
	 * @param pShopList The newly targeted bean of link ShopListLArticleLList.
	 */
	public void setRef_ShopListLArticleListFk(ShopList pShopList) {
		Key primaryKey = null;
		if (pShopList != null) {
			primaryKey = pShopList.getPrimaryKey();
		}
		setForeignKey(ShopListLArticleConstants.Links.LINK_SHOP_LIST_L_ARTICLE_L_LIST, primaryKey);
	}

	/**
	 * Instance of ShopArticle matching the link ShopListLArticleLArticle based on foreign key values.

	 * Warning : This method does not cache its results and each call imply a database access !!!
	 *
	 * @param ctx Current context
	 * @return Instance of ShopArticle matching the link pays if any, null otherwise.
	 */
	public ShopArticle getRef_ShopListLArticleArticleFk(RequestContext ctx) {
		return (ShopArticle) DB.getRef(this, ShopListLArticleConstants.Links.LINK_SHOP_LIST_L_ARTICLE_L_ARTICLE, ctx);
	}

	/**
	 * This method sets all variables of foreign key in the current ShopListLArticle object to match the primary key of the ShopArticle instance.

	 * If the ShopArticle instance is null, all foreign key variables will be set to null.

	 * This method does not access database and won't automatically update database link.
	 *
	 * @param pShopArticle The newly targeted bean of link ShopListLArticleLArticle.
	 */
	public void setRef_ShopListLArticleArticleFk(ShopArticle pShopArticle) {
		Key primaryKey = null;
		if (pShopArticle != null) {
			primaryKey = pShopArticle.getPrimaryKey();
		}
		setForeignKey(ShopListLArticleConstants.Links.LINK_SHOP_LIST_L_ARTICLE_L_ARTICLE, primaryKey);
	}

	/**
	 * Clones the current bean.
	 */
	@Override
	public ShopListLArticle clone() {
		ShopListLArticle clone = (ShopListLArticle) super.clone();
		clone.removeDefaultValues();
		for (String f : getModel().getFields()) {
			clone.invokeSetter(f, invokeGetter(f));
		}
		clone.resetLinksAndBackRefs();
		return clone;
	}

	/**
	 * Removes all initial values from the bean and sets everything to null
	 */
	@Override
	public void removeDefaultValues() {
		quantity = null;
		status = null;
	}
}


text:
using System;
using System.IO;
using Microsoft.Kinect;

namespace Kinect.Toolbox.Record
{
    class ColorRecorder
    {
        DateTime referenceTime;
        readonly BinaryWriter writer;

        internal ColorRecorder(BinaryWriter writer)
        {
            this.writer = writer;
            referenceTime = DateTime.Now;
        }

        public void Record(ColorImageFrame frame)
        {
            // Header
            writer.Write((int)KinectRecordOptions.Color);

            // Data
            TimeSpan timeSpan = DateTime.Now.Subtract(referenceTime);
            referenceTime = DateTime.Now;
            writer.Write((long)timeSpan.TotalMilliseconds);
            writer.Write(frame.BytesPerPixel);
            writer.Write((int)frame.Format);
            writer.Write(frame.Width);
            writer.Write(frame.Height);

            writer.Write(frame.FrameNumber);

            // Bytes
            writer.Write(frame.PixelDataLength);
            byte[] bytes = new byte[frame.PixelDataLength];
            frame.CopyPixelDataTo(bytes);
            writer.Write(bytes);
        }
    }
}


text:
/*
 * NaCl Simple/secure ELF loader (NaCl SEL).
 */

#ifndef NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_SEL_ADDRSPACE_H_
#define NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_SEL_ADDRSPACE_H_ 1

#include "native_client/src/include/nacl_base.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/trusted/service_runtime/nacl_error_code.h"

struct NaClApp; /* fwd */

EXTERN_C_BEGIN

#if NACL_LINUX
extern size_t g_prereserved_sandbox_size;
#endif

enum NaClAslrMode {
  NACL_DISABLE_ASLR,
  NACL_ENABLE_ASLR
};

/*
 * Try to find prereserved sandbox memory.  Sets *p to the start of the
 * sandbox.
 *
 * Returns a non-zero value if prereserved sandbox memory was found and the
 * memory is the same size as the requested size.  Returns zero otherwise.
 */
int NaClFindPrereservedSandboxMemory(void **p, size_t num_bytes);

void NaClAddrSpaceBeforeAlloc(size_t guarded_addrsp_size);

/*
 * Allocate the NaCl module's address space.  The |aslr_mode|
 * argument is passed to NaClAllocateSpaceAslr and may be ignored on
 * platforms where the sandbox requires a zero-base, e.g., ARM.
 */
NaClErrorCode NaClAllocAddrSpaceAslr(struct NaClApp *nap,
                                     enum NaClAslrMode aslr_mode) NACL_WUR;

/*
 * Old interface.  Invokes NaClAllocAddrSpaceAlsr with aslr_mode =
 * NACL_ENABLE_ASLR.
 */
NaClErrorCode NaClAllocAddrSpace(struct NaClApp *nap) NACL_WUR;

/*
 * Apply memory protection to memory regions.
 */
NaClErrorCode NaClMemoryProtection(struct NaClApp *nap) NACL_WUR;

/*
 * Platform-specific routine to allocate memory space for the NaCl
 * module.  mem is an out argument; addrsp_size is the requested
 * address space size, currently always ((size_t) 1) <<
 * nap->addr_bits.  On x86-64, there's a further requirement that this
 * is 4G.
 *
 * If |aslr_mode| is NACL_ENABLE_ASLR, this routine will attempt to
 * pick a random address for the address space.  If we are running on
 * a platform where a zero-based address space is pre-reserved (for
 * Atom performance issues), then |aslr_mode| may be ignored.
 *
 * The actual amount of memory allocated is larger than requested on
 * x86-64 and on the ARM, since guard pages are also allocated to be
 * contiguous with the allocated address space.
 *
 * If successful, the guard pages are also mapped as inaccessible (PROT_NONE).
 *
 * Returns LOAD_OK on success.
 */
NaClErrorCode NaClAllocateSpaceAslr(void **mem, size_t addrsp_size,
                                    enum NaClAslrMode aslr_mode) NACL_WUR;

/*
 * Old interface.  Invokes NaClAllocateSpaceAslr with aslr_mode =
 * NACL_ENABLE_ASLR.
 */
NaClErrorCode NaClAllocateSpace(void **mem, size_t addrsp_size) NACL_WUR;

/*
 * NaClAddrSpaceFree() unmaps all of untrusted address space.  This is
 * only safe if no untrusted threads are running.
 *
 * Note that this does not free any other data structures associated
 * with the NaClApp.  In particular, it does not free mem_map.
 */
void NaClAddrSpaceFree(struct NaClApp *nap);

EXTERN_C_END

#endif


text:
<?php

final class DifferentialTransaction extends PhabricatorApplicationTransaction {

  public function getApplicationName() {
    return 'differential';
  }

  public function getApplicationTransactionType() {
    return PhabricatorPHIDConstants::PHID_TYPE_DREV;
  }

  public function getApplicationTransactionCommentObject() {
    return new DifferentialTransactionComment();
  }

  public function getApplicationObjectTypeName() {
    return pht('revision');
  }

}


text:
@echo off
cd %~dp0
cls
set file=XmlLite.dll
taskkill /f /im "spotify.exe" >nul 2>&1
copy "src\%file%" "%appdata%\Spotify\" >nul 2>&1
if errorlevel == 1 goto err
start %appdata%\Spotify\spotify.exe
goto end
:err
echo failed to copy, try again
pause
:end


text:
const float WHEEL_RADIUS = 0.075;
const float PULSES_PER_ROTATION = 64.0;
const float DISTANCE_FROM_RX = 0.138;

#ifndef PI
#define PI 3.141592653589793238;
#endif

class Locator {
public:
	Locator(Stream *encoder_stream, Position initial_position);
	~Locator();

	//getters
	const SimpleEncoder& getBackLeftEncoder() const;
	const SimpleEncoder& getBackRightEncoder() const;
	const EncoderList& getEncoderList() const;
	const SimpleEncoder& getFrontLeftEncoder() const;
	const SimpleEncoder& getFrontRightEncoder() const;
	float getLastRobotAngularSpeed() const;
	float getLastRobotLinearSpeed() const;
	unsigned long getLastUpdateTime() const;
	float getRobotAngularSpeed() const;
	float getRobotLinearSpeed() const;

	void start();
	void initMPU();
	void update();
	Position* getLastPosition();
	void reset(Position new_position);
	EncoderList encoder_list;

	void readMPU();
	float euler_degrees[3];
	float initial_euler_degrees;

public:
	SimpleEncoder front_left_encoder;
	SimpleEncoder front_right_encoder;
	SimpleEncoder back_left_encoder;
	SimpleEncoder back_right_encoder;

	unsigned long last_update_time;
	float robot_linear_speed;
	float robot_angular_speed;
	// Stream *encoder_stream;

	float last_robot_linear_speed;
	float last_robot_angular_speed;

	float left_speed, right_speed;
	Position last_position;

	float rps[4];
	MPU9150Lib MPU;
	bool mpu_first_time;

	void calculateSpeeds(float pps[]);
	void calcutePosition(float deta_t);

};

#endif


text:
class ModelInstance;
class DXObjectOrientedBoundingBox;
class Physics;

typedef std::unordered_map<ModelInstance*, std::unordered_map<ModelInstance*, DXObjectOrientedBoundingBox>> DeformableCollisionPair;

class DeformationPipeline
{
public:
	DeformationPipeline(){};
	~DeformationPipeline(){};
	HRESULT Create(ID3D11Device1* pd3dDevice);
	void Destroy();

	const DeformableCollisionPair& GetCollisionPairs() { return m_deformablePenetratorPairs; };
	void DetectDeformableCollisionPairs(Physics* physicsEngine, bool useCollisionsFromPhysics);
	void CheckAndApplyDeformation(ID3D11Device1* pd3dDevice, ID3D11DeviceContext1* pd3dImmediateContext);

protected:

	DeformableCollisionPair m_deformablePenetratorPairs;
};

extern DeformationPipeline g_deformationPipeline;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Relation-Bootstrap</groupId>
  <artifactId>Relation-Bootstrap</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-scm-plugin</artifactId>
			<version>1.9</version>
			<configuration>
				<connectionUrl>scm:git:https://github.com/stucco/${module.name}.git</connectionUrl>
				<checkoutDirectory>${module.name}</checkoutDirectory>
			</configuration>
		</plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>gov.ornl.stucco</groupId>
        <artifactId>entity-extractor</artifactId>
        <version>1.0.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/entity-extractor-bootstrap.jar</systemPath>
    </dependency>
  	<dependency>
  		<groupId>edu.stanford.nlp</groupId>
  		<artifactId>stanford-corenlp</artifactId>
  		<version>3.5.0</version>
  	</dependency>
  	<dependency>
		<groupId>edu.stanford.nlp</groupId>
		<artifactId>stanford-corenlp</artifactId>
		<version>3.5.0</version>
		<classifier>models</classifier>
	</dependency>
  	<dependency>
  		<groupId>com.googlecode.json-simple</groupId>
  		<artifactId>json-simple</artifactId>
  		<version>1.1.1</version>
  	</dependency>
  	<dependency>
  		<groupId>commons-io</groupId>
  		<artifactId>commons-io</artifactId>
  		<version>2.5</version>
  	</dependency>
  	<dependency>
  		<groupId>com.fasterxml.jackson.core</groupId>
  		<artifactId>jackson-databind</artifactId>
  		<version>2.7.0</version>
  	</dependency>
  </dependencies>
</project>


text:
/* vim: set sw=8 ts=8 sts=8 noexpandtab: */
#ifndef EWL_TREE2_H
#define EWL_TREE2_H

#include "ewl_mvc.h"

/**
 * @addtogroup Ewl_Tree2 Ewl_Tree2: A Widget for List or Tree Layout
 * @brief Defines a widget for laying out other widgets in a tree or list
 * like manner. This also fulfills the functionality often seen in a table
 * widget.
 *
 * Model:
 * Defines communication callbacks for views and controllers. Query row/column
 * data, indicate expansion points, notify views and controllers of changes,
 * trigger sorting on a row/column combination.
 *
 * Data:
 * Provides a wrapper to the data which allows for observer registration and a
 * reference to a model for data access.
 *
 * View:
 * Defines the callbacks for setting up the widgets based on the data returned
 * from the Model. Create widgets, set data on widgets, calculate sizing,
 * minimize number of widgets.
 *
 * Controller:
 * The tree defines the entire controller and registers with the model.
 * Provides controls to sort columns, expand/collapse branching points, reacts
 * to changes from data model.
 *
 * Simple case:
 * Widgets packed using standard container functions. This should result in a
 * simple list of packed widgets.
 *
 * Features:
 * * Default data provider, so standard container functions are supported.
 * * MVC pattern of data access for more powerful layouts.
 * * Packing of arbitrary widget types in cells.
 * * Theming based on repeating row counts.
 * * Number of columns dependant on number of providers, not a fixed number.
 * * When using data providers, can reap widgets to save memory and decrease
 *   layout time.
 *
 * Issues:
 * * How do we support click callbacks on full rows? Special notifier
 *   necessary? Proposal: Tree value change callback on row selection. Passes
 *   event structure with array of selected row numbers. Simple case handled
 *   by callback on packed widgets.
 * * Column or row layout? Column allows for redirecting to a container to
 *   handle the case of container functions used to add widgets and to use a
 *   fixed number of rows in display region. It would also allow for skipping
 *   configure of an entire off-screen column, rows would lay out the cells
 *   off-screen. How do we implement column layout? Proposal: Row height
 *   cache, easy for fixed height rows, more complex for variable height.
 *
 * @remarks Inherits from Ewl_MVC.
 * @image html Ewl_Tree2_inheritance.png
 *
 * @{
 */

/**
 * @themekey /tree/file
 * @themekey /tree/group
 */

/**
 * @def EWL_TREE2_TYPE
 * The type name for the Ewl_ widget
 */
#define EWL_TREE2_TYPE "tree2"

/**
 * @def EWL_TREE2_IS(w)
 * Returns TRUE if the widget is an Ewl_Tree2, FALSE otherwise
 */
#define EWL_TREE2_IS(w) (ewl_widget_type_is(EWL_WIDGET(w), EWL_TREE2_TYPE))

/**
 * @def EWL_TREE2(t)
 * Typecasts a pointer to an Ewl_Tree pointer.
 */
#define EWL_TREE2(t) ((Ewl_Tree2 *)t)

/**
 * The Ewl_Tree2 widget
 */
typedef struct Ewl_Tree2 Ewl_Tree2;

/**
 * @brief Inherits from Ewl_MVC and extends to provide a tree widget.
 */
struct Ewl_Tree2
{
	Ewl_MVC mvc; 		/**< Inherit from ewl_mvc. */

	Ewl_View *content_view;	/**< View for the content widget */

	Ewl_Widget *header; 	/**< The tree header */
	Ewl_Widget *rows; 	/**< The rows of the tree */

	unsigned int *rowcache; /**< Cache of row sizes */

	Ewl_Tree_Selection_Type type;	 /**< The selection type of the tree */

	Ecore_Hash *expansions;	/**< Hash of expanded rows */

	struct
	{
		unsigned int column;	/**< The sort column */
		Ewl_Sort_Direction direction; /**< Sort direction */
	} sort;			/**< The sort information */

	unsigned int columns;	/**< Number of columns in the tree */
	unsigned char fixed:1;    /**< Rows are fixed height */
	unsigned char headers_visible:1; /**< Are the headers visible? */
};

/*
 * Tree view/controller manipulation
 */
Ewl_Widget 	*ewl_tree2_new(void);
int 		 ewl_tree2_init(Ewl_Tree2 *tree);

void		 ewl_tree2_column_count_set(Ewl_Tree2 *tree,
						unsigned int count);
unsigned int	 ewl_tree2_column_count_get(Ewl_Tree2 *tree);

void		 ewl_tree2_headers_visible_set(Ewl_Tree2 *tree,
					       unsigned char visible);
unsigned int	 ewl_tree2_headers_visible_get(Ewl_Tree2 *tree);

void		 ewl_tree2_content_view_set(Ewl_Tree2 *tree, Ewl_View *view);
Ewl_View	*ewl_tree2_content_view_get(Ewl_Tree2 *tree);

Ewl_Tree_Selection_Type ewl_tree2_selection_type_get(Ewl_Tree2 *tree);
void 		 ewl_tree2_selection_type_set(Ewl_Tree2 *tree,
						Ewl_Tree_Selection_Type type);

void		 ewl_tree2_fixed_rows_set(Ewl_Tree2 *tree, unsigned int fixed);
unsigned int	 ewl_tree2_fixed_rows_get(Ewl_Tree2 *tree);

Ewl_Widget	*ewl_tree2_content_widget_get(Ewl_Tree2 *tree);

void		 ewl_tree2_row_expand(Ewl_Tree2 *tree, void *data,
						unsigned int row);
void		 ewl_tree2_row_collapse(Ewl_Tree2 *tree, void *data,
						unsigned int row);

unsigned int	 ewl_tree2_row_expanded_is(Ewl_Tree2 *tree, void *data,
						unsigned int row);

/*
 * Internal stuff.
 */
void ewl_tree2_cb_destroy(Ewl_Widget *w, void *ev, void *data);
void ewl_tree2_cb_configure(Ewl_Widget *w, void *ev, void *data);
void ewl_tree2_cb_column_sort(Ewl_Widget *w, void *ev, void *data);

/*
 * Ewl_Tree2_Node stuff
 */
#define EWL_TREE2_NODE_TYPE "node"

/**
 * @def EWL_TREE2_NODE_IS(w)
 * Returns TRUE if the widget is an Ewl_Tree2_Node, FALSE otherwise
 */
#define EWL_TREE2_NODE_IS(w) (ewl_widget_type_is(EWL_WIDGET(w), EWL_TREE2_NODE_TYPE))

#define EWL_TREE2_NODE(n) ((Ewl_Tree2_Node *)n)

/**
 * Ewl_Tree2_Node
 */
typedef struct Ewl_Tree2_Node Ewl_Tree2_Node;

/**
 * @brief Inherits from Ewl_Container and extends to hold information on a
 * row of the tree
 */
struct Ewl_Tree2_Node
{
	Ewl_MVC mvc;

	Ewl_Widget *tree;		/**< The parent tree */
	Ewl_Widget *row;		/**< The row this node is for */
	Ewl_Widget *handle;		/**< the expansion handle */

	unsigned int row_num;		/**< The row number of this row */
	Ewl_Tree_Node_Flags expanded;

	unsigned char built_children:1;	/**< Have we generated child nodes */
};

Ewl_Widget	*ewl_tree2_node_new(void);
int		 ewl_tree2_node_init(Ewl_Tree2_Node *node);

void		 ewl_tree2_node_expandable_set(Ewl_Tree2_Node *node, void *data);
unsigned int	 ewl_tree2_node_expandable_get(Ewl_Tree2_Node *node);

void		 ewl_tree2_node_expand(Ewl_Tree2_Node *node);
void		 ewl_tree2_node_collapse(Ewl_Tree2_Node *node);

unsigned int	 ewl_tree2_node_expanded_is(Ewl_Tree2_Node *node);

void ewl_tree2_cb_node_configure(Ewl_Widget *w, void *ev_data, void *user_data);
void ewl_tree2_cb_node_realize(Ewl_Widget *w, void *ev, void *data);
void ewl_tree2_cb_node_toggle(Ewl_Widget *w, void *ev_data, void *user_data);

void ewl_tree2_cb_node_child_show(Ewl_Container *c, Ewl_Widget *w);
void ewl_tree2_cb_node_child_hide(Ewl_Container *c, Ewl_Widget *w);
void ewl_tree2_cb_node_resize(Ewl_Container *c, Ewl_Widget *w, int size,
                                                     Ewl_Orientation o);
void ewl_tree2_cb_node_child_add(Ewl_Container *c, Ewl_Widget *w);
void ewl_tree2_cb_node_child_del(Ewl_Container *c, Ewl_Widget *w, int idx);

/**
 * @}
 */

#endif


text:
/* global Layer2dCamera, Layer2dCanvas */

/**
 * Renderer2d provides an API to components for drawing paths and images to HTML5 canvas.
 * It also handles multiple layers, with configurable render modes per layer.
 *
 * TODO: document config, including layers and cameras
 */
javelin.plugin('renderer2d', function(config) {

    var self = this;
    var renderTarget = null;
    var cameras = {};
    var layers = {};
    var layerRenderTargets = {};
    var engine = this.$engine;
    var lastTimeRendered;
    var targetFps = 30;

    /**
     * Get a camera instance by name.
     *
     * @param  {string} name            Name of camera to get.
     *
     * @return {Layer2dCamera}  The camera instance
     */
    this.getCamera = function (name) {
        if (!cameras[name]) {
            throw new Error("Unknown camera ["+name+"] requested.");
        }

        return cameras[name];
    };

    /**
     * Get a layer instance by name.  Currently only Canvas2dRenderLayers
     * are supported, but in the future there may be other types of layer
     * renderers.
     *
     * @param  {string} name            Name of layer to get.
     *
     * @return {Canvas2dRenderer}  The layer instance
     */
    this.getLayer = function(name) {
        if (!layers[name]) {
            throw new Error("Unknown layer ["+name+"] requested.");
        }

        return layers[name];
    };

    /**
     * Load creates layer and camera instances based on given config.  If config
     * does not specify anything, there is always a 'default' layer, and a
     * 'default' camera.
     */
    this.$onLoad = function() {
        //only active in the browser
        if (!document || !window) {
            self.$active = false;
            console.log("No browser environment detected - deactivating the renderer2d plugin.");
            return;
        }

        targetFps = config.framesPerSecond || engine.stepsPerSecond;
        lastTimeRendered = 0.0;

        var target = document.getElementById(config.renderTargetId);
        renderTarget = target;

        if (!target) {
            throw new Error("No render target defined!");
        }

        //enforce default layer
        config.layers = config.layers || {};
        if (!config.layers['default']) {
            config.layers['default'] = {
                renderer: 'canvas2d',
                camera: 'default',
                clearOnUpdate: true,
                config: {
                    pixelsPerUnit: 20
                }
            };
        }

        //enforce default camera
        config.cameras = config.cameras || {};
        if (!config.cameras['default']) {
            config.cameras['default'] = {};
        }

        //create cameras
        for (var cameraName in config.cameras) {
            cameras[cameraName] = new Layer2dCamera(cameraName, config.cameras[cameraName]);
        }

        //create and stack layer containers
        var targetStyle = window.getComputedStyle(renderTarget);
        var targetHeight = targetStyle.height;
        var targetWidth = targetStyle.width;
        var zIndex = targetStyle.zIndex || 0;
        for (var layerName in config.layers) {
            var layerConfig = config.layers[layerName];
            zIndex++;

            //create layer render target, add to DOM
            var layerRenderTarget = document.createElement('div');
            layerRenderTarget.style.height = targetHeight;
            layerRenderTarget.style.width = targetWidth;
            layerRenderTarget.style.zIndex = zIndex;
            // layerRenderTarget.style.top = top;
            // layerRenderTarget.style.left = left;
            layerRenderTarget.id = 'javelin-layer-' + layerName;
            layerRenderTargets[layerName] = layerRenderTarget;
            target.appendChild(layerRenderTarget);

            //instantiate layer with render target
            var layerInstance = createLayerInstance(
                layerRenderTarget,
                self.getCamera(layerConfig.camera || 'default'),
                layerConfig.config
            );

            layers[layerName] = layerInstance;
        }
    };

    /**
     * Unload will remove any created layerRenderTargets.
     */
    this.$onUnload = function() {
        for (var name in layerRenderTargets) {
            renderTarget.removeChild(layerRenderTargets[name]);
        }

        //drop internally created objects
        layerRenderTargets = {};
        layers = {};
        cameras = {};
    };

    /**
     * PostUpdate will call all available `renderer2d.draw` callbacks registered
     * by entity components, passing along the relevant layer instance and camera.
     */
    this.$onPostUpdate = function(deltaTime) {
        if (engine.isRunningSlowly || engine.time - lastTimeRendered <= targetFps) {
            console.log("skipping frame");
            return;
        }

        var i, j;

        //clear all layers
        for (var layerName in config.layers) {
            if (config.layers[layerName].clearOnUpdate) {
                layers[layerName].clear();
            }
        }

        //execute `renderer2d.draw` callbacks on all root game objects (by layer)
        var entities = engine.gos;
        var li = entities.length;
        for (i = 0; i < li; i++) {
            if (entities[i].enabled && entities[i].isRoot()) {
                var layer = self.getLayer(entities[i].layer);
                var camera = layer.getCamera();
                this.$engine.broadcast('renderer2d.draw', [layer, camera]);
            }
        }

        lastTimeRendered = engine.time;
    };

    var createLayerInstance = function(layerRenderTarget, camera, layerConfig) {
        //one day, this could return different types of
        //render layers
        return new Layer2dCanvas(layerRenderTarget, camera, layerConfig);
    };
});


text:
package org.kie.workbench.common.widgets.decoratedgrid.client.widget.cells;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
import org.kie.soup.project.datamodel.oracle.DropDownData;
import org.kie.workbench.common.widgets.client.datamodel.AsyncPackageDataModelOracle;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.CellTableDropDownDataValueMapProvider;

/**
 * A Popup drop-down Editor proxy that delegates operation to different implementations depending on whether
 * the cell should represent a list of values or single value. The need arose from incomplete dependent enumeration
 * definitions; e.g. Fact.field1=['A', 'B'] Fact.field2[field1=A]=['A1', 'A2']; where no dependent enumeration has
 * been defined for Fact.field2[field1=B]. In this scenario a TextBox for field2 should be shown when field1=B
 */
public abstract class AbstractProxyPopupDropDownEditCell<C, V> extends
                                                               AbstractPopupEditCell<C, V> {

    private final String factType;
    private final String factField;

    private final AsyncPackageDataModelOracle dmo;
    private final CellTableDropDownDataValueMapProvider dropDownManager;

    private final ProxyPopupDropDown<C> singleValueEditor;
    private final ProxyPopupDropDown<C> multipleValueEditor;
    private ProxyPopupDropDown<C> delegate;

    public AbstractProxyPopupDropDownEditCell(final String factType,
                                              final String factField,
                                              final String operator,
                                              final AsyncPackageDataModelOracle dmo,
                                              final CellTableDropDownDataValueMapProvider dropDownManager,
                                              final boolean isReadOnly) {
        super(isReadOnly);
        this.factType = factType;
        this.factField = factField;
        this.dropDownManager = dropDownManager;
        this.singleValueEditor = getSingleValueEditor();
        this.multipleValueEditor = getMultipleValueEditor(operator);
        this.dmo = dmo;
    }

    @Override
    public void render(final Context context,
                       final C value,
                       final SafeHtmlBuilder sb) {

        //We need to get the list of potential values to lookup the "Display" value from the "Stored" value.
        //Since the content of the list may be different for each cell (dependent enumerations) the list
        //has to be populated "on demand".
        DropDownData dd = dmo.getEnums(this.factType,
                                       this.factField,
                                       this.dropDownManager.getCurrentValueMap(context));

        if (dd == null) {
            //If no enumeration exists show a TextBox
            delegate = singleValueEditor;
            delegate.setValue(value);
            vPanel.clear();
            vPanel.add(delegate.asWidget());
        } else {
            //Otherwise show a drop-down list box
            delegate = multipleValueEditor;
            delegate.setDropDownData(dd);
            vPanel.clear();
            vPanel.add(delegate.asWidget());
        }

        delegate.render(context,
                        value,
                        sb,
                        renderer);
    }

    @Override
    protected void commit() {
        final C value = delegate.getValue();

        setValue(lastContext,
                 lastParent,
                 value);
        if (valueUpdater != null) {
            valueUpdater.update(value);
        }
        panel.hide();
    }

    // Start editing the cell
    @Override
    protected void startEditing(final Context context,
                                final Element parent,
                                final C value) {

        //We need to get the list of potential values for the enumeration. Since the content
        //of the list may be different for each cell (dependent enumerations) the list
        //has to be populated "on demand".
        DropDownData dd = dmo.getEnums(this.factType,
                                       this.factField,
                                       this.dropDownManager.getCurrentValueMap(context));
        if (dd == null) {
            //If no enumeration exists show a TextBox
            delegate = singleValueEditor;
            delegate.setValue(value);
            vPanel.clear();
            vPanel.add(delegate.asWidget());
        } else {
            //Otherwise show a drop-down list box
            delegate = multipleValueEditor;
            delegate.setDropDownData(dd);
            vPanel.clear();
            vPanel.add(delegate.asWidget());
        }
        delegate.startEditing(context,
                              parent,
                              value);

        panel.setPopupPositionAndShow(new PositionCallback() {
            public void setPosition(int offsetWidth,
                                    int offsetHeight) {
                panel.setPopupPosition(parent.getAbsoluteLeft()
                                               + offsetX,
                                       parent.getAbsoluteTop()
                                               + offsetY);

                // Focus the first enabled control
                Scheduler.get().scheduleDeferred(new ScheduledCommand() {

                    public void execute() {
                        delegate.setFocus(true);
                    }
                });
            }
        });
    }

    AsyncPackageDataModelOracle getDataModelOracle() {
        return this.dmo;
    }

    protected abstract ProxyPopupDropDown<C> getSingleValueEditor();

    protected abstract ProxyPopupDropDown<C> getMultipleValueEditor(final String operator);
}


text:
<@pp.dropOutputFile />

<#list cast.types as type>

<#if type.major == "IntervalVarChar">  <#-- Template to convert from Interval, IntervalYear, IntervalDay to VarChar -->

<@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/gcast/Cast${type.from}To${type.to}.java" />

<#include "/@includes/license.ftl" />

package org.apache.drill.exec.expr.fn.impl.gcast;

<#include "/@includes/vv_imports.ftl" />

import io.netty.buffer.ByteBuf;
import io.netty.buffer.DrillBuf;

import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionCostCategory;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.holders.*;
import org.apache.drill.exec.record.RecordBatch;
import org.joda.time.MutableDateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.DateMidnight;

/*
 * This class is generated using freemarker and the ${.template_name} template.
 */
@SuppressWarnings("unused")
@FunctionTemplate(name = "cast${type.to?upper_case}",
    scope = FunctionTemplate.FunctionScope.SIMPLE,
    returnType = FunctionTemplate.ReturnType.STRING_CAST,
    nulls = NullHandling.NULL_IF_NULL)
public class Cast${type.from}To${type.to} implements DrillSimpleFunc {

  @Param ${type.from}Holder in;
  @Param BigIntHolder len;
  @Inject DrillBuf buffer;
  @Output ${type.to}Holder out;

  public void setup() {
    buffer = buffer.reallocIfNeeded(${type.bufferLength});
  }

  public void eval() {

      int years  = (in.months / org.apache.drill.exec.vector.DateUtilities.yearsToMonths);
      int months = (in.months % org.apache.drill.exec.vector.DateUtilities.yearsToMonths);

      long millis = in.milliseconds;

      long hours  = millis / (org.apache.drill.exec.vector.DateUtilities.hoursToMillis);
      millis     = millis % (org.apache.drill.exec.vector.DateUtilities.hoursToMillis);

      long minutes = millis / (org.apache.drill.exec.vector.DateUtilities.minutesToMillis);
      millis      = millis % (org.apache.drill.exec.vector.DateUtilities.minutesToMillis);

      long seconds = millis / (org.apache.drill.exec.vector.DateUtilities.secondsToMillis);
      millis      = millis % (org.apache.drill.exec.vector.DateUtilities.secondsToMillis);

      String yearString = (Math.abs(years) == 1) ? " year " : " years ";
      String monthString = (Math.abs(months) == 1) ? " month " : " months ";
      String dayString = (Math.abs(in.days) == 1) ? " day " : " days ";

      StringBuilder str = new StringBuilder().
                            append(years).append(yearString).
                            append(months).append(monthString).
                            append(in.days).append(dayString).
                            append(hours).append(":").
                            append(minutes).append(":").
                            append(seconds).append(".").
                            append(millis);
      out.buffer = buffer;
      out.start = 0;
      out.end = Math.min((int)len.value, str.length()); // truncate if target type has length smaller than that of input's string
      out.buffer.setBytes(0, String.valueOf(str.substring(0,out.end)).getBytes(java.nio.charset.StandardCharsets.UTF_8));
  }
}

<#elseif type.major == "IntervalYearVarChar">
<@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/gcast/Cast${type.from}To${type.to}.java" />

<#include "/@includes/license.ftl" />

package org.apache.drill.exec.expr.fn.impl.gcast;

<#include "/@includes/vv_imports.ftl" />

import io.netty.buffer.ByteBuf;

import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionCostCategory;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.holders.*;
import org.apache.drill.exec.record.RecordBatch;
import org.joda.time.MutableDateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.DateMidnight;

@SuppressWarnings("unused")
@FunctionTemplate(name = "cast${type.to?upper_case}",
    scope = FunctionTemplate.FunctionScope.SIMPLE,
    returnType = FunctionTemplate.ReturnType.STRING_CAST,
    nulls = NullHandling.NULL_IF_NULL)
public class Cast${type.from}To${type.to} implements DrillSimpleFunc {

  @Param ${type.from}Holder in;
  @Param BigIntHolder len;
  @Inject DrillBuf buffer;
  @Output ${type.to}Holder out;

  public void setup() {
    buffer = buffer.reallocIfNeeded((int) len.value);
  }

  public void eval() {
      int years  = (in.value / org.apache.drill.exec.vector.DateUtilities.yearsToMonths);
      int months = (in.value % org.apache.drill.exec.vector.DateUtilities.yearsToMonths);

      String yearString = (Math.abs(years) == 1) ? " year " : " years ";
      String monthString = (Math.abs(months) == 1) ? " month " : " months ";

      StringBuilder str = new StringBuilder().append(years).append(yearString).append(months).append(monthString);

      out.buffer = buffer;
      out.start = 0;
      out.end = Math.min((int)len.value, str.length()); // truncate if target type has length smaller than that of input's string
      out.buffer.setBytes(0, String.valueOf(str.substring(0,out.end)).getBytes(java.nio.charset.StandardCharsets.UTF_8));
  }
}

<#elseif type.major == "IntervalDayVarChar">
<@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/gcast/Cast${type.from}To${type.to}.java" />

<#include "/@includes/license.ftl" />

package org.apache.drill.exec.expr.fn.impl.gcast;

import io.netty.buffer.ByteBuf;

import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionCostCategory;
import org.apache.drill.exec.expr.annotations.FunctionTemplate.NullHandling;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.holders.*;
import org.apache.drill.exec.record.RecordBatch;
import org.joda.time.MutableDateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.DateMidnight;
import javax.inject.Inject;
import io.netty.buffer.DrillBuf;

@SuppressWarnings("unused")
@FunctionTemplate(name = "cast${type.to?upper_case}",
    scope = FunctionTemplate.FunctionScope.SIMPLE,
    returnType = FunctionTemplate.ReturnType.STRING_CAST,
    nulls = NullHandling.NULL_IF_NULL,
    costCategory = FunctionCostCategory.COMPLEX)
public class Cast${type.from}To${type.to} implements DrillSimpleFunc {

  @Param ${type.from}Holder in;
  @Param BigIntHolder len;
  @Inject DrillBuf buffer;
  @Output ${type.to}Holder out;

  public void setup() {
    buffer = buffer.reallocIfNeeded((int) len.value);
  }

  public void eval() {
      long millis = in.milliseconds;

      long hours  = millis / (org.apache.drill.exec.vector.DateUtilities.hoursToMillis);
      millis     = millis % (org.apache.drill.exec.vector.DateUtilities.hoursToMillis);

      long minutes = millis / (org.apache.drill.exec.vector.DateUtilities.minutesToMillis);
      millis      = millis % (org.apache.drill.exec.vector.DateUtilities.minutesToMillis);

      long seconds = millis / (org.apache.drill.exec.vector.DateUtilities.secondsToMillis);
      millis      = millis % (org.apache.drill.exec.vector.DateUtilities.secondsToMillis);

      String dayString = (Math.abs(in.days) == 1) ? " day " : " days ";

      StringBuilder str = new StringBuilder().
                            append(in.days).append(dayString).
                            append(hours).append(":").
                            append(minutes).append(":").
                            append(seconds).append(".").
                            append(millis);

      out.buffer = buffer;
      out.start = 0;
      out.end = Math.min((int)len.value, str.length()); // truncate if target type has length smaller than that of input's string
      out.buffer.setBytes(0, String.valueOf(str.substring(0,out.end)).getBytes(java.nio.charset.StandardCharsets.UTF_8));
  }
}
</#if> <#-- type.major -->
</#list>


text:
package org.quantintel.ql.instruments.options.nvpd

/**
 *
 * A cliquet option or 'ratchet option" is an exotic option consisting of a series
 * of consecutive forward start options.  The first is active immediately.  The
 * second becomes active when the first expires, ect.  Each option is struck at-th-
 * money when it becomes active.
 * A cliqet is, therefore, a series of at-the-money options but where the total
 * premium is determined in advance.  A cliquet can be thought of a series of "pre-
 * purchased" at-the-money options.  The payout on each option can either be paid at
 * the final maturity, or at th eend of each reset period.
 * source- Wikipedia 2014
 *
 * @author Paul Bernard
 */
class CliquetOption {

}


text:
from __future__ import print_function

from apiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools

SCOPES = "https://www.googleapis.com/auth/forms.body"
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"

store = file.Storage('token.json')
creds = None
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES)
    creds = tools.run_flow(flow, store)

form_service = discovery.build('forms', 'v1', http=creds.authorize(
    Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False)

form = {
    "info": {
        "title": "My new quiz",
    }
}

# Creates the initial form
result = form_service.forms().create(body=form).execute()

# JSON to convert the form into a quiz
update = {
    "requests": [
        {
            "updateSettings": {
                "settings": {
                    "quizSettings": {
                        "isQuiz": True
                    }
                },
                "updateMask": "quizSettings.isQuiz"
            }
        }
    ]
}

# Converts the form into a quiz
question_setting = form_service.forms().batchUpdate(formId=result["formId"],
                                                    body=update).execute()

# Print the result to see it's now a quiz
getresult = form_service.forms().get(formId=result["formId"]).execute()
print(getresult)
# [END forms_convert_form]


text:
"""Unit tests for NEC Driver."""

from unittest import mock

from oslo_config import cfg
import requests

from cinder import context as cinder_context
from cinder import db
from cinder.tests.unit import fake_volume
from cinder.tests.unit import test
from cinder.volume import configuration as conf
from cinder.volume.drivers.hitachi import hbsd_rest
from cinder.volume.drivers.hitachi import hbsd_rest_api
from cinder.volume.drivers.nec.v import nec_v_fc
from cinder.volume.drivers.nec.v import nec_v_rest
from cinder.volume import volume_utils

# Configuration parameter values
CONFIG_MAP = {
    'serial': '886000123456',
    'my_ip': '127.0.0.1',
    'rest_server_ip_addr': '172.16.18.108',
    'rest_server_ip_port': '23451',
    'port_id': 'CL1-A',
    'host_grp_name': 'NEC-0123456789abcdef',
    'host_mode': 'LINUX/IRIX',
    'host_wwn': '0123456789abcdef',
    'target_wwn': '1111111123456789',
    'user_id': 'user',
    'user_pass': 'password',
    'pool_name': 'test_pool',
    'auth_user': 'auth_user',
    'auth_password': 'auth_password',
}

# Dummy response
DEFAULT_CONNECTOR = {
    'host': 'host',
    'ip': CONFIG_MAP['my_ip'],
    'wwpns': [CONFIG_MAP['host_wwn']],
    'multipath': False,
}

# Dummy response for REST API
POST_SESSIONS_RESULT = {
    "token": "b74777a3-f9f0-4ea8-bd8f-09847fac48d3",
    "sessionId": 0,
}

GET_PORTS_RESULT = {
    "data": [
        {
            "portId": CONFIG_MAP['port_id'],
            "portType": "FIBRE",
            "portAttributes": [
                "TAR",
                "MCU",
                "RCU",
                "ELUN"
            ],
            "fabricMode": True,
            "portConnection": "PtoP",
            "lunSecuritySetting": True,
            "wwn": CONFIG_MAP['target_wwn'],
        },
    ],
}

GET_HOST_WWNS_RESULT = {
    "data": [
        {
            "hostGroupNumber": 0,
            "hostWwn": CONFIG_MAP['host_wwn'],
        },
    ],
}

COMPLETED_SUCCEEDED_RESULT = {
    "status": "Completed",
    "state": "Succeeded",
    "affectedResources": ('a/b/c/1',),
}

def _brick_get_connector_properties(multipath=False, enforce_multipath=False):
    """Return a predefined connector object."""
    return DEFAULT_CONNECTOR

class FakeResponse():

    def __init__(self, status_code, data=None, headers=None):
        self.status_code = status_code
        self.data = data
        self.text = data
        self.content = data
        self.headers = {'Content-Type': 'json'} if headers is None else headers

    def json(self):
        return self.data

class VStorageRESTFCDriverTest(test.TestCase):
    """Unit test class for NEC REST interface fibre channel module."""

    test_existing_ref = {'source-id': '1'}
    test_existing_ref_name = {
        'source-name': '15960cc7-38c9-4c5b-b4f1-365be5eeed45'}

    def setUp(self):
        """Set up the test environment."""
        def _set_required(opts, required):
            for opt in opts:
                opt.required = required

        # Initialize Cinder and avoid checking driver options.
        rest_required_opts = [
            opt for opt in nec_v_rest.REST_VOLUME_OPTS if opt.required]
        common_required_opts = [
            opt for opt in nec_v_rest.COMMON_VOLUME_OPTS if opt.required]
        _set_required(rest_required_opts, False)
        _set_required(common_required_opts, False)
        super(VStorageRESTFCDriverTest, self).setUp()
        _set_required(rest_required_opts, True)
        _set_required(common_required_opts, True)

        self.configuration = mock.Mock(conf.Configuration)
        self.ctxt = cinder_context.get_admin_context()
        self._setup_config()
        self._setup_driver()

    def _setup_config(self):
        """Set configuration parameter values."""
        self.configuration.config_group = "REST"

        self.configuration.volume_backend_name = "RESTFC"
        self.configuration.volume_driver = (
            "cinder.volume.drivers.nec.v.nec_v_fc.VStorageFCDriver")
        self.configuration.reserved_percentage = "0"
        self.configuration.use_multipath_for_image_xfer = False
        self.configuration.enforce_multipath_for_image_xfer = False
        self.configuration.max_over_subscription_ratio = 500.0
        self.configuration.driver_ssl_cert_verify = False

        self.configuration.nec_v_storage_id = CONFIG_MAP['serial']
        self.configuration.nec_v_pool = "30"
        self.configuration.nec_v_snap_pool = None
        self.configuration.nec_v_ldev_range = "0-1"
        self.configuration.nec_v_target_ports = [CONFIG_MAP['port_id']]
        self.configuration.nec_v_compute_target_ports = [
            CONFIG_MAP['port_id']]
        self.configuration.nec_v_group_create = True
        self.configuration.nec_v_group_delete = True
        self.configuration.nec_v_copy_speed = 3
        self.configuration.nec_v_copy_check_interval = 3
        self.configuration.nec_v_async_copy_check_interval = 10

        self.configuration.san_login = CONFIG_MAP['user_id']
        self.configuration.san_password = CONFIG_MAP['user_pass']
        self.configuration.san_ip = CONFIG_MAP[
            'rest_server_ip_addr']
        self.configuration.san_api_port = CONFIG_MAP[
            'rest_server_ip_port']
        self.configuration.nec_v_rest_disable_io_wait = True
        self.configuration.nec_v_rest_tcp_keepalive = True
        self.configuration.nec_v_discard_zero_page = True
        self.configuration.nec_v_rest_number = "0"
        self.configuration.nec_v_lun_timeout = hbsd_rest._LUN_TIMEOUT
        self.configuration.nec_v_lun_retry_interval = (
            hbsd_rest._LUN_RETRY_INTERVAL)
        self.configuration.nec_v_restore_timeout = hbsd_rest._RESTORE_TIMEOUT
        self.configuration.nec_v_state_transition_timeout = (
            hbsd_rest._STATE_TRANSITION_TIMEOUT)
        self.configuration.nec_v_lock_timeout = hbsd_rest_api._LOCK_TIMEOUT
        self.configuration.nec_v_rest_timeout = hbsd_rest_api._REST_TIMEOUT
        self.configuration.nec_v_extend_timeout = (
            hbsd_rest_api._EXTEND_TIMEOUT)
        self.configuration.nec_v_exec_retry_interval = (
            hbsd_rest_api._EXEC_RETRY_INTERVAL)
        self.configuration.nec_v_rest_connect_timeout = (
            hbsd_rest_api._DEFAULT_CONNECT_TIMEOUT)
        self.configuration.nec_v_rest_job_api_response_timeout = (
            hbsd_rest_api._JOB_API_RESPONSE_TIMEOUT)
        self.configuration.nec_v_rest_get_api_response_timeout = (
            hbsd_rest_api._GET_API_RESPONSE_TIMEOUT)
        self.configuration.nec_v_rest_server_busy_timeout = (
            hbsd_rest_api._REST_SERVER_BUSY_TIMEOUT)
        self.configuration.nec_v_rest_keep_session_loop_interval = (
            hbsd_rest_api._KEEP_SESSION_LOOP_INTERVAL)
        self.configuration.nec_v_rest_another_ldev_mapped_retry_timeout = (
            hbsd_rest_api._ANOTHER_LDEV_MAPPED_RETRY_TIMEOUT)
        self.configuration.nec_v_rest_tcp_keepidle = (
            hbsd_rest_api._TCP_KEEPIDLE)
        self.configuration.nec_v_rest_tcp_keepintvl = (
            hbsd_rest_api._TCP_KEEPINTVL)
        self.configuration.nec_v_rest_tcp_keepcnt = (
            hbsd_rest_api._TCP_KEEPCNT)
        self.configuration.nec_v_host_mode_options = []

        self.configuration.nec_v_zoning_request = False

        self.configuration.san_thin_provision = True
        self.configuration.san_private_key = ''
        self.configuration.san_clustername = ''
        self.configuration.san_ssh_port = '22'
        self.configuration.san_is_local = False
        self.configuration.ssh_conn_timeout = '30'
        self.configuration.ssh_min_pool_conn = '1'
        self.configuration.ssh_max_pool_conn = '5'

        self.configuration.use_chap_auth = True
        self.configuration.chap_username = CONFIG_MAP['auth_user']
        self.configuration.chap_password = CONFIG_MAP['auth_password']

        self.configuration.safe_get = self._fake_safe_get

        CONF = cfg.CONF
        CONF.my_ip = CONFIG_MAP['my_ip']

    def _fake_safe_get(self, value):
        """Retrieve a configuration value avoiding throwing an exception."""
        try:
            val = getattr(self.configuration, value)
        except AttributeError:
            val = None
        return val

    @mock.patch.object(requests.Session, "request")
    @mock.patch.object(
        volume_utils, 'brick_get_connector_properties',
        side_effect=_brick_get_connector_properties)
    def _setup_driver(
            self, brick_get_connector_properties=None, request=None):
        """Set up the driver environment."""
        self.driver = nec_v_fc.VStorageFCDriver(
            configuration=self.configuration, db=db)
        request.side_effect = [FakeResponse(200, POST_SESSIONS_RESULT),
                               FakeResponse(200, GET_PORTS_RESULT),
                               FakeResponse(200, GET_HOST_WWNS_RESULT)]
        self.driver.do_setup(None)
        self.driver.check_for_setup_error()
        self.driver.local_path(None)
        # stop the Loopingcall within the do_setup treatment
        self.driver.common.client.keep_session_loop.stop()

    def tearDown(self):
        self.client = None
        super(VStorageRESTFCDriverTest, self).tearDown()

    # API test cases
    def test_configuration(self):
        drv = nec_v_fc.VStorageFCDriver(
            configuration=self.configuration, db=db)
        self.assertEqual(drv.configuration.hitachi_storage_id,
                         drv.configuration.nec_v_storage_id)
        self.assertEqual(drv.configuration.hitachi_pool,
                         drv.configuration.nec_v_pool)
        self.assertEqual(drv.configuration.hitachi_snap_pool,
                         drv.configuration.nec_v_snap_pool)
        self.assertEqual(drv.configuration.hitachi_ldev_range,
                         drv.configuration.nec_v_ldev_range)
        self.assertEqual(drv.configuration.hitachi_target_ports,
                         drv.configuration.nec_v_target_ports)
        self.assertEqual(drv.configuration.hitachi_compute_target_ports,
                         drv.configuration.nec_v_compute_target_ports)
        self.assertEqual(drv.configuration.hitachi_group_create,
                         drv.configuration.nec_v_group_create)
        self.assertEqual(drv.configuration.hitachi_group_delete,
                         drv.configuration.nec_v_group_delete)
        self.assertEqual(drv.configuration.hitachi_copy_speed,
                         drv.configuration.nec_v_copy_speed)
        self.assertEqual(drv.configuration.hitachi_copy_check_interval,
                         drv.configuration.nec_v_copy_check_interval)
        self.assertEqual(drv.configuration.hitachi_async_copy_check_interval,
                         drv.configuration.nec_v_async_copy_check_interval)
        self.assertEqual(drv.configuration.hitachi_rest_disable_io_wait,
                         drv.configuration.nec_v_rest_disable_io_wait)
        self.assertEqual(drv.configuration.hitachi_rest_tcp_keepalive,
                         drv.configuration.nec_v_rest_tcp_keepalive)
        self.assertEqual(drv.configuration.hitachi_discard_zero_page,
                         drv.configuration.nec_v_discard_zero_page)
        self.assertEqual(drv.configuration.hitachi_lun_timeout,
                         drv.configuration.nec_v_lun_timeout)
        self.assertEqual(drv.configuration.hitachi_lun_retry_interval,
                         drv.configuration.nec_v_lun_retry_interval)
        self.assertEqual(drv.configuration.hitachi_restore_timeout,
                         drv.configuration.nec_v_restore_timeout)
        self.assertEqual(drv.configuration.hitachi_state_transition_timeout,
                         drv.configuration.nec_v_state_transition_timeout)
        self.assertEqual(drv.configuration.hitachi_lock_timeout,
                         drv.configuration.nec_v_lock_timeout)
        self.assertEqual(drv.configuration.hitachi_rest_timeout,
                         drv.configuration.nec_v_rest_timeout)
        self.assertEqual(drv.configuration.hitachi_extend_timeout,
                         drv.configuration.nec_v_extend_timeout)
        self.assertEqual(drv.configuration.hitachi_exec_retry_interval,
                         drv.configuration.nec_v_exec_retry_interval)
        self.assertEqual(drv.configuration.hitachi_rest_connect_timeout,
                         drv.configuration.nec_v_rest_connect_timeout)
        self.assertEqual(
            drv.configuration.hitachi_rest_job_api_response_timeout,
            drv.configuration.nec_v_rest_job_api_response_timeout)
        self.assertEqual(
            drv.configuration.hitachi_rest_get_api_response_timeout,
            drv.configuration.nec_v_rest_get_api_response_timeout)
        self.assertEqual(drv.configuration.hitachi_rest_server_busy_timeout,
                         drv.configuration.nec_v_rest_server_busy_timeout)
        self.assertEqual(
            drv.configuration.hitachi_rest_keep_session_loop_interval,
            drv.configuration.nec_v_rest_keep_session_loop_interval)
        self.assertEqual(
            drv.configuration.hitachi_rest_another_ldev_mapped_retry_timeout,
            drv.configuration.nec_v_rest_another_ldev_mapped_retry_timeout)
        self.assertEqual(drv.configuration.hitachi_rest_tcp_keepidle,
                         drv.configuration.nec_v_rest_tcp_keepidle)
        self.assertEqual(drv.configuration.hitachi_rest_tcp_keepintvl,
                         drv.configuration.nec_v_rest_tcp_keepintvl)
        self.assertEqual(drv.configuration.hitachi_rest_tcp_keepcnt,
                         drv.configuration.nec_v_rest_tcp_keepcnt)
        self.assertEqual(drv.configuration.hitachi_host_mode_options,
                         drv.configuration.nec_v_host_mode_options)
        self.assertEqual(drv.configuration.hitachi_zoning_request,
                         drv.configuration.nec_v_zoning_request)

    def test_driverinfo(self):
        drv = nec_v_fc.VStorageFCDriver(
            configuration=self.configuration, db=db)
        self.assertEqual(drv.common.driver_info['version'],
                         "1.0.0")
        self.assertEqual(drv.common.driver_info['proto'],
                         "FC")
        self.assertEqual(drv.common.driver_info['hba_id'],
                         "wwpns")
        self.assertEqual(drv.common.driver_info['hba_id_type'],
                         "World Wide Name")
        self.assertEqual(drv.common.driver_info['msg_id']['target'].msg_id,
                         308)
        self.assertEqual(drv.common.driver_info['volume_backend_name'],
                         "NECFC")
        self.assertEqual(drv.common.driver_info['volume_type'],
                         "fibre_channel")
        self.assertEqual(drv.common.driver_info['param_prefix'],
                         "nec_v")
        self.assertEqual(drv.common.driver_info['vendor_name'],
                         "NEC")
        self.assertEqual(drv.common.driver_info['driver_prefix'],
                         "NEC")
        self.assertEqual(drv.common.driver_info['driver_file_prefix'],
                         "nec")
        self.assertEqual(drv.common.driver_info['target_prefix'],
                         "NEC-")
        self.assertEqual(drv.common.driver_info['hdp_vol_attr'],
                         "DP")
        self.assertEqual(drv.common.driver_info['hdt_vol_attr'],
                         "DT")
        self.assertEqual(drv.common.driver_info['nvol_ldev_type'],
                         "DP-VOL")
        self.assertEqual(drv.common.driver_info['target_iqn_suffix'],
                         ".nec-target")
        self.assertEqual(drv.common.driver_info['pair_attr'],
                         "SS")

    @mock.patch.object(requests.Session, "request")
    def test_create_volume(self, request):
        request.return_value = FakeResponse(202, COMPLETED_SUCCEEDED_RESULT)
        ret = self.driver.create_volume(fake_volume.fake_volume_obj(self.ctxt))
        self.assertEqual('1', ret['provider_location'])
        self.assertEqual(2, request.call_count)


text:
CKEDITOR.plugins.setLang( 'removeformat', 'sq', {
	toolbar: 'Largo Formatin'
} );


text:
/**
 * @file stock.h
 *
 * Functions for manipulating stock and order structs.
 */

#ifndef STOCK_H_
#define STOCK_H_

#include "list.h"
#include "pool.h"

#define HASH_TABLE_NUM_BUCKETS 251
#define STOCK_NAME_MAX_LEN 4

enum order_type {
    BUY,
    SELL
};

typedef LIST_OF(struct order) order_list_t;
typedef LIST_OF(struct stock) stock_list_t;

struct stock;

// Type confusion
#ifdef PATCHED
enum object_type {
    ORDER,
    STOCK
};
#endif

struct order {
// Type confusion
#ifdef PATCHED
    enum object_type obj_type;
#else
    int dummy;
#endif
    void (*on_complete)(struct order *order);
    unsigned int id, price, quantity;
    LIST_ELEMS(struct order) global_list, stock_list;
    enum order_type type;
    struct stock *stock;
};

struct stock {
// Type confusion
#ifdef PATCHED
    enum object_type obj_type;
#else
    int dummy;
#endif
    char name[STOCK_NAME_MAX_LEN];
    unsigned int num_orders;
    LIST_ELEMS(struct stock) bucket_list, global_list;
    order_list_t buy_orders, sell_orders;
};

struct stock_state {
// Use after free
#ifdef PATCHED
    int stock_freed;
#endif
    struct pool stock_pool;
    stock_list_t stocks_list;
    order_list_t orders_list;
    stock_list_t stock_hash_table[HASH_TABLE_NUM_BUCKETS];
};

/**
 * Initialize a stock state struct.
 *
 * @param state The stock state struct
 */
void stock_init(struct stock_state *state);

/**
 * Destroy a stock state struct.
 *
 * @param state The stock state struct
 */
void stock_destroy(struct stock_state *state);

/**
 * Process a command to list all stocks, printing to stdout.
 *
 * @param state The stock state struct
 * @return 0 on success, -1 on failure
 */
int cmd_list_stocks(struct stock_state *state);

/**
 * Process a command to list all orders for a stock, printing to stdout.
 *
 * @param state The stock state struct
 * @param name The name of the stock to examine
 * @return 0 on success, -1 on failure
 */
int cmd_list_orders(const struct stock_state *state, const char *name);

/**
 * Process a command to place an order
 *
 * @param state The stock state struct
 * @param name The name of the stock to place an order for
 * @param type The type of the order (zero for buy, non-zero for sell)
 * @param quantity The quantity to order
 * @param price The price for each unit of the order
 * @return id of new order on success, -1 on failure
 */
int cmd_place_order(struct stock_state *state, const char *name, int type,
        unsigned int quantity, unsigned int price);

/**
 * Process a command to check the status of an order, printing to stdout.
 *
 * @param state The stock state struct
 * @param id The id of the order
 * @return 0 on success, -1 on failure
 */
int cmd_check_order(const struct stock_state *state, unsigned int id);

/**
 * Process a command to cancel an order.
 *
 * @param state The stock state struct
 * @param id The id of the order
 * @return 0 on success, -1 on failure
 */
int cmd_cancel_order(struct stock_state *state, unsigned int id);

#endif /* STOCK_H_ */


text:
{{group.title}}

                        <input type="checkbox" id="cbstyle{{style.id}}" ng-model="style.enabled" data-ng-change="vm.$layerService.updateStyle(style);">
                        {{style.title}}

                                        {{key}}

                                             {{title}}

                                        Verwijder

{{style.activeLegend.description}}

{{le.label}}

{{style.activeLegend.description}}

                                    <div ng-if="key < style.activeLegend.legendEntries.length-1"
                                        class="legend-color-gradient-rect"
                                        style="float: left; position: relative; top: 10px; background: linear-gradient(to bottom, {{le.color}}, {{style.activeLegend.legendEntries[style.activeLegend.legendEntries.length-key-2].color}}">

{{le.label}}


text:
BOOL acm_valid_encoding(NSStringEncoding enc) {
    BOOL isGood;

    switch ( enc ) {
        case NSASCIIStringEncoding             :
        case NSNEXTSTEPStringEncoding          :
        case NSJapaneseEUCStringEncoding       :
        case NSUTF8StringEncoding              :
        case NSISOLatin1StringEncoding         :
        case NSSymbolStringEncoding            :
        case NSNonLossyASCIIStringEncoding     :
        case NSShiftJISStringEncoding          :
        case NSISOLatin2StringEncoding         :
        case NSUnicodeStringEncoding           :
        case NSWindowsCP1251StringEncoding     :
        case NSWindowsCP1252StringEncoding     :
        case NSWindowsCP1253StringEncoding     :
        case NSWindowsCP1254StringEncoding     :
        case NSWindowsCP1250StringEncoding     :
        case NSISO2022JPStringEncoding         :
        case NSMacOSRomanStringEncoding        :
        case NSUTF16BigEndianStringEncoding    :
        case NSUTF16LittleEndianStringEncoding :
        case NSUTF32StringEncoding             :
        case NSUTF32BigEndianStringEncoding    :
        case NSUTF32LittleEndianStringEncoding : isGood = TRUE;
            break;
        default : isGood = FALSE;
            break;
    }

    return isGood;
}


text:
# Authentication

You can read a quickstart guide for this sample [here](https://auth0.com/docs/quickstart/backend/webapi-owin/01-authorization).

## Running the example

In order to run the example you need to just start a server. What we suggest is doing the following:

1. Make sure `web.config` contains your credentials. You can find your credentials in the settings section of your Auth0 Client.
2. Hit F5 to start local web development server.

Go to `http://localhost:58105/api/ping` and you'll see the app running :).


text:
package manager

import (
	ds "github.com/Comcast/traffic_control/traffic_monitor/experimental/traffic_monitor/deliveryservice"
	"sync"
)

type StatsLastKbpsThreadsafe struct {
	stats *ds.StatsLastKbps
	m     *sync.RWMutex
}

func NewStatsLastKbpsThreadsafe() StatsLastKbpsThreadsafe {
	s := ds.NewStatsLastKbps()
	return StatsLastKbpsThreadsafe{m: &sync.RWMutex{}, stats: &s}
}

func (o *StatsLastKbpsThreadsafe) Get() ds.StatsLastKbps {
	o.m.RLock()
	defer o.m.RUnlock()
	return o.stats.Copy()
}

func (o *StatsLastKbpsThreadsafe) Set(s ds.StatsLastKbps) {
	o.m.Lock()
	*o.stats = s // TODO copy?
	o.m.Unlock()
}