text:
package org.jboss.pnc.integration;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.pnc.AbstractTest;
import org.jboss.pnc.integration.client.AbstractRestClient;
import org.jboss.pnc.integration.client.BuildRestClient;
import org.jboss.pnc.integration.client.util.RestResponse;
import org.jboss.pnc.integration.deployments.Deployments;
import org.jboss.pnc.integration.env.IntegrationTestEnv;
import org.jboss.pnc.integration.utils.AuthUtils;
import org.jboss.pnc.mock.coordinator.BuildCoordinatorMock;
import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.BuildConfigurationAudited;
import org.jboss.pnc.model.IdRev;
import org.jboss.pnc.model.User;
import org.jboss.pnc.rest.provider.BuildRecordProvider;
import org.jboss.pnc.rest.restmodel.BuildRecordRest;
import org.jboss.pnc.spi.coordinator.BuildTask;
import org.jboss.pnc.spi.datastore.repositories.BuildRecordRepository;
import org.jboss.pnc.test.category.ContainerTest;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.beans10.BeansDescriptor;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import java.lang.invoke.MethodHandles;
import java.util.List;
import java.util.stream.Collectors;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

@SuppressWarnings("ALL")
@RunWith(Arquillian.class)
@Category(ContainerTest.class)
public class BuildsRestTest  {

    public static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    private static BuildRestClient buildRestClient;

    @Inject
    private BuildRecordRepository buildRecordRepository;

    @Inject
    private BuildRecordProvider buildRecordProvider;

    @Inject
    BuildCoordinatorMock buildCoordinatorMock;

    @Deployment
    public static EnterpriseArchive deploy() {
        EnterpriseArchive enterpriseArchive = Deployments.baseEarWithTestDependencies();
        WebArchive war = enterpriseArchive.getAsType(WebArchive.class, AbstractTest.REST_WAR_PATH);
        war.addAsWebInfResource(new StringAsset(
                Descriptors.create(BeansDescriptor.class).
                        getOrCreateAlternatives().
                        clazz(BuildCoordinatorMock.class.
                                getName()).up().exportAsString()), "beans.xml");
        war.addClass(BuildsRestTest.class);
        war.addClass(BuildCoordinatorMock.class);
        addRestClientClasses(war);
        logger.info(enterpriseArchive.toString(true));
        return enterpriseArchive;
    }

    protected static void addRestClientClasses(WebArchive war) {
        war.addClass(BuildRestClient.class);
        war.addClass(AbstractRestClient.class);
        war.addClass(AuthUtils.class);
        war.addClass(IntegrationTestEnv.class);
        war.addClass(RestResponse.class);
    }

    @Before
    public void before() {
        if(buildRestClient == null) {
            buildRestClient = new BuildRestClient();
        }
        buildCoordinatorMock.clearActiveTasks();
    }

    @Test
    @InSequence(-1)
    public void sanityTests() throws Exception {
        assertThat(buildRecordProvider.getAll(0, 99, "", "").getContent())
                .hasSize(2)
                .overridingErrorMessage("2 BuildRecords are expected in DB before running this test");

        assertThat(buildCoordinatorMock).isNotNull();
    }

    @Test
    public void shouldGetAllArchivedBuildRecords() throws Exception {
        //given
        buildCoordinatorMock.addActiveTask(mockBuildTask());
        buildCoordinatorMock.addActiveTask(mockBuildTask());

        //when
        RestResponse<List<BuildRecordRest>> all = buildRestClient.all();

        //then
        assertThat(all.getValue()).hasSize(4);
    }

    @Test
    public void shouldSortResults() throws Exception {
        //given
        String sort = "=desc=id";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        //when
        List<Integer> sorted = buildRestClient.all(true, 0, 50, null, sort).getValue().stream()
                .map(value -> value.getId())
                .collect(Collectors.toList());

        //then
        assertThat(sorted).containsExactly(99, 2, 1);

    }

    @Test
    public void shouldFilterResults() throws Exception {
        //given
        String rsql = "id==1";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        //when
        List<Integer> sorted = buildRestClient.all(true, 0, 50, rsql, null).getValue().stream()
                .map(value -> value.getId())
                .collect(Collectors.toList());

        //then
        assertThat(sorted).containsExactly(1);
    }

    @Test
    public void shouldSupportPaging() throws Exception {
        //given
        String sort = "=desc=id";

        buildCoordinatorMock.addActiveTask(mockBuildTask());

        //when
        List<BuildRecordRest> firstPage = buildRestClient.all(true, 0, 1, null, sort).getValue();
        List<BuildRecordRest> secondPage = buildRestClient.all(true, 1, 1, null, sort).getValue();
        List<BuildRecordRest> thirdPage = buildRestClient.all(true, 2, 1, null, sort).getValue();

        //then
        assertThat(firstPage).hasSize(1);
        assertThat(secondPage).hasSize(1);
        assertThat(thirdPage).hasSize(1);  // Added to ensure running and finished records interleave correctly.

    }

    @Test
    public void shouldBeAbleToReachAllBuildsWhenPaging() throws Exception {
        //given
        String sort = "=desc=id";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        //when
        List<BuildRecordRest> firstPage = buildRestClient.all(true, 0, 1, null, sort).getValue();
        List<BuildRecordRest> secondPage = buildRestClient.all(true, 1, 1, null, sort).getValue();
        List<BuildRecordRest> thirdPage = buildRestClient.all(true, 2, 1, null, sort).getValue();

        //then
        assertThat(firstPage.get(0).getId()).isEqualTo(99);
        assertThat(secondPage.get(0).getId()).isEqualTo(2);
        assertThat(thirdPage.get(0).getId()).isEqualTo(1);
    }

    @Test
    public void shouldReturnCorrectPageCount() throws Exception {
        // Given
        String sort = "=desc=id";

        buildCoordinatorMock.addActiveTask(mockBuildTask());

        // When
        int totalPages = buildRestClient.all(true, 0, 1, null, sort).getRestCallResponse().getBody().jsonPath().getInt("totalPages");

        //then
        assertThat(totalPages).isEqualTo(3);
    }

    @Test
    public void shouldFilterByUserId() throws Exception {
        // given
        String rsql = "user.id==1";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        // when
        List<Integer> sorted = buildRestClient.all(true, 0, 50, rsql, null).getValue().stream().map(value -> value.getId())
                .collect(Collectors.toList());

        // then
        assertThat(sorted).containsExactly(1, 2);
    }

    @Test
    public void shouldFilterByUsername() throws Exception {
        // given
        String rsql = "user.username==demo-user";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        // when
        List<Integer> sorted = buildRestClient.all(true, 0, 50, rsql, null).getValue().stream().map(value -> value.getId())
                .collect(Collectors.toList());

        // then
        assertThat(sorted).containsExactly(1, 2);
    }

    @Test
    public void shouldFilterByBuildConfigurationId() throws Exception {
        // given
        String rsql = "buildConfigurationAudited.idRev.id==1";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        // when
        List<Integer> sorted = buildRestClient.all(true, 0, 50, rsql, null).getValue().stream().map(value -> value.getId())
                .collect(Collectors.toList());

        // then
        assertThat(sorted).containsExactly(1);
    }

    @Test
    public void shouldFilterByBuildConfigurationName() throws Exception {
        // given
        String rsql = "buildConfigurationAudited.name==jboss-modules-1.5.0";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        // when
        List<Integer> sorted = buildRestClient.all(true, 0, 50, rsql, null).getValue().stream().map(value -> value.getId())
                .collect(Collectors.toList());

        // then
        assertThat(sorted).containsExactly(2);
    }

    @Test
    public void shouldFilterByNotExistingBuildConfigurationName() throws Exception {
        // given
        String rsql = "buildConfigurationAudited.name==jboss-modules-1.5.1";

        BuildTask mockedTask = mockBuildTask();
        buildCoordinatorMock.addActiveTask(mockedTask);

        // when
        List<Integer> sorted = buildRestClient.all(true, 0, 50, rsql, null).getValue().stream().map(value -> value.getId())
                .collect(Collectors.toList());

        // then
        assertThat(sorted).isEmpty();
    }

    protected BuildTask mockBuildTask() {
        BuildTask mockedTask = mock(BuildTask.class);
        doReturn(99).when(mockedTask).getId();
        doReturn(mock(User.class)).when(mockedTask).getUser();
        doReturn(mock(BuildConfiguration.class)).when(mockedTask).getBuildConfiguration();
        doReturn(mock(BuildConfigurationAudited.class)).when(mockedTask).getBuildConfigurationAudited();
        when(mockedTask.getBuildConfigurationAudited().getIdRev()).thenReturn(mock(IdRev.class));
        when(mockedTask.getBuildConfigurationAudited().getIdRev().getId()).thenReturn(99);
        when(mockedTask.getUser().getId()).thenReturn(99);
        when(mockedTask.getUser().getUsername()).thenReturn("test-username");
        return mockedTask;
    }
}


text:
package io.crnk.operations.server;

import io.crnk.core.engine.query.QueryContext;
import io.crnk.core.module.discovery.ServiceDiscovery;
import io.crnk.operations.server.order.OrderedOperation;

import java.util.List;

public interface OperationFilterContext {

    List<OrderedOperation> getOrderedOperations();

    ServiceDiscovery getServiceDiscovery();

    QueryContext getQueryContext();
}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/kgiusti/pyngus.svg)](https://travis-ci.org/kgiusti/pyngus)

A messaging framework built on the QPID Proton engine.  It provides a
callback-based API for message passing.

See the User Guide in the docs directory for more detail.

## Release 2.2.3 ##

* bumped max proton version to 0.20

## Release 2.2.2 ##

* verified Python 3.6 compatibility
* bumped max proton version to 0.19

## Release 2.2.1 ##

* disable the socket I/O logging - fills the debug logs with lots of
  useless crap.

## Release 2.2.0 ##

* Can now use the system's default CA by specifying the 'x-ssl' option
  in the 'properties' field of the create_connection call and _NOT_
  specifying the 'x-ssl-ca-file' property. (contributed by
  Juan Antonio Osorio Robles)
* use the most secure default setting for x-ssl-verify-mode based on
  the configuration
* bump max proton version to 0.17

## Release 2.1.4 ##

* avoid using deprecated next_tick in the container
* enable Python 3.5 testing in tox
* add client authentication via SSL tests
* bump max proton version to 0.16

## Release 2.1.3 ##

* Remove chatty debug log messages
* fix pep8 violation
* add static performace test tool
* Bump max proton version to 0.15

## Release 2.1.2 ##

* Bump max proton version to 0.14

## Release 2.1.1 ##

* bugfix: under some (rare) flow/credit interactions a sender may
  stall.  Changed code to invoke credit_granted() callback more
  frequently.

## Release 2.1.0 ##

* feature: add 'x-force-sasl' to connection property map
* bugfix: update old SASL unit test

## Release 2.0.4 ##

* Bump max proton version to 0.13
* performance tweak to link event handling
* fix perf-test.py tool
* bugfix: fix leak of timer callbacks
* enable Python 3.4 testing
* bugfix: fix receiver example (recv.py)
* several fixes to the SASL unit tests
* bugfix: fix leak of underlying proton objects
* Add SASL/SSL configuration options to examples
* bugfix: allow PLAIN or ANONYMOUS authentication in server mode

## Release 2.0.3 ##

* bugfix: fixed a memory leak
* bugfix: cyrus test fixed

## Release 2.0.0 ##

* Support for proton 0.10
* The SASL API has changed due to an API change in proton 0.10
  * Proton 0.10 implements SASL via the Cyrus SASL library
    * this change allows use of more secure authentication mechanisms, such as Kerberos
  * Applications should no longer directly access the Proton SASL class via the Connection.pn\_sasl property
    * instead, the following new properties may be passed to the Container.create\_connection() method:
      * x-username - (client only) the authentication id
      * x-password - (client only) the authentication password
      * x-require-auth - (server only) reject clients that do not use authentication
      * x-sasl-mechs - (server only) whitespace delimited string of
        acceptable mechanisms.  If not supplied the mechanisms
        specified in the system's SASL configuration will be used.
        This option should only be used when the application wants to
        further restrict the set of acceptable mechanisms.
      * x-sasl-config-dir - (server only) the location of the
        _directory_ that holds the system's Cyrus SASL configuration.
      * x-sasl-config-name - (server only) the name of the SASL
        configuration file (*without* the ".conf" suffix) in the
        x-sasl-dir directory.
      * *NOTE WELL*: Cyrus SASL cannot support multiple different SASL
        configurations per connection.  The values of
        x-sasl-config-dir and x-sasl-config-name *MUST* be the same
        for all connections that use SASL.
  * the ConnectionEventHandler.sasl\_step() callback has been deprecated as proton 0.10 no longer uses it
    * The ConnectionEventHandler.sasl\_done() callback *is* still supported.
* Pyngus now enforces strict reentrancy checking.  Attempting to call
  a non-reentrant Pyngus method will now throw a RuntimeError exception.

## Release 1.3.0 ##

* Support for proton 0.9
* Installation of proton dependencies via setup.py.  This feature was
  added by Flavio Percoco Premoli <flaper87@gmail.com> - thanks
  Flavio!


text:
module.exports = {
	run: function () {
		var test = {},
			nextRun = {};

		tests.findAll ({where: {nextRun: {$lt: Date.now ()}}}).then (function (scheduledTests) {
			for (i in scheduledTests) {
				test = scheduledTests[i];

				// add test to queue for running
				// we need to run this task for each test, do not move it!
				// this limit is because of selecting headers from environment and project
				testRunner.addToQueue ({id: test.id}, console.error);

				// and setup next time (or set NULL when should run only once)
				nextRun = test.runInterval ? new Date (Date.now () + test.runInterval * 60 * 1000) : null;

				test.update ({nextRun: nextRun}).then (function (updated) {
					console.log ('Scheduled test #' + test.id + ' for ' + updated.nextRun)
				});
			}
		})
	}
};


text:
						Username
						School
						Email
						Role
						Memebership

								{{gridItem.username}}

								{{gridItem.school.code}}

								{{gridItem.membership | date:'dd/MM/yyyy'}}

							<form class="form-inline tr-ng-grid-footer" grid="">

							</form>


text:
<!doctype html>

{% load compress cms_tags menu_tags sekizai_tags static %}

        {% language_chooser 'menu/hreflang.html' %}
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        {# <meta http-equiv="x-ua-compatible" content="ie=edge"> #}
        {# http://patorjk.com/software/taag/ #}

        <title>{% block title_tag %}{% endblock %}</title>
        <meta name="description" content="{% block meta_description %}{% endblock %}">
        {% include '{{ project_name }}/partials/favicon.html' %}

        <meta content="{% block facebook_url %}{% endblock %}" property="og:url"/>
        <meta content="{% block facebook_title %}{% endblock %}" property="og:title"/>
        <meta content="{% block facebook_description %}{% endblock %}" property="og:description"/>
        <meta content="{% block facebook_image %}{% endblock %}" property="og:image"/>

        {% compress js inline %}

        {% endcompress %}

        {% compress css inline %}
{#            thiw would go through sass/js/webpack #}
{#            <link rel="stylesheet" href="{% static '{{ project_name }}/libs/normalize-css/normalize.css' %}"> #}
{#            OLD STYLE #}
{#            <link rel="stylesheet" href="{% static '{{ project_name }}/css/screen.css' %}">#}
{#            check: https://pascalw.me/blog/2020/04/19/webpack-django.html  #}
            <link rel="stylesheet" href="{% static '{{ project_name }}/bundle/bundle.css' %}">
            <link rel="stylesheet" href="{% static 'djangocms_misc/css/cms_frontend_adjust.css' %}">
        {% endcompress %}
        {% comment %}
            if need...
        {% endcomment %}

        {% render_block "css" %}

        {% cms_toolbar %}

            {% block content %}

                    {% placeholder content %}

            {% endblock %}

                    ×

                            {% show_menu 0 2 2 2 %}

        {% compress js %}

        {% endcompress %}
{#        {% compress js %}#}
{#            #}
{#            #}
{#            #}
{#            #}
{#        {% endcompress %}#}

        {% if is_live and not request.user.is_staff and analytics_ua %}
            {% compress js inline %}

            {% endcompress %}
        {% endif %}

        {% render_block "js" %}


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_CRCCU_EXAMPLE_H_INCLUDED
#define CONF_CRCCU_EXAMPLE_H_INCLUDED

/// @cond 0
/**INDENT-OFF**/
#ifdef __cplusplus
extern "C" {
#endif
/**INDENT-ON**/
/// @endcond

#define FLASH_BUFFER_SIZE	IFLASH_PAGE_SIZE

/// @cond 0
/**INDENT-OFF**/
#ifdef __cplusplus
}
#endif
/**INDENT-ON**/
/// @endcond

#endif /* CONF_CRCCU_EXAMPLE_H_INCLUDED*/


text:
<?php

declare(strict_types=1);

namespace Gitter\Support;

use Psr\Http\Message\StreamInterface;
use Psr\Log\LoggerInterface;

/**
 * Class JsonStream
 * @package Gitter\Support
 */
class JsonStream
{
    /**
     * @var string[]
     */
    const JSON_STARTS_WITH = ['{', '['];

    /**
     * @var int
     */
    const BUFFER_MAX_SIZE = 2 ** 14;

    /**
     * @var string
     */
    private $bufferSize;

    /**
     * @var string
     */
    private $endsWith = ']';

    /**
     * @var string
     */
    private $buffer = '';

    /**
     * @var int
     */
    private $chunkSize = 1;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * JsonStream constructor.
     * @param int $bufferSize
     */
    public function __construct(int $bufferSize = self::BUFFER_MAX_SIZE)
    {
        $this->bufferSize = $bufferSize;
    }

    /**
     * @param LoggerInterface $logger
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws \OutOfBoundsException
     */
    private function checkSize()
    {
        if ($this->bufferSize > 0 && \strlen($this->buffer) > $this->bufferSize) {
            throw new \OutOfBoundsException(
                sprintf('Memory leak detected. Buffer size out of %s bytes', $this->bufferSize)
            );
        }
    }

    /**
     * @param string $data
     * @return bool
     */
    private function shouldStarts(string $data): bool
    {
        return $this->buffer === '' && \in_array($data[0], self::JSON_STARTS_WITH, true);;
    }

    /**
     * @param string $data
     * @param \Closure|null $callback
     * @return mixed|null
     */
    public function push(string $data, \Closure $callback = null)
    {
        // Buffer are empty and input starts with "[" or "{"
        $canBeBuffered = $this->shouldStarts($data);

        // Data can be starts buffering
        if ($canBeBuffered) {
            $this->endsWith = $data[0] === '[' ? ']' : '}';
        }

        // Add chunks for non empty buffer
        if ($canBeBuffered || $this->buffer !== '') {
            $this->buffer .= $data;

            if ($this->isEnds($data)) {
                $object = \json_decode($this->buffer, true);

                if (\json_last_error() === JSON_ERROR_NONE) {
                    $this->buffer = '';

                    if ($callback !== null) {
                        $callback($object);
                    }

                    return $object;
                }
            }
        }

        return null;
    }

    /**
     * @param string $text
     * @return bool
     */
    private function isEnds(string $text): bool
    {
        $text = \trim($text);

        return $text && $text[\strlen($text) - 1] === $this->endsWith;
    }

    /**
     * @param StreamInterface $stream
     * @return \Generator
     * @throws \OutOfBoundsException
     * @throws \RuntimeException
     */
    public function stream(StreamInterface $stream): \Generator
    {
        while (!$stream->eof()) {
            $data = $stream->read($this->chunkSize);

            $output = $this->push($data);
            if ($output !== null) {
                yield $output;
            }

            $this->checkSize();
        }
    }
}


text:
<?php
class Stock_IndexController extends Zend_Controller_Action {
	protected $tr;
	public function init()
    {
    	header('content-type: text/html; charset=utf8');
    	defined('BASE_URL')	|| define('BASE_URL', Zend_Controller_Front::getInstance()->getBaseUrl());
    	$this->tr=Application_Form_FrmLanguages::getCurrentlanguage();
	}
	public function indexAction(){
		$this->_redirect("stock/product");
	}
}


text:
package main

import (
	"fmt"
	"sync"

	"github.com/schollz/jsonstore"
)

func main() {
	ks := new(jsonstore.JSONStore)

	// set a key to any object you want
	type Human struct {
		Name   string
		Height float64
	}
	err := ks.Set("human:1", Human{"Dante", 5.4})
	if err != nil {
		panic(err)
	}

	// Saving will automatically gzip if .gz is provided,
	// and can be performed in a wait group
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		if err = jsonstore.Save(ks, "test.json.gz"); err != nil {
			panic(err)
		}
	}()
	wg.Wait()

	// Load any JSON / GZipped JSON
	ks2, err := jsonstore.Open("test.json.gz")
	if err != nil {
		panic(err)
	}

	// get the data back via an interface
	var human Human
	err = ks2.Get("human:1", &human)
	if err != nil {
		panic(err)
	}
	fmt.Println(human.Name)
}


text:
```
npm i -D eslint@latest
./tools/what_news
```

## Find Rules

`./tools/find_rule <rule_name>`


text:
package org.consumersunion.stories.login.application;

import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;

public class ApplicationPresenter extends Presenter<ApplicationPresenter.MyView, ApplicationPresenter.MyProxy> {
    interface MyView extends View {
    }

    @ProxyStandard
    interface MyProxy extends Proxy<ApplicationPresenter> {
    }

    @ContentSlot
    public static final Type<RevealContentHandler<?>> SLOT_MAIN_CONTENT = new Type<RevealContentHandler<?>>();

    @Inject
    ApplicationPresenter(
            EventBus eventBus,
            MyView view,
            MyProxy proxy) {
        super(eventBus, view, proxy, RevealType.Root);
    }
}


text:
/**
	A popup is used to display content that should be displayed on top of other
	content.

	Popups are initially hidden on creation; they can be shown by calling the
	_show_ method and re-hidden by calling _hide_.  Popups may be centered using
	the	_centered_ property; if not centered, they should be given a specific
	position.

	A popup may be optionally floated above all application content by setting
	its _floating_ property to true.  This has the advantage of guaranteeing
	that the popup will be displayed on top of other content.  This usage is
	appropriate when the popup does not need to scroll with other content.

	The _autoDismiss_ property controls how a popup may be dismissed.  If true
	(the default), then tapping outside the popup or pressing the ESC key will
	dismiss the popup.

	The _modal_ property may be set to true to prevent any
	controls outside the popup from responding to events while the popup is
	showing.

		{kind: "enyo.Popup", centered: true, modal: true, floating: true, components: [
			{content: "Here's some information..."}
		]}
 */
enyo.kind({
	name: "enyo.Popup",
	classes: "enyo-popup",
	published: {
		//* Set to true to prevent controls outside the popup from receiving events while the popup is showing.
		modal: false,
		//* By default, the popup will hide when the user taps outside it or presses ESC.  Set to false to prevent this behavior.
		autoDismiss: true,
		//* If true, the popup will be rendered in a floating layer outside of other controls.  This can be used to
		//* guarantee that the popup will be shown on top of other controls.
		floating: false,
		//* Set to true to automatically center the popup in the middle of the viewport.
		centered: false
	},
	//* @protected
	showing: false,
	handlers: {
		ondown: "down",
		onkeydown: "keydown",
		onfocus: "focus",
		onblur: "blur",
		onRequestShow: "requestShow",
		onRequestHide: "requestHide"
	},
	captureEvents: true,
	//* @public
	events: {
		//@ Event that fires after the popup is shown.
		onShow: "",
		//@ Event that fires after the popup is hidden.
		onHide: ""
	},
	//* @protected
	tools: [
		{kind: "Signals", onKeydown: "keydown"}
	],
	create: function() {
		this.inherited(arguments);
		if (this.floating) {
			this.setParent(enyo.floatingLayer);
		}
	},
	destroy: function() {
		if (this.showing) {
			this.release();
		}
		this.inherited(arguments);
	},
	// bubble events to owner when floating
	getBubbleTarget: function() {
		return this.floating ? this.owner : this.inherited(arguments);
	},
	reflow: function() {
		this.updatePosition();
		this.inherited(arguments);
	},
	calcViewportSize: function() {
		if (window.innerWidth) {
			return {
				width: window.innerWidth,
				height: window.innerHeight
			};
		} else {
			var e = document.documentElement;
			return {
				width: e.offsetWidth,
				height: e.offsetHeight
			};
		}
	},
	updatePosition: function() {
		if( this.centered ) {
			var d = this.calcViewportSize();
			var b = this.getBounds();

			this.addStyles( "top: " + Math.max( ( ( d.height - b.height ) / 2 ), 0 ) + "px; left: " + Math.max( ( ( d.width - b.width ) / 2 ), 0 ) + "px;" );
		}
	},
	showingChanged: function() {
		// auto render when shown.
		if (this.floating && this.showing && !this.hasNode()) {
			this.render();
		}
		// hide while sizing
		if (this.centered) {
			this.applyStyle("visibility", "hidden");
		}
		this.inherited(arguments);
		if (this.showing) {
			this.resized();
			if (this.captureEvents) {
				this.capture();
			}
		} else {
			if (this.captureEvents) {
				this.release();
			}
		}
		// show after sizing
		if (this.centered) {
			this.applyStyle("visibility", null);
		}
		// events desired due to programmatic show/hide
		if (this.hasNode()) {
			this[this.showing ? "doShow" : "doHide"]();
		}
	},
	capture: function() {
		enyo.dispatcher.capture(this, !this.modal);
	},
	release: function() {
		enyo.dispatcher.release();
	},
	down: function(inSender, inEvent) {
		// prevent focus from shifting outside the popup when modal.
		if (this.modal && !inEvent.dispatchTarget.isDescendantOf(this)) {
			inEvent.preventDefault();
		}
	},
	tap: function(inSender, inEvent) {
		// dismiss on tap if property is set and click was outside the popup
		if (this.autoDismiss && (!inEvent.dispatchTarget.isDescendantOf(this))) {
			this.hide();
			return true;
		}
	},
	keydown: function(inSender, inEvent) {
		if (this.showing && this.autoDismiss && inEvent.keyCode == 27 /* escape */) {
			this.hide();
		}
	},
	// if something inside the popup blurred, keep track of it
	blur: function(inSender, inEvent) {
		if (inEvent.dispatchTarget.isDescendantOf(this)) {
			this.lastFocus = inEvent.originator;
		}
	},
	// when something outside the popup focuses (e.g., due to tab key), focus our last focused control.
	focus: function(inSender, inEvent) {
		var dt = inEvent.dispatchTarget;
		if (this.modal && !dt.isDescendantOf(this)) {
			if (dt.hasNode()) {
				dt.node.blur();
			}
			var n = (this.lastFocus && this.lastFocus.hasNode()) || this.hasNode();
			if (n) {
				n.focus();
			}
		}
	},
	requestShow: function(inSender, inEvent) {
		this.show();
		return true;
	},
	requestHide: function(inSender, inEvent) {
		this.hide();
		return true;
	}
});


text:
void ofApp::setup(){
    ofBackground(0, 0, 0);
    ofSetVerticalSync(false);
    radiusCore = 25;
    radiusPtl = 25;

    coreStart.set(ofGetWidth()/2, ofGetHeight()/2,0);//set the core start at the center of the screen
//    floatingPtlPos.x = ;

//    if (<#condition#>) {
//        <#statements#>
//    }
//    sideNum = int(ofRandom(4));

    org.set(ofGetWidth()/2, ofGetHeight()/2, 0);
//    floatingPtlPos.set(ofRandom(0,ofGetWidth()),ofRandom(0, ofGetHeight()), 0);
    float degreeRad = ofRandom(2*PI);

    floatingPtlPos.set(400*sin(degreeRad)+ofGetWidth()/2, 400*cos(degreeRad)+ofGetHeight()/2);
//    VecSpeed.x = ofRandom(0, 20);
//    VecSpeed.y = ofRandom(0, 20);
//    VecSpeed.set(VecSpeed.x, VecSpeed.y,0);
//    VecSpeed = floatingPtlPos - org;
    VecSpeed = floatingPtlPos - org;
    VecSpeed.normalize();
    VecSpeed = ofRandom(10,20)*VecSpeed;

    particlesagged.push_back(coreStart);

    keyAnimate = true;

}

//--------------------------------------------------------------
void ofApp::update(){
//    coreStart.x +=ofGetElapsedTimef();
  //  cout << "a=" << ofGetElapsedTimef() << endl;
//
//    ofCircle(coreStart.x + ofGetElapsedTimef(), coreStart.y, 110);
//    floatingPtlPos.x += floatingPtlPos.x + VecSpeed.x;
//    floatingPtlPos.y += floatingPtlPos.y + VecSpeed.y;
    cout << "floatingPtPos:" << floatingPtlPos << endl;
    cout << "VecSpeed:" << VecSpeed << endl;
//    sideNum = ofRandom(1,5);
//    cout << "sideNum" << sideNum <<endl;
    org.set(ofGetWidth()/2, ofGetHeight()/2, 0);

    if (keyAnimate) {
        floatingPtlPos = floatingPtlPos + 1*VecSpeed;
    }

        if (floatingPtlPos.x > ofGetWidth()  ) {
            VecSpeed.x *= -1;
            floatingPtlPos.x = ofGetWidth();
        }else if (floatingPtlPos.x < 0){
            VecSpeed.x *= -1;
            floatingPtlPos.x = 0;
        }

        if (floatingPtlPos.y > ofGetHeight()  ) {
            VecSpeed.y *= -1;
            floatingPtlPos.y = ofGetHeight();
        }else if (floatingPtlPos.y < 0){
            VecSpeed.y *= -1;
            floatingPtlPos.y = 0;
        }

        for (int i = 0; i <= particlesagged.size(); i++) {
            if (floatingPtlPos.distance(particlesagged[i]) <  radiusCore + radiusPtl) {

    //          particlesagged.set(floatingPtlPos);

                float disAct = floatingPtlPos.distance(particlesagged[i]);
                float disShould = radiusPtl + radiusCore;
                ofVec3f moveBack = floatingPtlPos[i]-particlesagged[i];
                moveBack.normalize();
                moveBack = moveBack * (disShould - disAct);
    //            moveBack = moveBack * disShould;
                floatingPtlPos = floatingPtlPos + moveBack;

                particlesagged.push_back(floatingPtlPos);
                floatingPtlPos.set(ofRandom(0,ofGetWidth()),ofRandom(0, ofGetHeight()), 0);
                float degreeRad = ofRandom(2*PI);

                floatingPtlPos.set(400*sin(degreeRad)+ofGetWidth()/2, 400*cos(degreeRad)+ofGetHeight()/2);
    //            VecSpeed.x = ofRandom(0, 20);
    //            VecSpeed.y = ofRandom(0, 20);
    //            VecSpeed.set(VecSpeed.x, VecSpeed.y,0);
                VecSpeed = -1*(floatingPtlPos - org);
                VecSpeed.normalize();
                VecSpeed = ofRandom(10,20)*VecSpeed;

                keyAnimate = false;

            }
        }

}

//--------------------------------------------------------------
void ofApp::draw(){
    //ofCircle(coreStart.x+ofGetElapsedTimef(), coreStart.y, 110);

//    ofCircle(coreStart.x+ofGetElapsedTimef(), coreStart.y, 110);
//    cout << "a=" << coreStart.x+ofGetElapsedTimef() << endl;
    ofColor ptlColor;
    ptlColor.set(134, 22, 60,190);
    ofSetColor(ptlColor);
    ofNoFill();
    ofCircle(coreStart.x, coreStart.y, 400);
    ofFill();
    ofCircle(coreStart.x, coreStart.y, radiusCore);

    ofCircle(floatingPtlPos.x, floatingPtlPos.y, 0, radiusPtl);
    if (particlesagged.size() >= 2) {
        for (int i = 0; i <= particlesagged.size(); i++) {
            ofCircle(particlesagged[i].x, particlesagged[i].y, radiusPtl);
        }
    }

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    if (key == 's') {
        keyAnimate = !keyAnimate;
    }
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}


text:
package com.lachesis.support.auth.context.util;

import javax.servlet.ServletRequest;

import com.lachesis.support.auth.context.common.AuthContextConstants;
import com.lachesis.support.objects.vo.SecurityContext;

public final class SecurityContextUtils {
	public static SecurityContext getSecurityContext(ServletRequest request){
		if(request == null){
			return null;
		}

		return (SecurityContext) request.getAttribute(AuthContextConstants.REQUEST_ATTR_SECURITY_CONTEXT);
	}

	public static void setSecurityContext(ServletRequest request, SecurityContext securityContext){
		if(request != null){
			request.setAttribute(AuthContextConstants.REQUEST_ATTR_SECURITY_CONTEXT, securityContext);
		}
	}

	private SecurityContextUtils(){}
}


text:
/**
 *
ClassName: java edu.wustl.geneconnect.metadata.domain.BaseTable

 */

package edu.wustl.geneconnect.metadata.domain;

/**
 * This class describes the base table which stores mapping Ids among 2 adjucent data sources
 * @author mahesh_nalkande
 * @version 1.0
 */
public class BaseTable
{

	/**
	 * Table Id
	 */
	private Long Id;
	/**
	 * Name of the base Table
	 */
	private String name;
	/**
	 * Id of source data source which is connected by this base table.
	 */
	private Long sourceDataSourceId;
	/**
	 * Id of Destination data source which is connected by this base table.
	 */
	private Long destinationDataSourceId;

	/**
	 * Default constructor
	 */
	public BaseTable()
	{
		super();
	}

	/**
	 * @param id Table Id
	 * @param name Name of the base Table
	 * @param sourceDataSourceId Id of source data source which is connected by this base table.
	 * @param destinationDataSourceId Id of Destination data source which is connected by this base table.
	 */
	public BaseTable(Long id, String name, Long sourceDataSourceId, Long destinationDataSourceId)
	{
		super();
		Id = id;
		this.name = name;
		this.sourceDataSourceId = sourceDataSourceId;
		this.destinationDataSourceId = destinationDataSourceId;
	}

	/**
	 * Getter method for destinationDataSourceId.
	 * @return Returns the destinationDataSourceId.
	 */
	public Long getDestinationDataSourceId()
	{
		return destinationDataSourceId;
	}

	/**
	 * Setter method for destinationDataSourceId
	 * @param destinationDataSourceId The destinationDataSourceId to set.
	 */
	public void setDestinationDataSourceId(Long destinationDataSourceId)
	{
		this.destinationDataSourceId = destinationDataSourceId;
	}

	/**
	 * Getter method for id.
	 * @return Returns the id.
	 */
	public Long getId()
	{
		return Id;
	}

	/**
	 * Setter method for id
	 * @param id The id to set.
	 */
	public void setId(Long id)
	{
		Id = id;
	}

	/**
	 * Getter method for name.
	 * @return Returns the name.
	 */
	public String getName()
	{
		return name;
	}

	/**
	 * Setter method for name
	 * @param name The name to set.
	 */
	public void setName(String name)
	{
		this.name = name;
	}

	/**
	 * Getter method for sourceDataSourceId.
	 * @return Returns the sourceDataSourceId.
	 */
	public Long getSourceDataSourceId()
	{
		return sourceDataSourceId;
	}

	/**
	 * Setter method for sourceDataSourceId
	 * @param sourceDataSourceId The sourceDataSourceId to set.
	 */
	public void setSourceDataSourceId(Long sourceDataSourceId)
	{
		this.sourceDataSourceId = sourceDataSourceId;
	}
}


text:
using System;
using System.Linq;
using Csla;

namespace BusinessLibrary
{
  [Serializable]
  public class PersonList : ReadOnlyListBase<PersonList, PersonInfo>
  {
    [Fetch]
    private void Fetch([Inject]DataAccess.IPersonDal dal, [Inject]IChildDataPortal<PersonInfo> dp)
    {
      IsReadOnly = false;
      var data = dal.Get().Select(d => dp.FetchChild(d));
      AddRange(data);
      IsReadOnly = true;
    }
  }
}


text:
namespace gfx {
class GpuMemoryBuffer;
}

namespace gpu {
struct ManagedMemoryStats;

// Common interface for GpuControl implementations.
class GPU_EXPORT GpuControl {
 public:
  GpuControl() {}
  virtual ~GpuControl() {}

  virtual Capabilities GetCapabilities() = 0;

  // Create a gpu memory buffer of the given dimensions and format. Returns
  // its ID or -1 on error.
  virtual gfx::GpuMemoryBuffer* CreateGpuMemoryBuffer(
      size_t width,
      size_t height,
      unsigned internalformat,
      int32* id) = 0;

  // Destroy a gpu memory buffer. The ID must be positive.
  virtual void DestroyGpuMemoryBuffer(int32 id) = 0;

  // Inserts a sync point, returning its ID. Sync point IDs are global and can
  // be used for cross-context synchronization.
  virtual uint32 InsertSyncPoint() = 0;

  // Runs |callback| when a sync point is reached.
  virtual void SignalSyncPoint(uint32 sync_point,
                               const base::Closure& callback) = 0;

  // Runs |callback| when a query created via glCreateQueryEXT() has cleared
  // passed the glEndQueryEXT() point.
  virtual void SignalQuery(uint32 query, const base::Closure& callback) = 0;

  virtual void SetSurfaceVisible(bool visible) = 0;

  virtual void SendManagedMemoryStats(const ManagedMemoryStats& stats) = 0;

  // Invokes the callback once the context has been flushed.
  virtual void Echo(const base::Closure& callback) = 0;

  // Attaches an external stream to the texture given by |texture_id| and
  // returns a stream identifier.
  virtual uint32 CreateStreamTexture(uint32 texture_id) = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(GpuControl);
};

}  // namespace gpu

#endif  // GPU_COMMAND_BUFFER_COMMON_GPU_CONTROL_H_


text:
package org.n52.oss.guice;

import java.util.HashMap;
import java.util.Map;

import org.n52.oss.api.AutoCompleteResource;
import org.n52.oss.api.TransformationResource;
import org.n52.oss.api.UserAccessResource;
import org.n52.oss.api.ValidatorResource;
import org.n52.oss.opensearch.OpenSearch;
import org.n52.sir.SIR;
import org.n52.sir.harvest.exec.IJSExecute;
import org.n52.sir.harvest.exec.impl.RhinoJSExecute;
import org.n52.sir.script.HarvestResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;

public class ServletModule extends JerseyServletModule {

    private static Logger log = LoggerFactory.getLogger(ServletModule.class);

    public ServletModule() {
        super();
    }

    @Override
    protected void configureServlets() {
        // String basepath = getServletContext().getRealPath("/");
        // bindConstant().annotatedWith(Names.named("context.basepath")).to(basepath);

        bind(IJSExecute.class).to(RhinoJSExecute.class);
        // bind(IValidatorFactory.class).to(ValidatorFactoryImpl.class);
        // bind(SchedulerFactory.class).to(StdSchedulerFactory.class).in(Singleton.class);

        // bind the JAX-RS resources: http://code.google.com/p/google-guice/wiki/ServletModule
        // TODO split up service into modules, move the binding to the respective modules
        bind(HarvestResource.class);
        bind(AutoCompleteResource.class);
        bind(OpenSearch.class);
        bind(SIR.class);
        bind(TransformationResource.class);
        bind(ValidatorResource.class);
        bind(UserAccessResource.class);

        // bind(StatisticsResource.class);

        if (log.isDebugEnabled())
            filter("*").through(DebugFilter.class);

        filter("*").through(CorsFilter.class);

        Map<String, String> params = new HashMap<>();
        params.put("com.sun.jersey.config.property.JSPTemplatesBasePath", "/WEB-INF");

        params.put("com.sun.jersey.config.property.WebPageContentRegex", "/.*\\.(jpg|ico|png|gif|html|id|txt|css|js)");
        params.put("com.sun.jersey.config.property.packages",
                   "org.n52.oss.api;com.wordnik.swagger.jersey.listing;org.codehaus.jackson.jaxrs");
        // params.put("api.version","1.0.0");
        // filter("/doc/api/*").through(GuiceContainer.class,params);
        // filter("/api-docs/*").through(GuiceContainer.class,params);

        filter("/*").through(GuiceContainer.class, params);
        log.debug("configured {} with context {}", this, getServletContext());
    }

}


text:
<?php
declare(strict_types = 1);
/**
 * /src/Security/Interfaces/ApiKeyUserProviderInterface.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Security\Interfaces;

use App\Entity\ApiKey;
use App\Repository\ApiKeyRepository;
use App\Security\RolesService;

/**
 * Interface ApiKeyUserProviderInterface
 *
 * @package App\Security\Provider
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
interface ApiKeyUserProviderInterface
{
    public function __construct(ApiKeyRepository $apiKeyRepository, RolesService $rolesService);

    /**
     * Method to fetch ApiKey entity for specified token.
     */
    public function getApiKeyForToken(string $token): ?ApiKey;
}


text:
//
//package org.foxbpm.engine.impl.util;
//
//import java.util.ArrayList;
//import java.util.List;
//
//import org.eclipse.bpmn2.BaseElement;
//import org.eclipse.bpmn2.Bpmn2Factory;
//import org.eclipse.bpmn2.Definitions;
//import org.eclipse.bpmn2.Documentation;
//import org.eclipse.bpmn2.Expression;
//import org.eclipse.bpmn2.ExtensionAttributeValue;
//import org.eclipse.bpmn2.FormalExpression;
//import org.eclipse.bpmn2.ParallelGateway;
//import org.eclipse.bpmn2.Process;
//import org.eclipse.bpmn2.ResourceRole;
//import org.eclipse.bpmn2.SequenceFlow;
//import org.eclipse.bpmn2.UserTask;
//import org.eclipse.bpmn2.di.BPMNEdge;
//import org.eclipse.bpmn2.di.BPMNShape;
//import org.eclipse.dd.di.DiagramElement;
//import org.eclipse.emf.common.util.TreeIterator;
//import org.eclipse.emf.ecore.EAttribute;
//import org.eclipse.emf.ecore.EObject;
//import org.eclipse.emf.ecore.EReference;
//import org.eclipse.emf.ecore.impl.BasicEObjectImpl;
//import org.eclipse.emf.ecore.impl.EStructuralFeatureImpl.SimpleFeatureMapEntry;
//import org.eclipse.emf.ecore.util.FeatureMap;
//import org.foxbpm.engine.impl.connector.ConnectorListener;
//import org.foxbpm.engine.impl.task.TaskAssigneeDefinition;
//import org.foxbpm.engine.task.TaskCommand;
//import org.foxbpm.model.SkipStrategy;
//import org.foxbpm.model.bpmn.foxbpm.AssignPolicyType;
//import org.foxbpm.model.bpmn.foxbpm.CompleteTaskDescription;
//import org.foxbpm.model.bpmn.foxbpm.ExpectedExecutionTime;
//import org.foxbpm.model.bpmn.foxbpm.FormParamContainer;
//import org.foxbpm.model.bpmn.foxbpm.FormUri;
//import org.foxbpm.model.bpmn.foxbpm.FormUriView;
//import org.foxbpm.model.bpmn.foxbpm.FoxBPMPackage;
//import org.foxbpm.model.bpmn.foxbpm.PotentialStarter;
//import org.foxbpm.model.bpmn.foxbpm.TaskDescription;
//import org.foxbpm.model.bpmn.foxbpm.TaskPriority;
//import org.foxbpm.model.bpmn.foxbpm.TaskSubject;
//
//
//public class BpmnModelUtil {
//
//	/** 获取流程的唯一编号*/
//	public static String getProcessId(Process process){
//		return StringUtil.getString(getExtensionAttribute(process,FoxBPMPackage.Literals.DOCUMENT_ROOT__DBID));
//	}
//
//	/** 获取任务领取方式*/
//	public static String claimType(UserTask userTask){
//		return StringUtil.getString(getExtensionAttribute(userTask,FoxBPMPackage.Literals.DOCUMENT_ROOT__CLAIM_TYPE));
//	}
//
//	/** 获取并行网关合并策略*/
//	public static String convergType(ParallelGateway parallelGateway){
//		return StringUtil.getString(getExtensionAttribute(parallelGateway,FoxBPMPackage.Literals.DOCUMENT_ROOT__CONVERG_TYPE));
//	}
//
//	/** 获取流程的分类*/
//	public static String getProcessCategory(Process process){
//		return StringUtil.getString(getExtensionAttribute(process,FoxBPMPackage.Literals.DOCUMENT_ROOT__CATEGORY));
//	}
//
//	/** 获取流程的发起人*/
//	public static List<PotentialStarter> getPotentialStarters(Process process){
//
//		List<PotentialStarter> extensionElementList = getExtensionElementList(PotentialStarter.class, process, FoxBPMPackage.Literals.DOCUMENT_ROOT__POTENTIAL_STARTER);
//
//		return extensionElementList;
//	}
//
//	public List<ConnectorListener> getcConnectors(BaseElement baseElement){
//
//		List<ConnectorListener> connectors=new ArrayList<ConnectorListener>();
//
//
//		return connectors;
//	}
//
//	/**
//	 * 获取开始节点是否持久化属性
//	 * @param baseElement
//	 * @return
//	 */
//	public static boolean getStartEventPersistence(BaseElement baseElement){
//		return StringUtil.getBoolean(BpmnModelUtil.getExtensionAttribute(baseElement, FoxBPMPackage.Literals.DOCUMENT_ROOT__IS_PERSISTENCE));
//	}
//
//	/**
//	 * 获取线条表达式值
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getSequenceFlowCondition(BaseElement baseElement){
//		SequenceFlow sequenceFlow = (SequenceFlow)baseElement;
//		Expression expression = sequenceFlow.getConditionExpression();
//		if(expression != null){
//			FormalExpression formalExpression = (FormalExpression)expression;
//			return formalExpression.getBody();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取人工任务主题信息
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getUserTaskSubject(BaseElement baseElement){
//		TaskSubject taskSubject = (TaskSubject)BpmnModelUtil.getExtensionElement(baseElement,FoxBPMPackage.Literals.DOCUMENT_ROOT__TASK_SUBJECT);
//		if(taskSubject != null&&taskSubject.getExpression()!=null){
//
//
//
//			return taskSubject.getExpression().getValue();
//
//		}
//		return null;
//	}
//
//
//	/**
//	 * 获取人工任务表单参数
//	 * @param baseElement
//	 * @return
//	 */
//	public static FormParamContainer getFormParamContainer(BaseElement baseElement){
//		FormParamContainer formParamContainer = (FormParamContainer)BpmnModelUtil.getExtensionElement(baseElement,FoxBPMPackage.Literals.DOCUMENT_ROOT__FORM_PARAM_CONTAINER);
//		return formParamContainer;
//	}
//
//
//
//
//	/**
//	 * 获取人工任务描述
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getUserTaskDescription(BaseElement baseElement){
//		TaskDescription taskDescription = (TaskDescription)BpmnModelUtil.getExtensionElement(baseElement,FoxBPMPackage.Literals.DOCUMENT_ROOT__TASK_DESCRIPTION);
//		if(taskDescription != null&&taskDescription.getExpression()!=null){
//			return taskDescription.getExpression().getValue();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取人工任务描述
//	 * @param baseElement
//	 * @return
//	 */
//	public static double getExpectedExecuteTime(BaseElement baseElement){
//		ExpectedExecutionTime time = (ExpectedExecutionTime)BpmnModelUtil.getExtensionElement(baseElement,FoxBPMPackage.Literals.DOCUMENT_ROOT__EXPECTED_EXECUTION_TIME);
//		if(time != null){
//			int day = time.getDay();
//			int hours = time.getHour();
//			int minute = time.getMinute();
//			double expectTime = day*24 + hours + ((double)minute)/60;
//			return expectTime;
//		}
//		return 0;
//	}
//
//	/**
//	 * 获取人工任务完成后的描述
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getUserTaskCompleteTaskDescription(BaseElement baseElement){
//		CompleteTaskDescription completeTaskDescription = (CompleteTaskDescription)BpmnModelUtil.getExtensionElement(baseElement,FoxBPMPackage.Literals.DOCUMENT_ROOT__COMPLETE_TASK_DESCRIPTION);
//		if(completeTaskDescription != null&&completeTaskDescription.getExpression()!=null){
//			return completeTaskDescription.getExpression().getValue();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取操作表单
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getFormUri(BaseElement baseElement){
//		FormUri formUri = (FormUri)BpmnModelUtil.getExtensionElement(baseElement, FoxBPMPackage.Literals.DOCUMENT_ROOT__FORM_URI);
//		if(formUri != null&&formUri.getExpression()!=null){
//			return formUri.getExpression().getValue();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取浏览表单
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getFormUriView(BaseElement baseElement){
//		FormUriView formUri = (FormUriView)BpmnModelUtil.getExtensionElement(baseElement, FoxBPMPackage.Literals.DOCUMENT_ROOT__FORM_URI_VIEW);
//		if(formUri != null&&formUri.getExpression()!=null){
//			return formUri.getExpression().getValue();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取任务分配策略
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getUserTaskAssigneePolicyType(BaseElement baseElement){
//		AssignPolicyType policyType = (AssignPolicyType)BpmnModelUtil.getExtensionElement(baseElement, FoxBPMPackage.Literals.DOCUMENT_ROOT__ASSIGN_POLICY_TYPE);
//		if(policyType != null){
//			return policyType.getExpression().getValue();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取任务分配策略
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getUserTaskType(BaseElement baseElement){
//		String taskType = (String)BpmnModelUtil.getExtensionAttribute(baseElement, FoxBPMPackage.Literals.DOCUMENT_ROOT__TASK_TYPE);
//		return taskType;
//	}
//
//	/**
//	 * 获取任务分配表达式
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getUserTaskAssigneeExpression(BaseElement baseElement){
//		org.foxbpm.model.bpmn.foxbpm.Expression expression = (org.foxbpm.model.bpmn.foxbpm.Expression)BpmnModelUtil.getExtensionElement(baseElement, FoxBPMPackage.Literals.DOCUMENT_ROOT__ASSIGN_POLICY_TYPE);
//		return getValueFormExpression(expression);
//	}
//
//	/**
//	 * 获取任务处理者
//	 * @param baseElement
//	 * @return
//	 */
//	public static List<TaskAssigneeDefinition> getUserTaskAssignees(BaseElement baseElement){
//		UserTask userTask = (UserTask)baseElement;
//		List<ResourceRole> resources = userTask.getResources();
//		List<TaskAssigneeDefinition> assignees = new ArrayList<TaskAssigneeDefinition>();
//		if(resources != null){
//			for(ResourceRole resource :resources){
//				if(resource != null){
//					String resourceType = StringUtil.getString(resource.eGet(FoxBPMPackage.Literals.DOCUMENT_ROOT__RESOURCE_TYPE, true));
//					boolean isContainsSub = StringUtil.getBoolean(resource.eGet(FoxBPMPackage.Literals.DOCUMENT_ROOT__IS_CONTAINS_SUB, true));
//					String resourceExpression = BpmnModelUtil.getExpression(resource.getResourceAssignmentExpression().getExpression());
//					//String resourceName = resource.getName();
//					TaskAssigneeDefinition assignee = new TaskAssigneeDefinition();
//					assignee.setContainsSub(isContainsSub);
//					assignee.setUserIdExpression(resourceExpression);
//					assignee.setGroupIdExpression(resourceExpression);
//					assignee.setGroupTypeExpression(resourceType);
//					assignees.add(assignee);
//				}
//			}
//		}
//		return assignees;
//	}
//
//	/**
//	 * 获取任务命令集合
//	 * @param baseElement
//	 * @return
//	 */
//	public static List<TaskCommand> getUserTaskCommands(BaseElement baseElement){
//		List<TaskCommand> taskCommands = new ArrayList<TaskCommand>();
////		List<TaskCommandModel> taskCommandsObj  =BpmnModelUtil.getAll(TaskCommandModel.class, baseElement);
////		if(taskCommandsObj!=null){
////			for (TaskCommandModel tmpTaskCommand : taskCommandsObj) {
////				TaskCommand taskCommandDefinition = new TaskCommand();
////				taskCommandDefinition.setCommandType(tmpTaskCommand.getCommandType());
////				taskCommandDefinition.setId(tmpTaskCommand.getId());
////				taskCommandDefinition.setName(tmpTaskCommand.getName());
////				org.foxbpm.model.bpmn.foxbpm.Expression expression =  tmpTaskCommand.getExpression();
////				if(expression != null){
////					taskCommandDefinition.setExpression(expression.getValue());
////				}
////				expression =  tmpTaskCommand.getParameterExpression();
////				if(expression != null){
////					taskCommandDefinition.setParaExpression(expression.getValue());
////				}
////				taskCommands.add(taskCommandDefinition);
////			}
////		}
//		return taskCommands;
//	}
//
//	/**
//	 * 获取任务优先级
//	 * @param baseElement
//	 * @return
//	 */
//	public static String getUserTaskPriority(BaseElement baseElement){
//		TaskPriority taskPriorityObj  = (TaskPriority)BpmnModelUtil.getExtensionElement(baseElement, FoxBPMPackage.Literals.DOCUMENT_ROOT__TASK_PRIORITY);
//		if(taskPriorityObj != null){
//			return taskPriorityObj.getExpression().getValue();
//		}
//		return null;
//	}
//
//	public static String getValueFormExpression(org.foxbpm.model.bpmn.foxbpm.Expression expression){
//		if(expression != null){
//			return expression.getValue();
//		}
//		return null;
//	}
//
//	public static Object getExtensionAttribute(BaseElement baseElement,EAttribute eAttribute){
//		return baseElement.eGet(eAttribute);
//	}
//
//	public static Object getExtensionElement(BaseElement baseElement,EReference eReference){
//		if(baseElement==null){
//			return null;
//		}
//		if (baseElement.getExtensionValues().size() > 0) {
//			for (ExtensionAttributeValue extensionAttributeValue : baseElement.getExtensionValues()) {
//				FeatureMap extensionElements = extensionAttributeValue.getValue();
//				Object objectElement = extensionElements.get(eReference, true);
//				if (objectElement != null) {
//					if(objectElement instanceof List){
//						@SuppressWarnings("unchecked")
//						List<EObject> tObjList = (List<EObject>)objectElement;
//						if(tObjList.size()>0){
//							return tObjList.get(0);
//						}
//					}else{
//						return objectElement;
//					}
//				}
//			}
//		}
//		return null;
//	}
//
//	@SuppressWarnings("unchecked")
//	public static <T> T getExtensionElementOne(Class<T> t ,BaseElement baseElement,EReference eReference){
//
//
//		if(baseElement==null){
//			return null;
//		}
//
//		if (baseElement.getExtensionValues().size() > 0) {
//			for (ExtensionAttributeValue extensionAttributeValue : baseElement.getExtensionValues()) {
//				FeatureMap extensionElements = extensionAttributeValue.getValue();
//
//				Object objectElement = extensionElements.get(eReference, true);
//				if (objectElement != null) {
//
//
//					if(objectElement instanceof List){
//						List<T> tObjList = (List<T>) objectElement;
//						if(tObjList.size()>0){
//							return tObjList.get(0);
//						}
//
//					}else{
//						return (T)objectElement;
//					}
//
//				}
//
//
//			}
//		}
//
//
//
//
//
//		return (T)null;
//	}
//
//
//	@SuppressWarnings("unchecked")
//	public static <T> List<T> getExtensionElementList( Class<T> t ,BaseElement baseElement,EReference eReference){
//
//
//		if (baseElement.getExtensionValues().size() > 0) {
//			for (ExtensionAttributeValue extensionAttributeValue : baseElement.getExtensionValues()) {
//				FeatureMap extensionElements = extensionAttributeValue.getValue();
//				Object objectElement = extensionElements.get(eReference, true);
//				if (objectElement != null) {
//
//					List<T> tObjList = (List<T>) objectElement;
//					return tObjList;
//
//
//				}
//			}
//		}
//
//
//		return (List<T>)null;
//	}
//
//
//	public static String getDocumentation(BaseElement baseElement){
//		List<Documentation> documentations=baseElement.getDocumentation();
//		if(documentations.size()==0){
//			return null;
//		}
//		else{
//			String documentationText=documentations.get(0).getText();
//			return documentationText;
//		}
//	}
//
//	/**
//	 * 增加扩展元素
//	 * @param baseElement
//	 * @param eReference
//	 * @param o
//	 * @return
//	 */
//	public static boolean addExtensionElement(BaseElement baseElement,EReference eReference,Object o){
//		final FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry((org.eclipse.emf.ecore.EStructuralFeature.Internal) eReference, o);
//  	  	if(baseElement.getExtensionValues().size() > 0){
//  	  		baseElement.getExtensionValues().get(0).getValue().add(extensionElementEntry);
//  	  	}else{
//  	  		ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
//  	  		extensionElement.getValue().add(extensionElementEntry);
//  	  		baseElement.getExtensionValues().add(extensionElement);
//  	  	}
//		return false;
//	}
//
//	/**
//	 * 获取节点的跳过策略
//	 *
//	 * @return
//	 */
//	public static SkipStrategy getSkipStrategy(BaseElement baseElement) {
//
//		return getExtensionElementOne(SkipStrategy.class,baseElement,FoxBPMPackage.Literals.DOCUMENT_ROOT__SKIP_STRATEGY);
//
//	}
//
//	/**
//	 * 增加擴展屬性
//	 * @param baseElement
//	 * @param eReference
//	 * @param o
//	 * @return
//	 */
//	public static boolean addExtensionAttribute(BaseElement baseElement,EAttribute eAttribute,Object o){
//		final FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry((org.eclipse.emf.ecore.EStructuralFeature.Internal) eAttribute, o);
//		baseElement.getAnyAttribute().add(extensionElementEntry);
//		return false;
//	}
//
//	public static void setDocumentation(BaseElement baseElement,String documentationText){
//		List<Documentation> documentations=baseElement.getDocumentation();
//		if(documentations==null){
//			documentations=new ArrayList<Documentation>();
//			Documentation documentation=Bpmn2Factory.eINSTANCE.createDocumentation();
//			documentation.setText(documentationText);
//			documentations.add(documentation);
//			return;
//		}
//		if(documentations.size()==0){
//			Documentation documentation=Bpmn2Factory.eINSTANCE.createDocumentation();
//			documentation.setText(documentationText);
//			documentations.add(documentation);
//			return;
//		}
//		else{
//			documentations.get(0).setText(documentationText);
//			return;
//		}
//	}
//
//	public static String getExpression(Expression expression){
//		if(expression==null){
//			return null;
//		}
//		return ((FormalExpression)expression).getBody();
//
//	}
//
//	public static Expression getExpressionByString(String expression){
//		FormalExpression formalExpression=Bpmn2Factory.eINSTANCE.createFormalExpression();
//		formalExpression.setBody(expression);
//		return formalExpression;
//
//	}
//
//	public static BPMNShape getBpmnShape(Definitions definitions,String elementId){
//		List<DiagramElement> diagramElements=definitions.getDiagrams().get(0).getPlane().getPlaneElement();
//		for (DiagramElement diagramElement : diagramElements) {
//			if(diagramElement instanceof BPMNShape){
//				BPMNShape bpmnShape = (BPMNShape) diagramElement;
//				BaseElement bpmnElement=getBaseElement(definitions,bpmnShape.getBpmnElement());
//				if(bpmnElement==null){
//					continue;
//				}
//				if(elementId.equals(bpmnElement.getId())){
//					return bpmnShape;
//				}
//			}
//		}
//		return null;
//	}
//
//	public static  BaseElement getBaseElement(Definitions definitions,BaseElement baseElement){
//		if(baseElement==null){
//			return null;
//		}
//		if(baseElement.getId()==null){
//			BasicEObjectImpl basicEObjectImpl=(BasicEObjectImpl)baseElement;
//			if(basicEObjectImpl!=null&&basicEObjectImpl.eProxyURI()!=null){
//				String elementId=basicEObjectImpl.eProxyURI().fragment();
//				BaseElement bpmnElement=getBaseElement(definitions,elementId);
//				return bpmnElement;
//			}
//			else{
//				return null;
//			}
//		}else{
//			return baseElement;
//		}
//	}
//
//	public static BPMNEdge getBpmnEdge(Definitions definitions,String elementId){
//		List<DiagramElement> diagramElements=definitions.getDiagrams().get(0).getPlane().getPlaneElement();
//		for (DiagramElement diagramElement : diagramElements) {
//			if(diagramElement instanceof BPMNEdge){
//				BPMNEdge bPMNEdge = (BPMNEdge)diagramElement;
//				String bpmnId=bPMNEdge.getBpmnElement().getId();
//				if(elementId.equals(bpmnId)){
//					return bPMNEdge;
//				}
//			}
//		}
//		return null;
//	}
//
//
//	public static BaseElement findElement(String id,EObject eObject) {
//		if (id == null || StringUtil.isEmpty(id))
//			return null;
//
//		List<BaseElement> baseElements = getAll(BaseElement.class,eObject);
//
//		for (BaseElement be : baseElements) {
//			if (id.equals(be.getId())) {
//				return be;
//			}
//		}
//
//		return null;
//	}
//
//
//	@SuppressWarnings("unchecked")
//	public static <T> T findElement(String id,EObject eObject,Class<T> class1) {
//		if (id == null || StringUtil.isEmpty(id))
//			return null;
//
//		List<BaseElement> baseElements = getAll(BaseElement.class,eObject);
//
//		for (BaseElement be : baseElements) {
//			if (id.equals(be.getId())&&class1.isInstance(be)) {
//				return (T)be;
//			}
//		}
//
//		return null;
//	}
//
//	@SuppressWarnings("unchecked")
//	public static <T> List<T> getAll(final Class<T> class1,EObject eObject) {
//		ArrayList<T> l = new ArrayList<T>();
//		TreeIterator<EObject> contents =eObject.eResource().getAllContents();
//		for (; contents.hasNext();) {
//			Object t = contents.next();
//			if (class1.isInstance(t)) {
//				l.add((T) t);
//			}
//		}
//		return l;
//	}
//
//	public static BaseElement  getBaseElement(Definitions definitions,String elementId){
//		return findElement(elementId, definitions);
//	}
//
//	public static <T> T  getElement(Definitions definitions,String elementId,Class<T> class1){
//		return findElement(elementId, definitions, class1);
//	}
//
//	public static <T> List<T>  getElementList(BaseElement baseElement,Class<T> class1){
//		return getAll(class1, baseElement);
//	}
//
//	public static Process getProcess(BaseElement baseElement){
//		return getAll(Process.class, baseElement).get(0);
//	}
//
//	public static List<Process> getProcessList(BaseElement baseElement){
//		return getAll(Process.class, baseElement);
//	}
//
//}


text:
/**
 * The controller used when viewing an individual video.
 */
tooglesApp.controller('ViewCtrl', ['$scope', '$routeParams', '$location', 'youtube', function($scope, $routeParams, $location, youtube) {

  $scope.location = $location; // Access $location inside the view.
  $scope.showSidebar = true;
  $scope.showRelated = false;
  $scope.section = $location.path().split('/')[1];
  $scope.videoTab = $scope.section === 'view' ? 'Related' : 'Playlist';

  window.viewCallback = function(data) {
    if ($scope.section === 'view') {
      $scope.video = data.entry;
      $scope.video.video_id = $routeParams.id;
      $scope.video.embedurl = "http://www.youtube.com/embed/" + $scope.video.video_id + "?autoplay=1&theme=light&color=white&iv_load_policy=3&origin=http://toogl.es";
    } else {
      var start = $routeParams.start || 0;
      $scope.video = data.feed.entry[start];
      $scope.video.video_id = $scope.video.media$group.yt$videoid.$t;
      $scope.video.embedurl = "http://www.youtube.com/embed/videoseries?list=" + $routeParams.id + "&autoplay=1&theme=light&color=white&iv_load_policy=3&origin=http://toogl.es&index=" + start;
      $scope.videos = data.feed.entry;
    }
    onYouTubeIframeAPIReady($scope.video.video_id, $scope.section);
    document.title = $scope.video.title.$t + " | Toogles";
  }

  window.relatedCallback = function(data) {
    $scope.videos = data.feed.entry;
  }

  $scope.fetchRelated = function() {
    if (!$scope.videos) {
      youtube.setCallback('relatedCallback');
      youtube.getVideos('related', $routeParams.id);
    }
    $scope.showRelated = true;
  }

  $scope.getLink = function(video, index) {
    if ($scope.section == 'view') {
      return '#/view/' + youtube.urlToID(video.media$group.yt$videoid.$t);
    } else if ($scope.section = 'playlist') {
      return '#/playlist/' + $routeParams.id + '/' + index
    }
  }

  $scope.formatDuration = function(seconds) {
    return youtube.formatDuration(seconds);
  }

  youtube.setCallback('viewCallback');
  if ($scope.section === 'view') {
    youtube.getItem('videos', $routeParams.id);
  } else {
    youtube.getItem('playlists', $routeParams.id);
  }

  started = false;

  var onYouTubeIframeAPIReady = function(id, section) {
    var player = new YT.Player('player', {
      videoId: id,
      events: {
        'onStateChange': function (event) {
          if (event.data == 1) {
            started = true;
          }
          if (started && event.data == -1) {
            // When a new video is started in an existing player, open up its dedicated page.
            if (section === 'view') {
              var video_url = event.target.getVideoUrl();
              var video_id = video_url.replace('http://www.youtube.com/watch?v=', '').replace('&feature=player_embedded', '');
              window.location = '#/view/' + video_id;
            } else if (section === 'playlist') {
              window.location = '#/playlist/' + event.target.getPlaylistId() + '/' + event.target.getPlaylistIndex();
            }
          }
        }
      }
    });
  }
}]);


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/users/avatar/user_image_loader.h"

#include <memory>
#include <utility>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/ptr_util.h"
#include "base/sequenced_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "components/user_manager/user_image/user_image.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/skbitmap_operations.h"

namespace chromeos {
namespace user_image_loader {
namespace {

// Contains attributes we need to know about each image we decode.
struct ImageInfo {
  ImageInfo(const base::FilePath& file_path,
            int pixels_per_side,
            ImageDecoder::ImageCodec image_codec,
            const LoadedCallback& loaded_cb)
      : file_path(file_path),
        pixels_per_side(pixels_per_side),
        image_codec(image_codec),
        loaded_cb(loaded_cb) {}
  ~ImageInfo() {}

  const base::FilePath file_path;
  const int pixels_per_side;
  const ImageDecoder::ImageCodec image_codec;
  const LoadedCallback loaded_cb;
};

// Crops |image| to the square format and downsizes the image to
// |target_size| in pixels. On success, returns true and stores the cropped
// image in |bitmap| and the bytes representation in |byytes|.
bool CropImage(const SkBitmap& image,
               int target_size,
               SkBitmap* bitmap,
               user_manager::UserImage::Bytes* bytes) {
  DCHECK_GT(target_size, 0);

  SkBitmap final_image;
  // Auto crop the image, taking the largest square in the center.
  int pixels_per_side = std::min(image.width(), image.height());
  int x = (image.width() - pixels_per_side) / 2;
  int y = (image.height() - pixels_per_side) / 2;
  SkBitmap cropped_image = SkBitmapOperations::CreateTiledBitmap(
      image, x, y, pixels_per_side, pixels_per_side);
  if (pixels_per_side > target_size) {
    // Also downsize the image to save space and memory.
    final_image = skia::ImageOperations::Resize(
        cropped_image, skia::ImageOperations::RESIZE_LANCZOS3, target_size,
        target_size);
  } else {
    final_image = cropped_image;
  }

  // Encode the cropped image to web-compatible bytes representation
  std::unique_ptr<user_manager::UserImage::Bytes> encoded =
      user_manager::UserImage::Encode(final_image);
  if (!encoded)
    return false;

  bitmap->swap(final_image);
  bytes->swap(*encoded);
  return true;
}

// Handles the decoded image returned from ImageDecoder through the
// ImageRequest interface.
class UserImageRequest : public ImageDecoder::ImageRequest {
 public:
  UserImageRequest(
      const ImageInfo& image_info,
      const std::string& image_data,
      scoped_refptr<base::SequencedTaskRunner> background_task_runner)
      : image_info_(image_info),
        image_data_(image_data.begin(), image_data.end()),
        background_task_runner_(background_task_runner),
        weak_ptr_factory_(this) {}
  ~UserImageRequest() override {}

  // ImageDecoder::ImageRequest implementation.
  void OnImageDecoded(const SkBitmap& decoded_image) override;
  void OnDecodeImageFailed() override;

  // Called after the image is cropped (and downsized) as needed.
  void OnImageCropped(SkBitmap* bitmap,
                      user_manager::UserImage::Bytes* bytes,
                      bool succeeded);

  // Called after the image is finalized. |image_bytes_regenerated| is true
  // if |image_bytes| is regenerated from the cropped image.
  void OnImageFinalized(const SkBitmap& image,
                        const user_manager::UserImage::Bytes& image_bytes,
                        bool image_bytes_regenerated);

 private:
  const ImageInfo image_info_;
  const user_manager::UserImage::Bytes image_data_;
  scoped_refptr<base::SequencedTaskRunner> background_task_runner_;

  // This should be the last member.
  base::WeakPtrFactory<UserImageRequest> weak_ptr_factory_;
};

void UserImageRequest::OnImageDecoded(const SkBitmap& decoded_image) {
  int target_size = image_info_.pixels_per_side;
  if (target_size > 0) {
    // Cropping an image could be expensive, hence posting to the background
    // thread.
    SkBitmap* bitmap = new SkBitmap;
    user_manager::UserImage::Bytes* bytes = new user_manager::UserImage::Bytes;
    base::PostTaskAndReplyWithResult(
        background_task_runner_.get(), FROM_HERE,
        base::Bind(&CropImage, decoded_image, target_size, bitmap, bytes),
        base::Bind(&UserImageRequest::OnImageCropped,
                   weak_ptr_factory_.GetWeakPtr(), base::Owned(bitmap),
                   base::Owned(bytes)));
  } else {
    OnImageFinalized(decoded_image, image_data_,
                     false /* image_bytes_regenerated */);
  }
}

void UserImageRequest::OnImageCropped(SkBitmap* bitmap,
                                      user_manager::UserImage::Bytes* bytes,
                                      bool succeeded) {
  DCHECK_GT(image_info_.pixels_per_side, 0);

  if (!succeeded) {
    OnDecodeImageFailed();
    return;
  }
  OnImageFinalized(*bitmap, *bytes, true /* image_bytes_regenerated */);
}

void UserImageRequest::OnImageFinalized(
    const SkBitmap& image,
    const user_manager::UserImage::Bytes& image_bytes,
    bool image_bytes_regenerated) {
  SkBitmap final_image = image;
  // Make the SkBitmap immutable as we won't modify it. This is important
  // because otherwise it gets duplicated during painting, wasting memory.
  final_image.setImmutable();
  gfx::ImageSkia final_image_skia =
      gfx::ImageSkia::CreateFrom1xBitmap(final_image);
  final_image_skia.MakeThreadSafe();
  std::unique_ptr<user_manager::UserImage> user_image(
      new user_manager::UserImage(final_image_skia, image_bytes));
  user_image->set_file_path(image_info_.file_path);
  if (image_info_.image_codec == ImageDecoder::ROBUST_JPEG_CODEC ||
      image_bytes_regenerated)
    user_image->MarkAsSafe();
  image_info_.loaded_cb.Run(std::move(user_image));
  delete this;
}

void UserImageRequest::OnDecodeImageFailed() {
  image_info_.loaded_cb.Run(base::WrapUnique(new user_manager::UserImage));
  delete this;
}

// Starts decoding the image with ImageDecoder for the image |data| if
// |data_is_ready| is true.
void DecodeImage(
    const ImageInfo& image_info,
    scoped_refptr<base::SequencedTaskRunner> background_task_runner,
    const std::string* data,
    bool data_is_ready) {
  if (!data_is_ready) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE,
        base::Bind(image_info.loaded_cb, base::Passed(base::WrapUnique(
                                             new user_manager::UserImage))));
    return;
  }

  UserImageRequest* image_request =
      new UserImageRequest(image_info, *data, background_task_runner);
  ImageDecoder::StartWithOptions(image_request, *data, image_info.image_codec,
                                 false);
}

}  // namespace

void StartWithFilePath(
    scoped_refptr<base::SequencedTaskRunner> background_task_runner,
    const base::FilePath& file_path,
    ImageDecoder::ImageCodec image_codec,
    int pixels_per_side,
    const LoadedCallback& loaded_cb) {
  std::string* data = new std::string;
  base::PostTaskAndReplyWithResult(
      background_task_runner.get(), FROM_HERE,
      base::Bind(&base::ReadFileToString, file_path, data),
      base::Bind(&DecodeImage,
                 ImageInfo(file_path, pixels_per_side, image_codec, loaded_cb),
                 background_task_runner, base::Owned(data)));
}

void StartWithData(
    scoped_refptr<base::SequencedTaskRunner> background_task_runner,
    std::unique_ptr<std::string> data,
    ImageDecoder::ImageCodec image_codec,
    int pixels_per_side,
    const LoadedCallback& loaded_cb) {
  DecodeImage(
      ImageInfo(base::FilePath(), pixels_per_side, image_codec, loaded_cb),
      background_task_runner, data.get(), true /* data_is_ready */);
}

}  // namespace user_image_loader
}  // namespace chromeos


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main(name) {
  // [START osconfig_v1alpha_generated_OsConfigZonalService_GetInventory_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. API resource name for inventory resource.
   *  Format:
   *  `projects/{project}/locations/{location}/instances/{instance}/inventory`
   *  For `{project}`, either `project-number` or `project-id` can be provided.
   *  For `{instance}`, either Compute Engine  `instance-id` or `instance-name`
   *  can be provided.
   */
  // const name = 'abc123'
  /**
   *  Inventory view indicating what information should be included in the
   *  inventory resource. If unspecified, the default view is BASIC.
   */
  // const view = {}

  // Imports the Osconfig library
  const {OsConfigZonalServiceClient} = require('@google-cloud/os-config').v1alpha;

  // Instantiates a client
  const osconfigClient = new OsConfigZonalServiceClient();

  async function callGetInventory() {
    // Construct request
    const request = {
      name,
    };

    // Run request
    const response = await osconfigClient.getInventory(request);
    console.log(response);
  }

  callGetInventory();
  // [END osconfig_v1alpha_generated_OsConfigZonalService_GetInventory_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pair
{
    public class Pair<T>
    {
        private readonly object first;
        private readonly object second;
        public object First { get { return first; } }
        public object Second { get { return second; } }

        public Pair() { }
        public Pair(T object1, T object2)
        {
            first = object1;
            second = object2;
        }

        public override bool Equals(object obj)
        {
            if (obj is Pair<T>)
            {
                Pair<T> pair = obj as Pair<T>;
                if (!first.Equals(pair.first))
                {
                    return false;
                }

                if (!second.Equals(pair.second))
                {
                    return false;
                }

                return true;
            }

            else return false;
        }

        public static bool operator ==(Pair<T> firstPair, Pair<T> secondPair)
        {
            return object.Equals(firstPair, secondPair);
        }

        public static bool operator !=(Pair<T> firstPair, Pair<T> secondPair)
        {
            return !object.Equals(firstPair, secondPair);
        }

        public override string ToString()
        {
            return string.Format("Pair({0}, {1})", First, Second);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hash = 17;
                hash = hash * 23 + First.GetHashCode();
                hash = hash * 23 + Second.GetHashCode();
                return hash;
            }
        }
    }
}


text:
cd ..
rm -rf ansible/action_plugins/pout
mkdir pout
protoc --proto_path=vendor --proto_path=api --python_out=pout api/models/vpp/interfaces/interface.proto api/models/vpp/ipsec/ipsec.proto api/models/vpp/l3/route.proto api/models/vpp/l2/bridge-domain.proto api/models/vpp/nat/nat.proto api/models/vpp/l2/xconnect.proto api/models/vpp/l3/l3.proto api/models/linux/interfaces/interface.proto  api/models/linux/namespace/namespace.proto
mv pout ansible/action_plugins/.
cd ansible/action_plugins/pout
find . -type d -exec touch {}/__init__.py \;


text:
package org.apache.storm.scheduler.multitenant;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import org.apache.storm.scheduler.SchedulerAssignment;
import org.apache.storm.scheduler.TopologyDetails;
import org.apache.storm.scheduler.WorkerSlot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A pool of machines that anyone can use, but topologies are not isolated.
 */
public class DefaultPool extends NodePool {
    private static final Logger LOG = LoggerFactory.getLogger(DefaultPool.class);
    private Set<Node> nodes = new HashSet<>();
    private HashMap<String, TopologyDetails> tds = new HashMap<>();

    @Override
    public void addTopology(TopologyDetails td) {
        String topId = td.getId();
        LOG.debug("Adding in Topology {}", topId);
        tds.put(topId, td);
        SchedulerAssignment assignment = cluster.getAssignmentById(topId);
        if (assignment != null) {
            for (WorkerSlot ws : assignment.getSlots()) {
                Node n = nodeIdToNode.get(ws.getNodeId());
                nodes.add(n);
            }
        }
    }

    @Override
    public boolean canAdd(TopologyDetails td) {
        return true;
    }

    @Override
    public Collection<Node> takeNodes(int nodesNeeded) {
        HashSet<Node> ret = new HashSet<>();
        LinkedList<Node> sortedNodes = new LinkedList<>(nodes);
        Collections.sort(sortedNodes, Node.FREE_NODE_COMPARATOR_DEC);
        for (Node n : sortedNodes) {
            if (nodesNeeded <= ret.size()) {
                break;
            }
            if (n.isAlive()) {
                n.freeAllSlots(cluster);
                nodes.remove(n);
                ret.add(n);
            }
        }
        return ret;
    }

    @Override
    public int nodesAvailable() {
        int total = 0;
        for (Node n : nodes) {
            if (n.isAlive()) {
                total++;
            }
        }
        return total;
    }

    @Override
    public int slotsAvailable() {
        return Node.countTotalSlotsAlive(nodes);
    }

    @Override
    public NodeAndSlotCounts getNodeAndSlotCountIfSlotsWereTaken(int slotsNeeded) {
        int nodesFound = 0;
        int slotsFound = 0;
        LinkedList<Node> sortedNodes = new LinkedList<>(nodes);
        Collections.sort(sortedNodes, Node.FREE_NODE_COMPARATOR_DEC);
        for (Node n : sortedNodes) {
            if (slotsNeeded <= 0) {
                break;
            }
            if (n.isAlive()) {
                nodesFound++;
                int totalSlotsFree = n.totalSlots();
                slotsFound += totalSlotsFree;
                slotsNeeded -= totalSlotsFree;
            }
        }
        return new NodeAndSlotCounts(nodesFound, slotsFound);
    }

    @Override
    public Collection<Node> takeNodesBySlots(int slotsNeeded) {
        HashSet<Node> ret = new HashSet<>();
        LinkedList<Node> sortedNodes = new LinkedList<>(nodes);
        Collections.sort(sortedNodes, Node.FREE_NODE_COMPARATOR_DEC);
        for (Node n : sortedNodes) {
            if (slotsNeeded <= 0) {
                break;
            }
            if (n.isAlive()) {
                n.freeAllSlots(cluster);
                nodes.remove(n);
                ret.add(n);
                slotsNeeded -= n.totalSlotsFree();
            }
        }
        return ret;
    }

    @Override
    public void scheduleAsNeeded(NodePool... lesserPools) {
        for (TopologyDetails td : tds.values()) {
            String topId = td.getId();
            if (cluster.needsScheduling(td)) {
                LOG.debug("Scheduling topology {}", topId);
                int totalTasks = td.getExecutors().size();
                int origRequest = td.getNumWorkers();
                int slotsRequested = Math.min(totalTasks, origRequest);
                int slotsUsed = Node.countSlotsUsed(topId, nodes);
                int slotsFree = Node.countFreeSlotsAlive(nodes);
                //Check to see if we have enough slots before trying to get them
                int slotsAvailable = 0;
                if (slotsRequested > slotsFree) {
                    slotsAvailable = NodePool.slotsAvailable(lesserPools);
                }
                int slotsToUse = Math.min(slotsRequested - slotsUsed, slotsFree + slotsAvailable);
                int executorsNotRunning = cluster.getUnassignedExecutors(td).size();
                LOG.debug("Slots... requested {} used {} free {} available {} to be used {}, executors not running {}",
                          slotsRequested, slotsUsed, slotsFree, slotsAvailable, slotsToUse, executorsNotRunning);
                if (slotsToUse <= 0) {
                    if (executorsNotRunning > 0) {
                        cluster.setStatus(topId, "Not fully scheduled (No free slots in default pool) "
                                + executorsNotRunning
                                + " executors not scheduled");
                    } else {
                        if (slotsUsed < slotsRequested) {
                            cluster.setStatus(topId, "Running with fewer slots than requested ("
                                    + slotsUsed + "/"
                                    + origRequest + ")");
                        } else { //slotsUsed < origRequest
                            cluster.setStatus(topId,
                                    "Fully Scheduled (requested " + origRequest
                                            + " slots, but could only use " + slotsUsed + ")");
                        }
                    }
                    continue;
                }

                int slotsNeeded = slotsToUse - slotsFree;
                if (slotsNeeded > 0) {
                    nodes.addAll(NodePool.takeNodesBySlot(slotsNeeded, lesserPools));
                }

                if (executorsNotRunning <= 0) {
                    //There are free slots that we can take advantage of now.
                    for (Node n : nodes) {
                        n.freeTopology(topId, cluster);
                    }
                    slotsFree = Node.countFreeSlotsAlive(nodes);
                    slotsToUse = Math.min(slotsRequested, slotsFree);
                }

                RoundRobinSlotScheduler slotSched =
                    new RoundRobinSlotScheduler(td, slotsToUse, cluster);

                LinkedList<Node> nodes = new LinkedList<>(this.nodes);
                while (true) {
                    Node n;
                    do {
                        if (nodes.isEmpty()) {
                            throw new IllegalStateException("This should not happen, we"
                                    + " messed up and did not get enough slots");
                        }
                        n = nodes.peekFirst();
                        if (n.totalSlotsFree() == 0) {
                            nodes.remove();
                            n = null;
                        }
                    } while (n == null);
                    if (!slotSched.assignSlotTo(n)) {
                        break;
                    }
                }
                int afterSchedSlotsUsed = Node.countSlotsUsed(topId, this.nodes);
                if (afterSchedSlotsUsed < slotsRequested) {
                    cluster.setStatus(topId, "Running with fewer slots than requested ("
                            + afterSchedSlotsUsed + "/" + origRequest + ")");
                } else if (afterSchedSlotsUsed < origRequest) {
                    cluster.setStatus(topId,
                            "Fully Scheduled (requested "
                                    + origRequest
                                    + " slots, but could only use "
                                    + afterSchedSlotsUsed
                                    + ")");
                } else {
                    cluster.setStatus(topId, "Fully Scheduled");
                }
            } else {
                cluster.setStatus(topId, "Fully Scheduled");
            }
        }
    }

    @Override
    public String toString() {
        return "DefaultPool  " + nodes.size() + " nodes " + tds.size() + " topologies";
    }
}


text:
// Copyright 1997 Association for Universities for Research in Astronomy, Inc.,
// Observatory Control System, Gemini Telescopes Project.
// See the file LICENSE for complete details.
//
// $Id: ScreenMath.java 4725 2004-05-14 16:32:54Z brighton $
//
package jsky.app.ot.util;

import edu.gemini.spModel.util.Angle;

import java.awt.geom.Point2D;

/**
 * Routines for dealing with screen coordinates.
 */
public class ScreenMath {

    /**
     * Rotate a point through a given angle about a given point.
     */
    public static Point2D.Double rotateRadians(double x, double y, double angle, double xBase, double yBase) {
        if (angle == 0.0) {
            return new Point2D.Double(x, y);
        }

        // Translate x,y to be relative to the origin, where y is increasing
        // toward the top instead of toward the bottom.
        double x0 = x - xBase;
        double y0 = yBase - y;

        // Rotate the point and translate it back.
        double sin = Angle.sinRadians(angle);
        double cos = Angle.cosRadians(angle);

        x = xBase + (x0 * cos - y0 * sin);
        y = yBase - (x0 * sin + y0 * cos);

        return new Point2D.Double(x, y);
    }

    /**
     * Rotate a polygon through a given angle about a given point.
     */
    public static void rotateRadians(PolygonD p, double angle, double xBase, double yBase) {
        if (angle == 0.0) {
            return;
        }

        // Remember the sin and cos of the angle.
        double sin = Angle.sinRadians(angle);
        double cos = Angle.cosRadians(angle);

        // Rotate each point.
        for (int i = 0; i < p.npoints; ++i) {
            // Translate the point to be relative to the origin, and make y
            // increase toward the top instead of toward the bottom.
            double x0 = p.xpoints[i] - xBase;
            double y0 = yBase - p.ypoints[i];

            // Rotate the point and translate it back.
            p.xpoints[i] = xBase + (x0 * cos - y0 * sin);
            p.ypoints[i] = yBase - (x0 * sin + y0 * cos);
        }
    }

}


text:
li.active{font-weight:bold;}
#articles .card-heading a {color: #229f24!important}
.div-tags{line-height:30px;}
.input-group{margin-bottom: 18px;}
.input-group-btn a.btn{border-radius: 0 4px 4px 0;}