text:
<!--
  #%L
  fast-persistent-queue
  %%
  Copyright (C) 2014 btoddb.com
  %%
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  #L%
  -->
<assembly>
    <!--<id>chronicle</id>-->
    <formats>
        <format>tar.gz</format>
    </formats>

    <includeBaseDirectory>false</includeBaseDirectory>

    <dependencySets>
        <dependencySet>
            <!-- include dependencies of our dependencies -->
            <useTransitiveDependencies>true</useTransitiveDependencies>

            <unpack>false</unpack>

            <useProjectArtifact>true</useProjectArtifact>

            <outputDirectory>lib</outputDirectory>
        </dependencySet>
    </dependencySets>

    <fileSets>
        <fileSet>
            <directory>src/main/scripts</directory>
            <outputDirectory>.</outputDirectory>
            <fileMode>0755</fileMode>
        </fileSet>

        <fileSet>
            <directory>conf</directory>
            <outputDirectory>conf</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>


text:
void poweroff();

#endif

redpajama_set_name: RedPajamaGithub


text:
title: Sean Foust
---

@@include('../../templates/_head-team.tpl')

  @@include('../../templates/_homenav.tpl')

Sean Foust

Operations

SUPPORTS

                  EFF
                  Project Loon

CONTRIBUTES TO

                  Growing Food, Growing Health
                  Greenstar Coop

CONNECT

                      <svg viewBox="0 0 20 20" class="ico-social">
                        <use xlink:href="/assets/img/ico-social.svg#ico-facebook"></use>
                      </svg>

                      <svg viewBox="0 0 20 20" class="ico-social">
                        <use xlink:href="/assets/img/ico-social.svg#ico-linkedin"></use>
                      </svg>

Sean Foust has a passion for social entrepreneurship. He is inspired by the opportunity in business to propel environmental sustainability and social change. This opportunity is particularly vivid in the tech industry. Sean views the tech landscape as a kind of social change primordial soup, teeming with potentiality for positive growth.

Sean taught himself about technology when he was a child, partially through experimenting on an Apple IIc and partially through pestering his older brother who was learning to code on their family's Linux box. In addition to his propensity for tech, Sean has a knack for organization, creative problem solving and research projects, skills which support CoLab's internal operations. He is entering his 7th year working with cooperatives.

His passions include healthcare advocacy, green energy and permaculture design. When he isn't helping CoLab thrive, Sean spends his time listening to live music, hiking, camping, wildcrafting, kayaking, and doing all those things with the people that he loves.

  @@include('../../templates/_footer.tpl')

  @@include('../../templates/_tail.tpl')


text:
package org.batfish.coordinator;

import static javax.ws.rs.core.Response.Status.OK;
import static javax.ws.rs.core.Response.Status.UNAUTHORIZED;
import static org.batfish.common.CoordConstsV2.HTTP_HEADER_BATFISH_APIKEY;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import org.batfish.common.CoordConsts;
import org.batfish.coordinator.authorizer.Authorizer;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Before;
import org.junit.Test;

/** Tests for {@link ApiKeyAuthenticationFilter}. */
public class ApiKeyAuthenticationFilterTest extends JerseyTest {

  @Path("/test")
  public static class TestService {
    @GET
    public Response get() {
      return Response.ok().build();
    }
  }

  private static class TestAuthorizer implements Authorizer {

    @Override
    public void authorizeContainer(String apiKey, String containerName) {}

    @Override
    public boolean isAccessibleNetwork(String apiKey, String containerName, boolean logError) {
      return false;
    }

    @Override
    public boolean isValidWorkApiKey(String apiKey) {
      return apiKey.equals(CoordConsts.DEFAULT_API_KEY);
    }
  }

  @Before
  public void initAuthorizer() {
    Main.setAuthorizer(new TestAuthorizer());
  }

  @Override
  protected Application configure() {
    forceSet(TestProperties.CONTAINER_PORT, "0");
    return new ResourceConfig(TestService.class).register(ApiKeyAuthenticationFilter.class);
  }

  @Test
  public void testEmptyApiKey() {
    try (Response response =
        target("/test").request().header(HTTP_HEADER_BATFISH_APIKEY, "").get()) {
      assertThat(response.getStatus(), equalTo(UNAUTHORIZED.getStatusCode()));
      assertThat(
          response.readEntity(String.class),
          equalTo("HTTP header " + HTTP_HEADER_BATFISH_APIKEY + " should contain an API key"));
    }
  }

  @Test
  public void testDefaultKeyWhenApiKeyIsMissing() {
    try (Response response = target("/test").request().get()) {
      assertThat(response.getStatus(), equalTo(OK.getStatusCode()));
    }
  }

  @Test
  public void testUnauthorizedApiKey() {
    try (Response response =
        target("/test").request().header(HTTP_HEADER_BATFISH_APIKEY, "100").get()) {
      assertThat(response.getStatus(), equalTo(UNAUTHORIZED.getStatusCode()));
      String expectMessage = "Authorizer: '100' is NOT a valid key";
      assertThat(response.readEntity(String.class), equalTo(expectMessage));
    }
  }

  @Test
  public void testValidApiKey() {
    try (Response response =
        target("/test")
            .request()
            .header(HTTP_HEADER_BATFISH_APIKEY, CoordConsts.DEFAULT_API_KEY)
            .get()) {
      assertThat(response.getStatus(), equalTo(OK.getStatusCode()));
    }
  }
}


text:
require File.dirname(__FILE__) + '/spec_helper.rb'

describe 'airbrush' do

  it 'should add a log method to object' do
    Object.should respond_to(:log)
  end

end


text:
ajordens
asher
cfieber
robzienert


text:
import re
import json
import sublime

from ..utils import Debug
from ..utils.uiutils import get_prefix
from ..utils.viewutils import get_file_infos, get_content_of_line_at

# IS AN OBJECT MEMBER
# TRUE: line=Instance. or line=Instance.fooba or line=Instance.foobar.alic
# FALSE: line=Inst
js_id_re = re.compile(u'^[_$a-zA-Z\u00FF-\uFFFF][_$a-zA-Z0-9\u00FF-\uFFFF]*')
def is_member_completion(line_text):
    def partial_completion():
        sp = line_text.split(".")
        if len(sp) > 1:
            return js_id_re.match(sp[-1]) is not None
        return False
    return line_text.endswith(".") or partial_completion()

def get_col_after_last_dot(line_text):
    return line_text.rfind(".") + 1

class Completion(object):

    completion_chars = ['.']#['.',':']
    completion_list = []
    interface = False
    enabled_for_col_reference = ''     # 'dot' or 'cursor'
    enabled_for = {'line': 0, 'col': 0, 'viewid': -1}

    def __init__(self, project):
        self.project = project

    # PREPARE LISTE
    def prepare_list(self, tss_result_json):
        del self.completion_list[:]

        try:
            entries = json.loads(tss_result_json)
            entries = entries['entries']
        except:
            if tss_result_json.strip() == 'null':
                sublime.status_message('ArcticTypescript: no completions available')
            else:
                Debug('error', 'Completion request failed: %s' % tss_result_json)
            return 0

        for entry in entries:
            if self.interface and entry['kind'] != 'primitive type' and entry['kind'] != 'interface' : continue
            key = self._get_list_key(entry)
            value = self._get_list_value(entry)
            self.completion_list.append((key,value))

        self.completion_list.sort()
        return len(self.completion_list)

    # GET LISTE
    def get_list(self):
        return self.completion_list

    # TYPESCRIPT COMPLETION ?
    def trigger(self, view, force_enable=False):

        cursor_pos = view.sel()[0].begin() # cursor pos as int
        (cursor_line, cursor_col) = view.rowcol(cursor_pos)

        char = view.substr(cursor_pos-1)

        enabled = force_enable or (char in self.completion_chars)
        self.interface = char is ':'

        if enabled:
            Debug('autocomplete', "Autocompletion for line %i , %i, forced=%s" % (cursor_line+1, cursor_col+1, force_enable) )

            is_member = is_member_completion( get_content_of_line_at(view, cursor_pos) )
            is_member_str = str( is_member ).lower() # 'true' or 'false'

            # do execute tss.js complete for cursor positon after last dot, so we use
            # sublimes fuzzy mechanism to reduce the list, not the mechanism
            # (1:1 matching of the typed chars) tss.js would use

            autocomplete_col = 0

            if is_member:
                autocomplete_col = get_col_after_last_dot( get_content_of_line_at(view, cursor_pos) )
                self.enabled_for_col_reference = 'dot'
                Debug('autocomplete', " -> use dot as referene")
                if autocomplete_col != cursor_col:
                    Debug('autocomplete', " -> dot is on col %i, use this col instead of cursor position %i" % (autocomplete_col+1, cursor_col+1))
            else:
                Debug('autocomplete', " -> use cursor position %i for autocomplete" % (cursor_col+1))
                self.enabled_for_col_reference = 'cursor'
                autocomplete_col = cursor_col

            self.enabled_for['viewid'] = view.id()
            self.enabled_for['line'] = cursor_line
            self.enabled_for['col'] = autocomplete_col

            Debug('autocomplete', " -> push current file contents as update to tss.js")
            self.project.tsserver.update(view)

            def async_react_completions_available(tss_result_json, filename, line, col, is_member_str):
                Debug('autocomplete', "Autocompletion results available for line %i , %i" % (line+1, col+1) )

                i = self.prepare_list(tss_result_json)
                Debug('autocomplete', " -> prepare List (%i items)" % i )

                # view or line changed
                current_view = sublime.active_window().active_view()
                current_cursor_pos = current_view.sel()[0].begin()
                (current_cursor_line, current_cursor_col) = current_view.rowcol(current_cursor_pos)

                Debug('autocomplete', " => CL: {0}, L: {1}, efcr: {2}, ccc: {3}, col: {4}, ismstr: {5}"
                        .format(current_cursor_line,
                                line,
                                self.enabled_for_col_reference,
                                current_cursor_col,
                                col,
                                is_member_str))

                if current_view.id() != self.enabled_for['viewid'] or filename != current_view.file_name():
                    Debug('autocomplete', " -> file changed since activation of autocomplete or out-dated request -> cancel")
                    return
                if current_cursor_line != self.enabled_for['line'] or current_cursor_line != line:
                    Debug('autocomplete', " -> line changed since start of autocomplete (%i to %i) or out-dated request -> cancel" % (current_cursor_line, line) )
                    return
                if self.enabled_for_col_reference == 'cursor' \
                    and (current_cursor_col != self.enabled_for['col'] or current_cursor_col != col):
                    Debug('autocomplete', " -> cursor changed position (current col: %i ; at command issue: %i) or out-dated request -> cancel" % (current_cursor_col, col) )
                    return

                if is_member_str == 'true':
                    current_dot_col = get_col_after_last_dot( get_content_of_line_at(view, current_cursor_pos) )
                    if self.enabled_for_col_reference == 'dot' \
                        and (current_dot_col != self.enabled_for['col'] or current_dot_col != col):
                        Debug('autocomplete', " -> it's not the same dot reference anymore (current dot pos: %i ; at command issue: %i) or out-dated request -> cancel" % (current_dot_col, col) )
                        return

                Debug('autocomplete', " -> command to sublime to now show autocomplete box with prepared list" )

                # this will trigger Listener.on_query_completions
                # but on_query_completions needs to have the completion list
                # already available
                current_view.run_command('auto_complete',{
                    'disable_auto_insert': True,
                    'api_completions_only': True,
                    'next_completion_if_showing': True
                })
                Debug('autocomplete', " -> (sublime cmd finished)" )

            self.project.tsserver.complete(view.file_name(), cursor_line, autocomplete_col, is_member_str, async_react_completions_available)

    # ENTRY KEY
    def _get_list_key(self,entry):

        #{'name': 'SVGLineElement',
        # 'kind': 'var',
        # 'kindModifiers': 'declare',
        # 'type': 'interface SVGLineElement\nvar SVGLineElement: {\n    new (): SVGLineElement;\n    prototype: SVGLineElement;\n}',
        # 'docComment': ''}

        kindModifiers = get_prefix(entry['kindModifiers'])
        kind = get_prefix(entry['kind'])
        type_ = entry['type'] if 'type' in entry else entry['name']
        type_ = type_.split('\n')[0]

        if kindModifiers == "" and kind == "":
            kind = get_prefix(type_.split(' ')[0])

        return kindModifiers+' '+kind+' '+str(entry['name'])+' '+str(type_)

    # ENTRY VALUE
    def _get_list_value(self,entry):

        # {'kind': 'method', 'docComment': '', 'kindModifiers': 'declare', 'type': '(method) MSNodeExtensions.swapNode(otherNode: Node): Node', 'name': 'swapNode'}
        # {'kind': 'property', 'docComment': '', 'kindModifiers': 'declare', 'type': '(property) GlobalEventHandlers.onpointerup: (ev: PointerEvent) => any', 'name': 'onpointerup'}
        # {'kind': 'property', 'docComment': '', 'kindModifiers': 'declare', 'type': '(property) Node.DOCUMENT_TYPE_NODE: number', 'name': 'DOCUMENT_TYPE_NODE'}
        # {'kind': 'method', 'docComment': 'Allows updating the print settings for the page.', 'kindModifiers': 'declare', 'type': '(method) Document.updateSettings(): void', 'name': 'updateSettings'}
        # {'kindModifiers': 'declare', 'docComment': '', 'kind': 'function', 'name': 'setTimeout', 'type': '(function) setTimeout(handler: any, timeout?: any, ...args: any[]): number'}

        type_ = entry['type'] if 'type' in entry else entry['name']

        # remove (<kind>)
        kind_part = "(%s)" % entry['kind']
        if type_.startswith(kind_part):
            type_ = type_[len(kind_part):]

        # catches the inner argumetns of a function call
        match = re.match('.*\((.*)\):', str(type_))
        result = []

        if match:
            variables = self._parse_args(match.group(1))
            count = 1
            for variable in variables:
                splits = variable.split(':')
                if len(splits) > 1:
                    data = '"'+variable+'"'
                    data = '${'+str(count)+':'+data+'}'
                    result.append(data)
                    count = count+1
                else:
                    result.append('')

            return re.escape(entry['name'])+'('+','.join(result)+')'
        else:
            return re.escape(entry['name'])

    # PARSE FUNCTION ARGUMENTS
    def _parse_args(self, group):
        # group = "otherNode: Node, param2: string"
        args = []
        arg = ""
        callback = False

        for char in group:
            if char == '(' or char == '<':
                arg += char
                callback = True
            elif char == ')' or char == '>':
                arg += char
                callback = False
            elif char == ',':
                if callback == False:
                    args.append(arg)
                    arg = ""
                else:
                    arg+=char
            else:
                arg+=char

        args.append(arg)
        return args


text:
<!DOCTYPE html>

    <title>ResultsController Protocol Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>
	<meta name="viewport" content="width=device-width, viewport-fit=cover, initial-scale=1.0" />

          CollectionView Docs
           (63% documented)

            View on GitHub

            CollectionView Reference

          ResultsController Protocol Reference

ResultsController

public protocol ResultsController : AnyObject

A ResultsController manages data in a way that is usable by a collection view.

FetchedResultsController

RelationalResultsController

                      delegate

The delegate to notify about data changes

Declaration

Swift

var delegate: ResultsControllerDelegate? { get set }

                      numberOfSections

The number of sections in the results controller

Declaration

Swift

var numberOfSections: Int { get }

                      numberOfObjects(in:)

Returns the number of objects in the specified section

Declaration

Swift

func numberOfObjects(in section: Int) -> Int

Parameters

                                  section

The section for which to count the objects

Return Value

The number of objects

                      sectionName(forSectionAt:)

The name of the section at the specfied section

Note

The object represented by the section must adopt CustomDisplayStringConvertible, otherwise this returns an empty string

Declaration

Swift

func sectionName(forSectionAt indexPath: IndexPath) -> String

Return Value

A string representing the name of the section

                      reset()

Clear all storage for the controller and stop all observing

Declaration

Swift

func reset()

              Guides

                  Introduction

                  Basic Setup

                  Supplementary Views

                  Layouts

                  Drag & Drop

                  Content Updates

                  Results Controller

              Collection View

                  CollectionView

                  – SelectionMode

                  CollectionViewDataSource

                  CollectionViewDelegate

                  CollectionViewDragDelegate

                  CollectionViewCell

                  CollectionReusableView

                  CollectionViewController

                  CollectionViewLayoutElementKind

                  CollectionElementCategory

                  CollectionViewDirection

                  CollectionViewScrollDirection

                  CollectionViewScrollPosition

                  CollectionViewPreviewCell

                  CollectionViewPreviewController

                  CollectionViewPreviewTransitionCell

                  CollectionViewPreviewControllerDelegate

                  AnimationCompletion

              Collection View Layouts

                  CollectionViewLayout

                  CollectionViewLayoutAttributes

                  CollectionViewListLayout

                  CollectionViewDelegateListLayout

                  CollectionViewColumnLayout

                  – LayoutStrategy

                  CollectionViewDelegateColumnLayout

                  CollectionViewFlowLayout

                  – RowTransform

                  – ItemStyle

                  CollectionViewDelegateFlowLayout

                  CollectionViewHorizontalListLayout

                  CollectionViewDelegateHorizontalListLayout

              Results Controller

                  ResultsController

                  ResultsControllerDelegate

                  MutableResultsController

                  FetchedResultsController

                  RelationalResultsController

                  FetchedSetController

                  ResultsControllerChangeType

                  ResultsControllerError

                  CollectionViewProvider

                  CollectionViewResultsProxy

              Other Enumerations

                  SortDescriptorResult

              Other Extensions

                  IndexPath

              Other Protocols

                  CustomDisplayStringConvertible

              Other Structures

                  SortDescriptor

© 2018 Noun Project. All rights reserved. (Last updated: 2018-10-16)

Generated by jazzy ♪♫ v0.9.3, a Realm project.


text:
"use strict";
var config_1 = require('../util/config');
var copy_1 = require('../copy');
var path = require('path');
describe('copy', function () {
    describe('findFileCopyOptions', function () {
        it('should find copy option for a file in a directory', function () {
            var context = config_1.generateContext();
            var filePath = 'src/assets/some.jpg';
            var copyOptions = copy_1.findFileCopyOptions(context, copyConfig, filePath);
            expect(copyOptions.length).toEqual(1);
            expect(copyOptions[0].src).toEqual(path.join(context.rootDir, filePath));
            expect(copyOptions[0].dest).toEqual(path.join(context.rootDir, filePath).replace('src', 'www'));
        });
        it('should find copy option for an exact file', function () {
            var context = config_1.generateContext();
            var filePath = 'src/index.html';
            var copyOptions = copy_1.findFileCopyOptions(context, copyConfig, filePath);
            expect(copyOptions.length).toEqual(1);
            expect(copyOptions[0].src).toEqual(path.join(context.rootDir, filePath));
            expect(copyOptions[0].dest).toEqual(path.join(context.rootDir, filePath).replace('src', 'www'));
        });
        it('should not find any copy options', function () {
            var context = config_1.generateContext();
            var filePath = 'src/idk.json';
            var copyOptions = copy_1.findFileCopyOptions(context, copyConfig, filePath);
            expect(copyOptions.length).toEqual(0);
        });
    });
    var copyConfig = {
        include: [
            {
                src: '{{SRC}}/assets/',
                dest: '{{WWW}}/assets/'
            },
            {
                src: '{{SRC}}/index.html',
                dest: '{{WWW}}/index.html'
            },
            {
                src: '{{SRC}}/manifest.json',
                dest: '{{WWW}}/manifest.json'
            },
            {
                src: '{{SRC}}/service-worker.js',
                dest: '{{WWW}}/service-worker.js'
            },
            {
                src: 'node_modules/ionic-angular/polyfills/polyfills.js',
                dest: '{{BUILD}}/polyfills.js'
            },
            {
                src: 'node_modules/ionicons/dist/fonts/',
                dest: '{{WWW}}/assets/fonts/'
            },
        ]
    };
});


text:
package org.onetwo.ext.rocketmq.consumer;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.onetwo.ext.rocketmq.consumer.RocketMQPushConsumerStarter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

//@ContextConfiguration("classpath:applicationContext-mq-es-test.xml")
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=MQConsumerContextTestConfig.class)
public class MQConsumerTest  {

	@Autowired
	private RocketMQPushConsumerStarter starter;
	@Test
	public void test() throws Exception{
		System.out.println("starting...");
		System.in.read();
		starter.destroy();
	}

}


text:
describe('Dataset upload tile directive', function () {
	var scope;
	var createElement;
	const translations = {
		UPLOAD_PROCESSING: 'Profiling data, please wait...',
	};

	beforeEach(angular.mock.module('data-prep.dataset-upload-status'));

	beforeEach(angular.mock.module('pascalprecht.translate', function ($translateProvider) {
		$translateProvider.translations('en', translations);
		$translateProvider.preferredLanguage('en');
	}));

	beforeEach(inject(function ($rootScope, $compile) {
		scope = $rootScope.$new();
		createElement = function (directiveScope) {
			var element = angular.element('<dataset-upload-status dataset="dataset"></dataset-upload-status>');
			$compile(element)(directiveScope);
			directiveScope.$digest();
			return element;
		};
	}));

	it('should render progress bar while uploading new dataset file', function () {
		// given
		scope.dataset = {
			name: 'Customers (50 lines)',
			progress: 10,
			error: false,
			type: 'file'
		};

		// when
		var element = createElement(scope);
		var name = element.find('.inventory-title').first();
		var progress = element.find('.inventory-progress').first();

		// then
		expect(name.text()).toBe('Customers (50 lines)');
		expect(progress.find('pure-progress')).toBeDefined();
		expect(progress.hasClass('error')).toBe(false);
	});

	it('should render progressing remote dataset import', function () {
		//given
		scope.dataset = {
			name: 'remote 1',
			progress: 0,
			error: false,
			type: 'remote',
		};

		//when
		var element = createElement(scope);
		var name = element.find('.inventory-title').first();
		var progress = element.find('.inventory-progress').first();

		//then
		expect(name.text()).toBe('remote 1');
		expect(progress.hasClass('error')).toBe(false);
	});

	it('should render upload error dataset', function () {
		//given
		scope.dataset = {
			name: 'Customers (50 lines)',
			progress: 10,
			error: true,
		};

		//when
		var element = createElement(scope);
		var name = element.find('.inventory-title').first();
		var progress = element.find('.inventory-progress').first();

		//then
		expect(name.text()).toBe('Customers (50 lines)');
		expect(progress.text().trim()).not.toBe('10 %');
		expect(progress.hasClass('error')).toBe(true);
	});
});


text:
export * from './article.component';
export * from './articles.component';


text:
package org.alien4cloud.git;

import javax.inject.Inject;
import javax.inject.Named;

import org.alien4cloud.git.model.GitLocation;
import org.springframework.stereotype.Component;

import alien4cloud.dao.IGenericSearchDAO;

@Component
public class GitLocationDao {

    @Inject
    @Named("alien-es-dao")
    private IGenericSearchDAO alienDao;
    @Inject
    private GitLocationService gitLocationService;

    public GitLocation findById(String id) {
        return alienDao.findById(GitLocation.class, id);
    }

    public GitLocation findDeploymentSetupLocation(String applicationId, String environmentId) {
        String id = GitLocation.IdBuilder.forDeploymentSetup(applicationId, environmentId);

        // does a remote git has been configured ?
        GitLocation gitLocation = alienDao.findById(GitLocation.class, id);
        if (gitLocation == null) {
            // return alien managed git
            gitLocation = gitLocationService.getDeploymentSetupLocalGitLocation(applicationId, environmentId);
        }

        return gitLocation;
    }

    public GitLocation findApplicationVariablesLocation(String applicationId) {
        String id = GitLocation.IdBuilder.forApplicationVariables(applicationId);

        // does a remote git has been configured ?
        GitLocation gitLocation = alienDao.findById(GitLocation.class, id);
        if (gitLocation == null) {
            // return alien managed git
            gitLocation = gitLocationService.getApplicationVariablesLocalGitLocation(applicationId);
        }

        return gitLocation;
    }

    public void save(GitLocation location) {
        alienDao.save(location);
    }

    public void delete(String id) {
        alienDao.delete(GitLocation.class, id);
    }
}


text:
package com.github.tinosteinort.beanrepository.example._02_eventexample;

import com.github.tinosteinort.beanrepository.BeanRepository;
import com.github.tinosteinort.beanrepository.BeanRepositoryApplication;
import com.github.tinosteinort.beanrepository.BeanRepositoryConfigurator;
import com.github.tinosteinort.beanrepository.application.event.ApplicationEventBus;

/**
 * This sample shows
 *    * how to use an own event (listen to and fire)
 *    * different ways to register listeners
 *    * how to get notified for an application shutdown
 */
public class EventExampleApp implements BeanRepositoryConfigurator {

    public static void main(String[] args) {

        BeanRepositoryApplication.run(args, new EventExampleApp());
    }

    @Override
    public void configure(BeanRepository.BeanRepositoryBuilder builder) {

        builder
                .singleton(StartupListener.class, StartupListener::new, ApplicationEventBus.class)
                .singleton(ShutdownListener.class, ShutdownListener::new)

                // Concrete listener
                .singleton(PizzaTimeListener.class, PizzaTimeListener::new)

                // This bean registers an anonymous listener within its onPostConstruct method!
                .singleton(HungryPerson.class, HungryPerson::new, ApplicationEventBus.class);
    }
}


text:
package com.opengamma.master.marketdatasnapshot;

import java.util.Comparator;

import com.opengamma.util.PublicSPI;

/**
 * Available sort orders for market data snapshot.
 */
@PublicSPI
public enum MarketDataSnapshotSearchSortOrder implements Comparator<MarketDataSnapshotDocument> {
  // this design is simple and perhaps not ideal, but it is effective for most use cases at the moment

  /**
   * Sort by object id ascending.
   */
  OBJECT_ID_ASC {
    @Override
    public int compare(final MarketDataSnapshotDocument obj1, final MarketDataSnapshotDocument obj2) {
      return obj1.getObjectId().compareTo(obj2.getObjectId());
    }
  },
  /**
   * Sort by object id ascending.
   */
  OBJECT_ID_DESC {
    @Override
    public int compare(final MarketDataSnapshotDocument obj1, final MarketDataSnapshotDocument obj2) {
      return obj2.getObjectId().compareTo(obj1.getObjectId());
    }
  },
  /**
   * Sort by version from instant ascending.
   */
  VERSION_FROM_INSTANT_ASC {
    @Override
    public int compare(final MarketDataSnapshotDocument obj1, final MarketDataSnapshotDocument obj2) {
      return obj1.getVersionFromInstant().compareTo(obj2.getVersionFromInstant());
    }
  },
  /**
   * Sort by version from instant descending.
   */
  VERSION_FROM_INSTANT_DESC {
    @Override
    public int compare(final MarketDataSnapshotDocument obj1, final MarketDataSnapshotDocument obj2) {
      return obj2.getVersionFromInstant().compareTo(obj1.getVersionFromInstant());
    }
  },
  /**
   * Sort by name ascending.
   */
  NAME_ASC {
    @Override
    public int compare(final MarketDataSnapshotDocument obj1, final MarketDataSnapshotDocument obj2) {
      return obj1.getName().compareTo(obj2.getName());
    }
  },
  /**
   * Sort by name descending.
   */
  NAME_DESC {
    @Override
    public int compare(final MarketDataSnapshotDocument obj1, final MarketDataSnapshotDocument obj2) {
      return obj2.getName().compareTo(obj1.getName());
    }
  };

}


text:
//
//  WBSHorizonalTableViewController.m
//  WBSBlog
//
//  Created by Weberson on 16/7/20.
//  Copyright © 2016年 Weberson. All rights reserved.
//

#import "WBSHorizonalTableViewController.h"
#import "UIColor+Config.h"

@interface WBSHorizonalTableViewController ()

@end

static NSString *kHorizonalCellID = @"HorizonalCell";

@implementation WBSHorizonalTableViewController

- (instancetype)initWithViewControllers:(NSArray *)controllers
{
    self = [super init];
    if (self) {
        _controllers = controllers;
        for (UIViewController *controller in controllers) {
            [self addChildViewController:controller];
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

//    /***** 为解决iPhone 6 下的popviewcontroller后的问题而做的无奈之举,这样会引入新的问题,very ugly,亟待解决 *****/
    self.tableView = [[UITableView alloc]init];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollsToTop = NO;
    self.tableView.transform = CGAffineTransformMakeRotation(-M_PI_2);
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.pagingEnabled = YES;
    self.tableView.backgroundColor = [UIColor themeColor];
    self.tableView.bounces = NO;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kHorizonalCellID];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _controllers.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return tableView.frame.size.width;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kHorizonalCellID forIndexPath:indexPath];
    cell.contentView.transform = CGAffineTransformMakeRotation(M_PI_2);
    cell.contentView.backgroundColor = [UIColor themeColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    UIViewController *controller = _controllers[indexPath.row];
    controller.view.frame = cell.contentView.bounds;
    [cell.contentView addSubview:controller.view];

    return cell;
}

#pragma mark - <UIScrollViewDelegate>

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollStop:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self scrollStop:NO];
}

#pragma mark -

- (void)scrollToViewAtIndex:(NSUInteger)index
{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]
                          atScrollPosition:UITableViewScrollPositionNone
                                  animated:NO];

    if (_viewDidAppear) {
        _viewDidAppear(index);
    }
}

- (void)scrollStop:(BOOL)didScrollStop
{
    CGFloat horizonalOffset = self.tableView.contentOffset.y;
    CGFloat screenWidth = self.tableView.frame.size.width;
    CGFloat offsetRatio = (NSUInteger)horizonalOffset % (NSUInteger)screenWidth / screenWidth;
    NSUInteger focusIndex = (horizonalOffset + screenWidth / 2) / screenWidth;

    if (horizonalOffset != focusIndex * screenWidth) {
        NSUInteger animationIndex = horizonalOffset > focusIndex * screenWidth ? focusIndex + 1: focusIndex - 1;
        if (focusIndex > animationIndex) {offsetRatio = 1 - offsetRatio;}
        _scrollView(offsetRatio, focusIndex, animationIndex);
    }

    if (didScrollStop) {
        /*
         [_controllers enumerateObjectsUsingBlock:^(UIViewController *vc, NSUInteger idx, BOOL *stop) {
         if ([vc isKindOfClass:[UITableViewController class]]) {
         ((UITableViewController *)vc).tableView.scrollsToTop = (idx == focusIndex);
         }
         }];
         */

        _changeIndex(focusIndex);
    }
}

@end


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

<TITLE>
ch.unifr.pai.twice.widgets.mpproxyframe.client
</TITLE>

<META NAME="date" CONTENT="2013-03-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package ch.unifr.pai.twice.widgets.mpproxyframe.client

Class Summary

ComplexMPFrame
A more complex widget providing control mechanisms for a MPFrame

Controller
Implementation of a very basic onscreen keyboard interacting with the MPFrame

MPFrame
A specific IFrame that provides multipointer browsing functionalities

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
namespace blink {

static void throwExceptionIfMediaKeyExceptionOccurred(const String& keySystem, const String& sessionId, WebMediaPlayer::MediaKeyException exception, ExceptionState& exceptionState)
{
    switch (exception) {
    case WebMediaPlayer::MediaKeyExceptionNoError:
        return;
    case WebMediaPlayer::MediaKeyExceptionInvalidPlayerState:
        exceptionState.throwDOMException(InvalidStateError, "The player is in an invalid state.");
        return;
    case WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported:
        exceptionState.throwDOMException(NotSupportedError, "The key system provided ('" + keySystem +"') is not supported.");
        return;
    case WebMediaPlayer::MediaKeyExceptionInvalidAccess:
        exceptionState.throwDOMException(InvalidAccessError, "The session ID provided ('" + sessionId + "') is invalid.");
        return;
    }

    ASSERT_NOT_REACHED();
    return;
}

HTMLMediaElementEncryptedMedia::HTMLMediaElementEncryptedMedia()
    : m_emeMode(EmeModeNotSelected)
{
}

DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(HTMLMediaElementEncryptedMedia)

const char* HTMLMediaElementEncryptedMedia::supplementName()
{
    return "HTMLMediaElementEncryptedMedia";
}

HTMLMediaElementEncryptedMedia& HTMLMediaElementEncryptedMedia::from(HTMLMediaElement& element)
{
    HTMLMediaElementEncryptedMedia* supplement = static_cast<HTMLMediaElementEncryptedMedia*>(WillBeHeapSupplement<HTMLMediaElement>::from(element, supplementName()));
    if (!supplement) {
        supplement = new HTMLMediaElementEncryptedMedia();
        provideTo(element, supplementName(), adoptPtrWillBeNoop(supplement));
    }
    return *supplement;
}

bool HTMLMediaElementEncryptedMedia::setEmeMode(EmeMode emeMode, ExceptionState& exceptionState)
{
    if (m_emeMode != EmeModeNotSelected && m_emeMode != emeMode) {
        exceptionState.throwDOMException(InvalidStateError, "Mixed use of EME prefixed and unprefixed API not allowed.");
        return false;
    }
    m_emeMode = emeMode;
    return true;
}

WebContentDecryptionModule* HTMLMediaElementEncryptedMedia::contentDecryptionModule()
{
    return m_mediaKeys ? m_mediaKeys->contentDecryptionModule() : 0;
}

MediaKeys* HTMLMediaElementEncryptedMedia::mediaKeys(HTMLMediaElement& element)
{
    HTMLMediaElementEncryptedMedia& thisElement = HTMLMediaElementEncryptedMedia::from(element);
    return thisElement.m_mediaKeys.get();
}

void HTMLMediaElementEncryptedMedia::setMediaKeysInternal(HTMLMediaElement& element, MediaKeys* mediaKeys)
{
    if (m_mediaKeys == mediaKeys)
        return;

    ASSERT(m_emeMode == EmeModeUnprefixed);
    m_mediaKeys = mediaKeys;

    // If a player is connected, tell it that the CDM has changed.
    if (element.webMediaPlayer())
        element.webMediaPlayer()->setContentDecryptionModule(contentDecryptionModule());
}

void HTMLMediaElementEncryptedMedia::setMediaKeys(HTMLMediaElement& element, MediaKeys* mediaKeys, ExceptionState& exceptionState)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::setMediaKeys");
    HTMLMediaElementEncryptedMedia& thisElement = HTMLMediaElementEncryptedMedia::from(element);

    if (!thisElement.setEmeMode(EmeModeUnprefixed, exceptionState))
        return;

    thisElement.setMediaKeysInternal(element, mediaKeys);
}

// Create a MediaKeyNeededEvent for WD EME.
static PassRefPtrWillBeRawPtr<Event> createNeedKeyEvent(const String& contentType, const unsigned char* initData, unsigned initDataLength)
{
    MediaKeyNeededEventInit initializer;
    initializer.contentType = contentType;
    initializer.initData = Uint8Array::create(initData, initDataLength);
    initializer.bubbles = false;
    initializer.cancelable = false;

    return MediaKeyNeededEvent::create(EventTypeNames::needkey, initializer);
}

// Create a 'needkey' MediaKeyEvent for v0.1b EME.
static PassRefPtrWillBeRawPtr<Event> createWebkitNeedKeyEvent(const String& contentType, const unsigned char* initData, unsigned initDataLength)
{
    MediaKeyEventInit webkitInitializer;
    webkitInitializer.keySystem = String();
    webkitInitializer.sessionId = String();
    webkitInitializer.initData = Uint8Array::create(initData, initDataLength);
    webkitInitializer.bubbles = false;
    webkitInitializer.cancelable = false;

    return MediaKeyEvent::create(EventTypeNames::webkitneedkey, webkitInitializer);
}

void HTMLMediaElementEncryptedMedia::webkitGenerateKeyRequest(HTMLMediaElement& element, const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& exceptionState)
{
    HTMLMediaElementEncryptedMedia::from(element).generateKeyRequest(element.webMediaPlayer(), keySystem, initData, exceptionState);
}

void HTMLMediaElementEncryptedMedia::generateKeyRequest(WebMediaPlayer* webMediaPlayer, const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& exceptionState)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::webkitGenerateKeyRequest");

    if (!setEmeMode(EmeModePrefixed, exceptionState))
        return;

    if (keySystem.isEmpty()) {
        exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
        return;
    }

    if (!webMediaPlayer) {
        exceptionState.throwDOMException(InvalidStateError, "No media has been loaded.");
        return;
    }

    const unsigned char* initDataPointer = 0;
    unsigned initDataLength = 0;
    if (initData) {
        initDataPointer = initData->data();
        initDataLength = initData->length();
    }

    WebMediaPlayer::MediaKeyException result = webMediaPlayer->generateKeyRequest(keySystem, initDataPointer, initDataLength);
    throwExceptionIfMediaKeyExceptionOccurred(keySystem, String(), result, exceptionState);
}

void HTMLMediaElementEncryptedMedia::webkitGenerateKeyRequest(HTMLMediaElement& mediaElement, const String& keySystem, ExceptionState& exceptionState)
{
    webkitGenerateKeyRequest(mediaElement, keySystem, Uint8Array::create(0), exceptionState);
}

void HTMLMediaElementEncryptedMedia::webkitAddKey(HTMLMediaElement& element, const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& exceptionState)
{
    HTMLMediaElementEncryptedMedia::from(element).addKey(element.webMediaPlayer(), keySystem, key, initData, sessionId, exceptionState);
}

void HTMLMediaElementEncryptedMedia::addKey(WebMediaPlayer* webMediaPlayer, const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& exceptionState)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::webkitAddKey");

    if (!setEmeMode(EmeModePrefixed, exceptionState))
        return;

    if (keySystem.isEmpty()) {
        exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
        return;
    }

    if (!key) {
        exceptionState.throwDOMException(SyntaxError, "The key provided is invalid.");
        return;
    }

    if (!key->length()) {
        exceptionState.throwDOMException(TypeMismatchError, "The key provided is invalid.");
        return;
    }

    if (!webMediaPlayer) {
        exceptionState.throwDOMException(InvalidStateError, "No media has been loaded.");
        return;
    }

    const unsigned char* initDataPointer = 0;
    unsigned initDataLength = 0;
    if (initData) {
        initDataPointer = initData->data();
        initDataLength = initData->length();
    }

    WebMediaPlayer::MediaKeyException result = webMediaPlayer->addKey(keySystem, key->data(), key->length(), initDataPointer, initDataLength, sessionId);
    throwExceptionIfMediaKeyExceptionOccurred(keySystem, sessionId, result, exceptionState);
}

void HTMLMediaElementEncryptedMedia::webkitAddKey(HTMLMediaElement& mediaElement, const String& keySystem, PassRefPtr<Uint8Array> key, ExceptionState& exceptionState)
{
    webkitAddKey(mediaElement, keySystem, key, Uint8Array::create(0), String(), exceptionState);
}

void HTMLMediaElementEncryptedMedia::webkitCancelKeyRequest(HTMLMediaElement& element, const String& keySystem, const String& sessionId, ExceptionState& exceptionState)
{
    HTMLMediaElementEncryptedMedia::from(element).cancelKeyRequest(element.webMediaPlayer(), keySystem, sessionId, exceptionState);
}

void HTMLMediaElementEncryptedMedia::cancelKeyRequest(WebMediaPlayer* webMediaPlayer, const String& keySystem, const String& sessionId, ExceptionState& exceptionState)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::webkitCancelKeyRequest");

    if (!setEmeMode(EmeModePrefixed, exceptionState))
        return;

    if (keySystem.isEmpty()) {
        exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
        return;
    }

    if (!webMediaPlayer) {
        exceptionState.throwDOMException(InvalidStateError, "No media has been loaded.");
        return;
    }

    WebMediaPlayer::MediaKeyException result = webMediaPlayer->cancelKeyRequest(keySystem, sessionId);
    throwExceptionIfMediaKeyExceptionOccurred(keySystem, sessionId, result, exceptionState);
}

void HTMLMediaElementEncryptedMedia::keyAdded(HTMLMediaElement& element, const String& keySystem, const String& sessionId)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::mediaPlayerKeyAdded");

    MediaKeyEventInit initializer;
    initializer.keySystem = keySystem;
    initializer.sessionId = sessionId;
    initializer.bubbles = false;
    initializer.cancelable = false;

    RefPtrWillBeRawPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeyadded, initializer);
    event->setTarget(&element);
    element.scheduleEvent(event.release());
}

void HTMLMediaElementEncryptedMedia::keyError(HTMLMediaElement& element, const String& keySystem, const String& sessionId, WebMediaPlayerClient::MediaKeyErrorCode errorCode, unsigned short systemCode)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::mediaPlayerKeyError: sessionID=%s, errorCode=%d, systemCode=%d", sessionId.utf8().data(), errorCode, systemCode);

    MediaKeyError::Code mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_UNKNOWN;
    switch (errorCode) {
    case WebMediaPlayerClient::MediaKeyErrorCodeUnknown:
        mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_UNKNOWN;
        break;
    case WebMediaPlayerClient::MediaKeyErrorCodeClient:
        mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_CLIENT;
        break;
    case WebMediaPlayerClient::MediaKeyErrorCodeService:
        mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_SERVICE;
        break;
    case WebMediaPlayerClient::MediaKeyErrorCodeOutput:
        mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_OUTPUT;
        break;
    case WebMediaPlayerClient::MediaKeyErrorCodeHardwareChange:
        mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_HARDWARECHANGE;
        break;
    case WebMediaPlayerClient::MediaKeyErrorCodeDomain:
        mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_DOMAIN;
        break;
    }

    MediaKeyEventInit initializer;
    initializer.keySystem = keySystem;
    initializer.sessionId = sessionId;
    initializer.errorCode = MediaKeyError::create(mediaKeyErrorCode);
    initializer.systemCode = systemCode;
    initializer.bubbles = false;
    initializer.cancelable = false;

    RefPtrWillBeRawPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeyerror, initializer);
    event->setTarget(&element);
    element.scheduleEvent(event.release());
}

void HTMLMediaElementEncryptedMedia::keyMessage(HTMLMediaElement& element, const String& keySystem, const String& sessionId, const unsigned char* message, unsigned messageLength, const WebURL& defaultURL)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::mediaPlayerKeyMessage: sessionID=%s", sessionId.utf8().data());

    MediaKeyEventInit initializer;
    initializer.keySystem = keySystem;
    initializer.sessionId = sessionId;
    initializer.message = Uint8Array::create(message, messageLength);
    initializer.defaultURL = KURL(defaultURL);
    initializer.bubbles = false;
    initializer.cancelable = false;

    RefPtrWillBeRawPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeymessage, initializer);
    event->setTarget(&element);
    element.scheduleEvent(event.release());
}

void HTMLMediaElementEncryptedMedia::keyNeeded(HTMLMediaElement& element, const String& contentType, const unsigned char* initData, unsigned initDataLength)
{
    WTF_LOG(Media, "HTMLMediaElementEncryptedMedia::mediaPlayerKeyNeeded: contentType=%s", contentType.utf8().data());

    if (RuntimeEnabledFeatures::encryptedMediaEnabled()) {
        // Send event for WD EME.
        RefPtrWillBeRawPtr<Event> event = createNeedKeyEvent(contentType, initData, initDataLength);
        event->setTarget(&element);
        element.scheduleEvent(event.release());
    }

    if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
        // Send event for v0.1b EME.
        RefPtrWillBeRawPtr<Event> event = createWebkitNeedKeyEvent(contentType, initData, initDataLength);
        event->setTarget(&element);
        element.scheduleEvent(event.release());
    }
}

void HTMLMediaElementEncryptedMedia::playerDestroyed(HTMLMediaElement& element)
{
#if ENABLE(OILPAN)
    // FIXME: Oilpan: remove this once the media player is on the heap. crbug.com/378229
    if (element.isFinalizing())
        return;
#endif

    HTMLMediaElementEncryptedMedia& thisElement = HTMLMediaElementEncryptedMedia::from(element);
    thisElement.setMediaKeysInternal(element, 0);
}

WebContentDecryptionModule* HTMLMediaElementEncryptedMedia::contentDecryptionModule(HTMLMediaElement& element)
{
    HTMLMediaElementEncryptedMedia& thisElement = HTMLMediaElementEncryptedMedia::from(element);
    return thisElement.contentDecryptionModule();
}

void HTMLMediaElementEncryptedMedia::trace(Visitor* visitor)
{
    visitor->trace(m_mediaKeys);
    WillBeHeapSupplement<HTMLMediaElement>::trace(visitor);
}

} // namespace blink


text:
import React from 'react';
import PropTypes from 'prop-types';
import {
  Card,
  CardHeader,
  CardText,
} from 'material-ui';
import { itemType } from '../propTypes';
import ListItem from './ListItem';

const NextItem = ({ item, onListItemUpdate }) => (
  <Card>
    <CardHeader title="Next item up" />
    <CardText>
      <ListItem item={item} onListItemUpdate={onListItemUpdate} />
    </CardText>
  </Card>
);

NextItem.propTypes = {
  item:             itemType.isRequired,
  onListItemUpdate: PropTypes.func.isRequired,
};

export default NextItem;


text:
namespace {

bool HasSwitch(const std::string& switch_name) {
  // Most policy features must be controlled via the command line because policy
  // infrastructure must be initialized before about:flags or field trials.
  // Using a command line flag is the only way to control these features at
  // runtime.
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  return command_line->HasSwitch(switch_name);
}

// Returns true if the current command line contains the
// |kDisableEnterprisePolicy| switch.
bool IsDisableEnterprisePolicySwitchPresent() {
  return HasSwitch(switches::kDisableEnterprisePolicy);
}

}  // namespace

bool IsEnterprisePolicyEnabled() {
  return !IsDisableEnterprisePolicySwitchPresent();
}

bool ShouldInstallEnterprisePolicyHandlers() {
  return IsEnterprisePolicyEnabled();
}

bool ShouldInstallURLBlocklistPolicyHandlers() {
  return HasSwitch(switches::kInstallURLBlocklistHandlers);
}

bool IsURLBlocklistEnabled() {
  return ShouldInstallURLBlocklistPolicyHandlers();
}


text:
<?php
/**
 * Created by Philippe Le Van.
 * Date: 30/07/13
 */

namespace Kitpages\ActivityBundle;

class ActivityException
    extends \Exception
{

}


text:
namespace ash {

class UserActivityObserver;

// Watches for input events and notifies observers that the user is active.
class ASH_EXPORT UserActivityDetector : public ui::EventHandler {
 public:
  // Minimum amount of time between notifications to observers.
  static const double kNotifyIntervalMs;

  UserActivityDetector();
  virtual ~UserActivityDetector();

  void set_now_for_test(base::TimeTicks now) { now_for_test_ = now; }

  bool HasObserver(UserActivityObserver* observer) const;
  void AddObserver(UserActivityObserver* observer);
  void RemoveObserver(UserActivityObserver* observer);

  // Called when chrome has received a request to turn of all displays.
  void OnAllOutputsTurnedOff();

  // ui::EventHandler implementation.
  virtual ui::EventResult OnKeyEvent(ui::KeyEvent* event) OVERRIDE;
  virtual ui::EventResult OnMouseEvent(ui::MouseEvent* event) OVERRIDE;
  virtual ui::EventResult OnScrollEvent(ui::ScrollEvent* event) OVERRIDE;
  virtual ui::EventResult OnTouchEvent(ui::TouchEvent* event) OVERRIDE;
  virtual ui::EventResult OnGestureEvent(ui::GestureEvent* event) OVERRIDE;

 private:
  // Notifies observers if enough time has passed since the last notification.
  void MaybeNotify();

  ObserverList<UserActivityObserver> observers_;

  // Last time at which we notified observers that the user was active.
  base::TimeTicks last_observer_notification_time_;

  // If set, used when the current time is needed.  This can be set by tests to
  // simulate the passage of time.
  base::TimeTicks now_for_test_;

  // When this is true, the next mouse event is ignored. This is to
  // avoid mis-detecting a mouse enter event that occurs when turning
  // off display as a user activity.
  bool ignore_next_mouse_event_;

  DISALLOW_COPY_AND_ASSIGN(UserActivityDetector);
};

}  // namespace ash

#endif  // ASH_WM_USER_ACTIVITY_DETECTOR_H_


text:
namespace viennautils
{
namespace dfise
{

struct parsing_error : virtual viennautils::exception {};

} //end of namespace dfise

} //end of namespace viennautils

#endif


text:
\clearpage
\phantomsection
\addcontentsline{toc}{subsection}{LDUB}
\label{insn:ldub}
\subsection*{LDUB: load an unsigned 8 bit value}

\subsubsection*{Format}

\textrm{LDUB \%rd, \%r1}

\begin{center}
\begin{bytefield}[endianness=big,bitformatting=\scriptsize]{32}
\bitheader{0,7,8,15,16,23,24,31} \\
\bitbox{8}{0x1F}
\bitbox{8}{r1}
\bitbox{8}{r2}
\bitbox{8}{rd}
\end{bytefield}
\end{center}

\subsubsection*{Description}

The \instruction{ldub} instruction loads the value pointed to by \registerop{r1}
into \registerop{rd}, the results register. This is an \textbf{unsigned}
instruction and will not perform sign extension in any case.

\subsubsection*{Pseudocode}

\begin{verbatim}
%rd = %r1
\end{verbatim}

\subsubsection*{Load-time constraints}
The registers \registerop{r1} and \registerop{rd} must be valid registers,
\registerop{r2} must be \registerop{r0} and \registerop{rd} must not be
\registerop{r0}.

This instruction is \textbf{privileged} and thus performs no access control
checks. It is up to the OpenDTrace implementation to implement that constraint.

\subsubsection*{Failure modes}

This instruction has no run-time failure modes beyond its constraints.


text:
"use strict";
Object.defineProperties(module.exports, {
  q: {get: function() {
      return q;
    }},
  __esModule: {value: true}
});
var q = 'q';


text:
<?php
# Copyright (c) 2017, CESNET. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   o Redistributions of source code must retain the above
#     copyright notice, this list of conditions and the following
#     disclaimer.
#   o Redistributions in binary form must reproduce the above
#     copyright notice, this list of conditions and the following
#     disclaimer in the documentation and/or other materials
#     provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

/**
 * @author Michal Prochazka
 * @author Jakub Mlcak
 */
class OsDao
{
    private $db;

    public function __construct(DbManager &$dbManager)
    {
        $this->db = $dbManager;
    }

    public function create(Os &$os)
    {
        $sql = "insert into Os set
            name='" . $this->db->escape($os->getName()) . "'";
        $this->db->query($sql);

        # Set the newly assigned id
        $os->setId($this->db->getLastInsertedId());
    }

    public function getById($id)
    {
        $sql = "select id as _id, name as _name from Os
            where id='" . $this->db->escape($id) . "'";
        return $this->db->queryObject($sql, "Os");
    }

    public function getIdByName($name)
    {
        $sql = "select id from Os
            where name='" . $this->db->escape($name) . "'";
        $id = $this->db->queryToSingleValue($sql);
        return ($id == null) ? -1 : $id;
    }

    public function getIds($orderBy = null, $pageSize = -1, $pageNum = -1)
    {
        $select = "Os.id";
        $from = "Os";
        $join = null;
        $where = null;
        $order = "Os.name";
        $limit = null;
        $offset = null;

        if ($orderBy != null) {
            $order = "Os.".$this->db->escape($orderBy)."";
        }

        if ($pageSize != -1 && $pageNum != -1) {
            $limit = $pageSize;
            $offset = $pageSize * $pageNum;
        }

        $sql = Utils::sqlSelectStatement($select, $from, $join, $where, $order, $limit, $offset);
        return $this->db->queryToSingleValueMultiRow($sql);
    }

    public function unassignOsGroupsFromOs($osId)
    {
        $sql = "delete from OsOsGroup
            where osId='" . $this->db->escape($osId) . "'";
        $this->db->query($sql);
    }

    public function assignOsToOsGroup($osId, $osGroupId)
    {
        $sql = "insert ignore into OsOsGroup set
            osId='" . $this->db->escape($osId) . "',
            osGroupId='" . $this->db->escape($osGroupId) . "'";
        $this->db->query($sql);
    }
}


text:
package com.rmd.personal.projecteuler;

import org.junit.Test;

import static org.junit.Assert.*;

public class P048Test extends AbstractProblemTestBase<P048> {

    public P048Test() {
        super(new P048());
    }

    @Test
    public void runReturnsCorrectlyForProvided() {
        // Arrange
        final int numberOfDigits = 10;
        final int n = 10;
        this.getProblem().setNumberOfDigits(numberOfDigits);
        this.getProblem().setN(n);

        // Act
        String returned = this.getProblem().run();

        // Assert
        final String expected = "0405071317";
        assertEquals(expected, returned);
    }

    @Test
    public void runReturnsCorrectlyFor2DigitsN6() {
        // Arrange
        final int numberOfDigits = 2;
        final int n = 6;
        this.getProblem().setNumberOfDigits(numberOfDigits);
        this.getProblem().setN(n);

        // Act
        String returned = this.getProblem().run();

        // Assert
        final String expected = "69";
        assertEquals(expected, returned);
    }

    @Test
    public void runReturnsCorrectlyFor3DigitsN6() {
        // Arrange
        final int numberOfDigits = 3;
        final int n = 6;
        this.getProblem().setNumberOfDigits(numberOfDigits);
        this.getProblem().setN(n);

        // Act
        String returned = this.getProblem().run();

        // Assert
        final String expected = "069";
        assertEquals(expected, returned);
    }

    @Test
    public void runReturnsCorrectlyFor4DigitsN6() {
        // Arrange
        final int numberOfDigits = 4;
        final int n = 6;
        this.getProblem().setNumberOfDigits(numberOfDigits);
        this.getProblem().setN(n);

        // Act
        String returned = this.getProblem().run();

        // Assert
        final String expected = "0069";
        assertEquals(expected, returned);
    }

    @Test
    public void runReturnsCorrectlyForDefault() {
        // Act
        String returned = this.getProblem().run();

        // Assert
        final String expected = "9110846700";
        assertEquals(expected, returned);
    }
}


text:
<?php

namespace Surfnet\StepupMiddleware\ApiBundle\Identity\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\Query;
use Surfnet\Stepup\Identity\Value\IdentityId;
use Surfnet\StepupMiddleware\ApiBundle\Exception\RuntimeException;
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\AuditLogEntry;
use Surfnet\StepupMiddleware\ApiBundle\Identity\Query\SecondFactorAuditLogQuery;

class AuditLogRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, AuditLogEntry::class);
    }

    /**
     * An array of event FQCNs that pertain to second factors (verification, vetting, revocation etc.).
     *
     * @var string[]
     */
    private static $secondFactorEvents = [
        'Surfnet\Stepup\Identity\Event\YubikeySecondFactorBootstrappedEvent',
        'Surfnet\Stepup\Identity\Event\GssfPossessionProvenEvent',
        'Surfnet\Stepup\Identity\Event\PhonePossessionProvenEvent',
        'Surfnet\Stepup\Identity\Event\YubikeyPossessionProvenAndVerifiedEvent',
        'Surfnet\Stepup\Identity\Event\GssfPossessionProvenAndVerifiedEvent',
        'Surfnet\Stepup\Identity\Event\PhonePossessionProvenAndVerifiedEvent',
        'Surfnet\Stepup\Identity\Event\EmailVerifiedEvent',
        'Surfnet\Stepup\Identity\Event\SecondFactorVettedEvent',
        'Surfnet\Stepup\Identity\Event\SecondFactorVettedWithoutTokenProofOfPossession',
        'Surfnet\Stepup\Identity\Event\SecondFactorMigratedEvent',
        'Surfnet\Stepup\Identity\Event\SecondFactorMigratedToEvent',
        'Surfnet\Stepup\Identity\Event\UnverifiedSecondFactorRevokedEvent',
        'Surfnet\Stepup\Identity\Event\VerifiedSecondFactorRevokedEvent',
        'Surfnet\Stepup\Identity\Event\VettedSecondFactorRevokedEvent',
        'Surfnet\Stepup\Identity\Event\CompliedWithUnverifiedSecondFactorRevocationEvent',
        'Surfnet\Stepup\Identity\Event\CompliedWithVerifiedSecondFactorRevocationEvent',
        'Surfnet\Stepup\Identity\Event\CompliedWithVettedSecondFactorRevocationEvent',
        'Surfnet\Stepup\Identity\Event\IdentityAccreditedAsRaaEvent',
        'Surfnet\Stepup\Identity\Event\IdentityAccreditedAsRaEvent',
        'Surfnet\Stepup\Identity\Event\IdentityAccreditedAsRaForInstitutionEvent',
        'Surfnet\Stepup\Identity\Event\IdentityAccreditedAsRaaForInstitutionEvent',
        'Surfnet\Stepup\Identity\Event\AppointedAsRaaEvent',
        'Surfnet\Stepup\Identity\Event\AppointedAsRaForInstitutionEvent',
        'Surfnet\Stepup\Identity\Event\AppointedAsRaaForInstitutionEvent',
        'Surfnet\Stepup\Identity\Event\AppointedAsRaEvent',
        'Surfnet\Stepup\Identity\Event\RegistrationAuthorityRetractedEvent',
        'Surfnet\Stepup\Identity\Event\RegistrationAuthorityRetractedForInstitutionEvent',
        'Surfnet\Stepup\Identity\Event\SafeStoreSecretRecoveryTokenPossessionPromisedEvent',
        'Surfnet\Stepup\Identity\Event\RecoveryTokenRevokedEvent',
        'Surfnet\Stepup\Identity\Event\PhoneRecoveryTokenPossessionProvenEvent',
        'Surfnet\Stepup\Identity\Event\CompliedWithRecoveryCodeRevocationEvent',
    ];

    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity) - The filtering switch triggers the CyclomaticComplexity, it does
     *                                                 not actually make the class complex or hard to maintain.
     * @param SecondFactorAuditLogQuery $query
     * @return Query
     */
    public function createSecondFactorSearchQuery(SecondFactorAuditLogQuery $query)
    {
        $queryBuilder = $this
            ->createQueryBuilder('al')
            ->where('al.identityInstitution = :identityInstitution')
            ->setParameter('identityInstitution', $query->identityInstitution)
            ->andWhere('al.identityId = :identityId')
            ->andWhere('al.event IN (:secondFactorEvents)')
            ->setParameter('identityId', $query->identityId)
            ->setParameter('secondFactorEvents', self::$secondFactorEvents);

        switch ($query->orderBy) {
            case 'secondFactorType':
            case 'secondFactorIdentifier':
            case 'recoveryTokenType':
            case 'recoveryTokenIdentifier':
            case 'recordedOn':
            case 'actorCommonName':
            case 'actorInstitution':
                $queryBuilder->orderBy(
                    sprintf('al.%s', $query->orderBy),
                    $query->orderDirection === 'desc' ? 'DESC' : 'ASC'
                );
                break;
            default:
                throw new RuntimeException(sprintf('Unknown order by column "%s"', $query->orderBy));
        }

        return $queryBuilder->getQuery();
    }

    /**
     * @param IdentityId $actorId
     * @return AuditLogEntry[]
     */
    public function findEntriesWhereIdentityIsActorOnly(IdentityId $actorId)
    {
        return $this->createQueryBuilder('al')
            ->where('al.actorId = :actorId')
            ->andWhere('al.identityId != :actorId')
            ->setParameter('actorId', $actorId)
            ->getQuery()
            ->getResult();
    }

    /**
     * @param IdentityId $actorId
     * @return AuditLogEntry[]
     */
    public function findByIdentityId(IdentityId $identityId)
    {
        return $this->createQueryBuilder('al')
            ->where('al.identityId = :identityId')
            ->setParameter('identityId', $identityId)
            ->getQuery()
            ->getResult();
    }

    /**
     * @param AuditLogEntry $entry
     */
    public function save(AuditLogEntry $entry)
    {
        $entityManager = $this->getEntityManager();
        $entityManager->persist($entry);
        $entityManager->flush();
    }

    public function saveAll(array $entries)
    {
        $entityManager = $this->getEntityManager();

        foreach ($entries as $entry) {
            $entityManager->persist($entry);
        }

        $entityManager->flush();
    }
}


text:
from unittest import TestCase, main
import requests
from time import sleep

# plugins
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import TimeoutException

# application
from vue_flask import get_input_id, get_population_limit

class TestDeployedSiteWithRequests(TestCase):
    def setUp(self):
        self.site = 'https://kw4udfbos9.execute-api.us-west-2.amazonaws.com/production'

    def test_server_is_up_and_running(self):
        request = requests.get(self.site)
        self.assertEqual(200, request.status_code)

    def test_server_content_type(self):
        request = requests.get(self.site)
        self.assertEqual('text/html; charset=utf-8', request.headers['Content-Type'], msg=request.headers)

class TestDeployedSiteWithSelenium(TestCase):
    def setUp(self):
        # Reference: http://seleniumhq.github.io/selenium/docs/api/py/
        self.site = 'https://kw4udfbos9.execute-api.us-west-2.amazonaws.com/production'
        self.browsers = [
            # webdriver.Chrome(),
            webdriver.Firefox(),
            # webdriver.Ie()
        ]
        self.input_id = get_input_id()
        self.creationform = self.input_id['creationform']
        self.firstname = self.input_id['firstname']
        self.lastname = self.input_id['lastname']
        self.dob = self.input_id['dob']
        self.zipcode = self.input_id['zipcode']
        self.submit = self.input_id['submit']
        self.population = self.input_id['population']

        self.population_limit = get_population_limit()

    def tearDown(self):
        for browser in self.browsers:
            self.addCleanup(browser.quit)

    def create_person(self, browser, input):
        element_ids = [self.firstname, self.lastname, self.dob, self.zipcode, ]

        for index, element_id in enumerate(element_ids):
            input_element = browser.find_element_by_id(element_id)
            input_element.send_keys(input[index])

        submit_button = browser.find_element_by_id(self.submit)
        submit_button.click()

    def delete_person(self, browser):
        # Delete first person is list. First in First out.
        first_delete_icon = browser.find_element_by_id('0')
        first_delete_icon.click()

    def handle_population_limits(self, browser, create=False, delete=False):
        """ The population value comes from firebase and is loading by vue. Both of these operations take time. A delay
        is required to ensure that the population value is correct since vue sometimes loads the value 0 then changes
        it once firebase returns.

        Steps:
        Wait for vue and firebase.
        Test that population is within limits.
        If population is at the min population limit and delete mode increment population.
        If population is at the max population limit and create mode decrement population.
        Return population value.
        """
        population_element = browser.find_element_by_id(self.population)
        sleep(1.5)    # Wait for vue and firebase lag.
        population = int(population_element.text)

        self.assertTrue(0 <= population <= self.population_limit, msg='Population out of bounds.')

        # Pre-Deletion
        if population == 0 and delete:
            self.create_person(browser, input=['Gerotty', 'Rafan', '1968-10-08', '00760-2341', ])
            return population + 1

        # Pre-Creation
        if population == self.population_limit and create:
            self.delete_person(browser)
            self.assertTrue(self.population_decremented(browser, population))
            return population - 1

        return population

    def population_changed(self, browser, population_expected):
        # Reference: http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#explicit-waits
        # https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/support/expected_conditions.py
        delay = 5   # in seconds
        try:
            WebDriverWait(browser, delay).until(
                expected_conditions.text_to_be_present_in_element((By.ID, self.population), population_expected)
            )
            return True
        except TimeoutException:
            return False

    def population_decremented(self, browser, population_before):
        population_expected = unicode(int(population_before) - 1)
        return self.population_changed(browser, population_expected)

    def population_incremented(self, browser, population_before):
        population_expected = unicode(int(population_before) + 1)
        return self.population_changed(browser, population_expected)

    def test_page_title(self):
        for browser in self.browsers:
            browser.get(self.site)
            self.assertIn('Person Creation Machine', browser.title)

    def test_population_exists(self):
        for browser in self.browsers:
            browser.get(self.site)
            population_element = browser.find_element_by_id(self.population)
            population = int(population_element.text)
            self.assertTrue(0 <= population <= self.population_limit)

    def test_create_person_form_with_valid_data(self):
        for browser in self.browsers:
            browser.get(self.site)
            population_before = self.handle_population_limits(browser, create=True)
            self.create_person(browser, input=['Xython', 'Ber', '1999-09-09', '85000', ])
            self.assertTrue(self.population_incremented(browser, population_before))

    def test_button_disabled(self):
        submit = self.submit

        for browser in self.browsers:
            browser.get(self.site)
            submit_button = browser.find_element_by_id(submit)
            self.assertFalse(submit_button.is_enabled())

    # def test_create_a_person_form_input_length_exceeded(self):
    #     pass
    #
    # def test_create_a_person_form_future_birth_day(self):
    #     pass
    #
    # def test_create_a_person_form_invalid_zipcodes(self):
    #     pass
    #
    def test_remove_person_top_table(self):
        for browser in self.browsers:
            browser.get(self.site)
            population_before = self.handle_population_limits(browser, delete=True)
            self.delete_person(browser)
            self.assertTrue(self.population_decremented(browser, population_before))

if __name__ == '__main__':
    main()


text:
from openerp.addons.web.http import request
from openerp.osv import orm

class QWeb(orm.AbstractModel):
    """ QWeb object for rendering stuff in the website context
    """
    _inherit = 'ir.qweb'

    URL_ATTRS = {
        'form': 'action',
        'a': 'href',
    }

    CDN_TRIGGERS = {
        'link':    'href',
        'script':  'src',
        'img':     'src',
    }

    PRESERVE_WHITESPACE = [
        'pre',
        'textarea',
        'script',
        'style',
    ]

    def render_attribute(self, element, name, value, qwebcontext):
        context = qwebcontext.context or {}
        if not context.get('rendering_bundle'):
            if name == self.URL_ATTRS.get(element.tag) and qwebcontext.get('url_for'):
                value = qwebcontext.get('url_for')(value)
            elif request and getattr(request, 'website', None) and request.website.cdn_activated and (name == self.URL_ATTRS.get(element.tag) or name == self.CDN_TRIGGERS.get(element.tag)):
                value = request.website.get_cdn_url(value)
        return super(QWeb, self).render_attribute(element, name, value, qwebcontext)

    def render_text(self, text, element, qwebcontext):
        compress = request and not request.debug and getattr(request, 'website', None) and request.website.compress_html
        if compress and element.tag not in self.PRESERVE_WHITESPACE:
            text = self.re_remove_spaces.sub(' ', text)
        return super(QWeb, self).render_text(text, element, qwebcontext)

    def render_tail(self, tail, element, qwebcontext):
        compress = request and not request.debug and getattr(request, 'website', None) and request.website.compress_html
        if compress and element.getparent().tag not in self.PRESERVE_WHITESPACE:
            # No need to recurse because those tags children are not html5 parser friendly
            tail = self.re_remove_spaces.sub(' ', tail.rstrip())
        return super(QWeb, self).render_tail(tail, element, qwebcontext)


text:
package com.github.haixing_hu.util.ref;

/**
 * A trivial structure representing the reference of a float variable, which could
 * be used as a reference argument in function calls.
 *
 * @author Haixing Hu
 */
public final class FloatRef {
  public float value;
}


text:
package eu.leads.processor.common;

import eu.leads.processor.common.infinispan.InfinispanManager;
import org.vertx.java.core.json.JsonObject;

import java.io.Serializable;

/**
 * Created by vagvaz on 6/7/14.
 */
public interface LeadsListener extends Serializable {

  /**
   * Getter for property 'manager'.
   *
   * @return Value for property 'manager'.
   */
  public InfinispanManager getManager();

  /**
   * Setter for property 'manager'.
   *
   * @param manager Value to set for property 'manager'.
   */
  public void setManager(InfinispanManager manager);

  public void initialize(InfinispanManager manager, JsonObject conf);

  public void initialize(InfinispanManager manager);

  /**
   * Getter for property 'id'.
   *
   * @return Value for property 'id'.
   */
  public String getId();

  public void close();

  void setConfString(String s);
}


text:
package starpunk.screens;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Slider;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import java.util.Locale;
import starpunk.StarPunkGame;

public class OptionsScreen
  extends Base2DScreen
{
  public OptionsScreen( final StarPunkGame game )
  {
    super( game );
  }

  @Override
  public void show()
  {
    super.show();

    final Table table = super.getTable();
    table.defaults().spaceBottom( 30 );
    table.columnDefaults( 0 ).padRight( 20 );
    table.add( "Options" ).colspan( 3 );

    final CheckBox soundCheckbox = new CheckBox( "", getSkin() );
    soundCheckbox.setChecked( getGame().getPreferenceManager().isSoundEnabled() );
    soundCheckbox.addListener( new ChangeListener()
    {
      @Override
      public void changed( final ChangeEvent event, final Actor actor )
      {
        getGame().getPreferenceManager().setSoundEnabled( soundCheckbox.isChecked() );
        getGame().getSoundManager().play( MediaConstants.CLICK_SOUND );
      }
    } );
    table.row();
    table.add( "Sound Effects" );
    table.add( soundCheckbox ).colspan( 2 ).left();

    final Label soundVolumeLabel =
      new Label( formatVolume( getGame().getPreferenceManager().getSoundVolume() ), getSkin() );

    // range is [0.0,1.0]; step is 0.1f
    final Slider soundVolumeSlider = new Slider( 0f, 1f, 0.1f, false, getSkin() );
    soundVolumeSlider.setValue( getGame().getPreferenceManager().getSoundVolume() );
    soundVolumeSlider.addListener( new ChangeListener()
    {
      @Override
      public void changed( final ChangeEvent event, final Actor actor )
      {
        final float value = ( (Slider) actor ).getValue();
        getGame().getPreferenceManager().setSoundVolume( value );
        soundVolumeLabel.setText( formatVolume( getGame().getPreferenceManager().getSoundVolume() ) );
      }
    } );

    table.row();
    table.add( "Music Volume" );
    table.add( soundVolumeSlider );
    table.add( soundVolumeLabel ).width( 40 );

    final CheckBox musicCheckbox = new CheckBox( "", getSkin() );
    musicCheckbox.setChecked( getGame().getPreferenceManager().isMusicEnabled() );
    musicCheckbox.addListener( new ChangeListener()
    {
      @Override
      public void changed( final ChangeEvent event, final Actor actor )
      {
        final boolean enabled = musicCheckbox.isChecked();
        getGame().getPreferenceManager().setMusicEnabled( enabled );
        getGame().getSoundManager().play( MediaConstants.CLICK_SOUND );
        if( enabled )
        {
          getGame().getMusicManager().play( MediaConstants.MENU_MUSIC );
        }
      }
    } );
    table.row();
    table.add( "Music" );
    table.add( musicCheckbox ).colspan( 2 ).left();

    final Label musicVolume =
      new Label( formatVolume( getGame().getPreferenceManager().getMusicVolume() ), getSkin() );

    // range is [0.0,1.0]; step is 0.1f
    final Slider musicVolumeSlider = new Slider( 0f, 1f, 0.1f, false, getSkin() );
    musicVolumeSlider.setValue( getGame().getPreferenceManager().getMusicVolume() );
    musicVolumeSlider.addListener( new ChangeListener()
    {
      @Override
      public void changed( final ChangeEvent event, final Actor actor )
      {
        final float value = ( (Slider) actor ).getValue();
        getGame().getPreferenceManager().setMusicVolume( value );
        musicVolume.setText( formatVolume( getGame().getPreferenceManager().getMusicVolume() ) );
      }
    } );

    table.row();
    table.add( "Music Volume" );
    table.add( musicVolumeSlider );
    table.add( musicVolume ).width( 40 );

    // register the back button
    final TextButton backButton = new TextButton( "Back to main menu", getSkin() );
    backButton.addListener( new ClickListener()
    {
      @Override
      public void touchUp( final InputEvent event, final float x, final float y, final int pointer, final int button )
      {
        super.touchUp( event, x, y, pointer, button );
        getGame().getSoundManager().play( MediaConstants.CLICK_SOUND );
        getGame().setScreen( new MenuScreen( getGame() ) );
      }
    } );
    table.row();
    table.add( backButton ).size( 250, 60 ).colspan( 3 );
  }

  private String formatVolume( final float volume )
  {
    return String.format( Locale.US, "%1.0f%%", ( volume * 100 ) );
  }
}


text:
                        // on molecules)
//#define EXCLUDE_WRONG_COMPOSITION   // fast but with a little effect, because
// amount of external bonds usually is very small.
// Exclude mismatched bonds combinations during seed growing (2^N-1 stage)

#define FAST_SUBSTRUCT_CACHE  // based on a hash of Morgan code
#define DUP_SUBSTRUCT_CACHE   // based on list of query atoms and bonds. For
                              // rings where seeds growing in both directions
                              // throw the same ring.

#define FAST_INCREMENTAL_MATCH  // fast and some time very usefull. request
                                // PRECOMPUTED_TABLES_MATCH
// previous match result based match checking without finding new matched
// substructure location in the target

#define VERBOSE_STATISTICS_ON

#ifdef _MSC_VER
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL

struct timezone {
  int tz_minuteswest;  // minutes W of Greenwich
  int tz_dsttime;      // type of dst correction
};

static inline int gettimeofday(struct timeval *tv, struct timezone *tz) {
  FILETIME ft;
  unsigned __int64 tmpres = 0;
  static int tzflag;

  if (NULL != tv) {
    GetSystemTimeAsFileTime(&ft);

    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    // converting file time to unix epoch
    tmpres -= DELTA_EPOCH_IN_MICROSECS;
    tmpres /= 10;  // convert into microseconds
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }

  if (NULL != tz) {
    if (!tzflag) {
      _tzset();
      tzflag++;
    }
    tz->tz_minuteswest = _timezone / 60;
    tz->tz_dsttime = _daylight;
  }
  return 0;
}
#endif

static inline unsigned long long nanoClock(
    void) {  // actually returns microseconds
  struct timeval t;
  gettimeofday(&t, (struct timezone *)0);
  return t.tv_usec + t.tv_sec * 1000000ULL;
}

namespace RDKit {
namespace FMCS {

#ifdef VERBOSE_STATISTICS_ON

// compute statistics of really very very fast calls.
// It a bit decrease overal performance, but might be interested for
// investigation purpose (only)
//#define VERBOSE_STATISTICS_FASTCALLS_ON

struct ExecStatistics {
  unsigned TotalSteps, MCSFoundStep;
  unsigned long long MCSFoundTime;
  unsigned InitialSeed, MismatchedInitialSeed;
  unsigned Seed, RemainingSizeRejected;
  unsigned SeedCheck, SingleBondExcluded;
  unsigned MatchCall, MatchCallTrue;
  unsigned FastMatchCall, FastMatchCallTrue, SlowMatchCallTrue;
  unsigned ExactMatchCall, ExactMatchCallTrue;  // hash cache
  unsigned FindHashInCache, HashKeyFoundInCache;
  unsigned AtomCompareCalls, BondCompareCalls;  // long long
  unsigned AtomFunctorCalls, BondFunctorCalls;  // long long
  unsigned WrongCompositionRejected, WrongCompositionDetected;
  unsigned DupCacheFound, DupCacheFoundMatch;

  ExecStatistics()
      : TotalSteps(0),
        MCSFoundStep(0),
        MCSFoundTime(nanoClock()),
        InitialSeed(0),
        MismatchedInitialSeed(0),
        Seed(0),
        RemainingSizeRejected(0),
        SeedCheck(0),
        SingleBondExcluded(0),
        MatchCall(0),
        MatchCallTrue(0),
        FastMatchCall(0),
        FastMatchCallTrue(0),
        SlowMatchCallTrue(0),
        ExactMatchCall(0),
        ExactMatchCallTrue(0),
        FindHashInCache(0),
        HashKeyFoundInCache(0),
        AtomCompareCalls(0),
        BondCompareCalls(0),
        AtomFunctorCalls(0),
        BondFunctorCalls(0),
        WrongCompositionRejected(0),
        WrongCompositionDetected(0),
        DupCacheFound(0),
        DupCacheFoundMatch(0) {}
};
#endif
}
}


text:
/*
 * 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
 *
 *     http://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.
 */
package io.trino.plugin.iceberg;

import io.trino.plugin.hive.HdfsEnvironment;
import io.trino.plugin.hive.HdfsEnvironment.HdfsContext;
import org.apache.iceberg.io.FileIO;

import javax.inject.Inject;

import static java.util.Objects.requireNonNull;

public class HdfsFileIoProvider
        implements FileIoProvider
{
    private final HdfsEnvironment hdfsEnvironment;

    @Inject
    public HdfsFileIoProvider(HdfsEnvironment hdfsEnvironment)
    {
        this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null");
    }

    @Override
    public FileIO createFileIo(HdfsContext hdfsContext, String queryId)
    {
        return new HdfsFileIo(hdfsEnvironment, hdfsContext);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>

    <parent>
        <groupId>com.protonail.leveldb-jna</groupId>
        <artifactId>leveldb-jna</artifactId>
        <version>1.20.0</version>
    </parent>

    <artifactId>leveldb-jna-native</artifactId>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <excludeResources>true</excludeResources>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>native</id>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                        <configuration>
                            <classifier>${platform.classifier}</classifier>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-jar</id>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                        <configuration>
                            <classesDirectory>src/main/java</classesDirectory>
                            <excludes>
                                <exclude>src/main/resources</exclude>
                            </excludes>
                        </configuration>
                    </execution>
                    <execution>
                        <id>empty-javadoc</id>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                        <configuration>
                            <classifier>javadoc</classifier>
                            <classesDirectory>src/main/java</classesDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
layout: post
title: "Les Licences Ouvertes"
excerpt: "Quelques licences ouvertes, pour s'ouvrir l'esprit"
categories: articles
tags: [Droit, Ouvert, Libre]
comments: true
share: true
---

#Principales Licences Ouvertes

##Licences Creative Commons
Elles s'appliquent aux créations autres que les logiciels ("contenus").
Il existe six licence Creative Commons (CC) combinant une ou plusieurs de ces 4 clauses :
*attribution (clause toujours présente)
*pas de modifications (clause facultative)
*pas d'utilisation commerciale (clause facultative)
*partage dans les mêmes conditions (clause facultative).

Ces licences permettent à tout utilisateur (dont étudiants, enseignants, chercheurs) de reproduire et représenter en toutes circonstances, et en particulier dans le cadre de leur étude, enseignements et recherches, les oeuvres visées par ces licences. Certaines des licences autorisent également les modifications, ou les usages commerciaux.
Pour plus d'informations, consulter la Foire aux questions de Creative Commons France.
Les licences CC sont les plus importantes aujourd'hui et les plus utilisées par les auteurs, notamment sur Wikimedia Commons qui constitue une des plus conséquentes base de données d'oeuvres sous licences libres actuellement.

##Licences de la Free Software Foundation (FSF) (Fondation pour le Logiciel Libre)
La Free Software Foundation (FSF) fondation de droit américain créé par Richard Stallman (informaticien du MIT à l'origine du concept de logiciel libre) a défini plusieurs licences applicables selon la nature de l'oeuvre.
La principale licence est la GNU General public license (GPL) qui s'applique aux logiciels.
Elle accorde par avance à l'utilisateur les droits de :
*copier le logiciel ou contenu
*le rediffuser
*le modifier
*diffuser la version modifiée.

##Les licences BSD, MIT, ...
Va voir là et nous embete pas


text:
package jhc.redsniff.internal.finders;

import jhc.redsniff.core.SFinder;
import jhc.redsniff.internal.core.Item;

import org.hamcrest.Description;

public abstract class WrappingSFinder<E,  C> extends BaseSFinder<E, C> {
    protected final SFinder<E, C> wrappedFinder;

    public WrappingSFinder(SFinder<E, C> wrappedFinder) {
        this.wrappedFinder = wrappedFinder;
    }

    @Override
    public Item<E> findFrom(C context, Description notFoundDescription) {
        return wrappedFinder.findFrom(context, notFoundDescription);
    }

    @Override
    public void describeTo(Description description) {
        wrappedFinder.describeTo(description);
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\HearAbout */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
    <?php
    echo $form->field($model, 'isdescription')->dropDownList(
        [0 => 'No',1 => 'Yes'],
        [ 'class'=>'form-control select2' ]
    );
    ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
package lc.bullsandcows;

import java.util.HashMap;

public class Solution {

	// figure out what the problem is actually asking is the key.
	// thus once confused ask problems!
	// digits that match in position and digit exactly => bulls
	// digits that match the digit but locate in wrong pos => cows
	// thus the condition for a digit in the guess to become a cow is
	// that it is not a bull and there is a digit that are doesn't
	// correspond to the bull digit in guess that is identical to itself.
	// O(n) runtime and O(1) space in best case, O(n) space in the worst case
    public String getHint(String secret, String guess) {
        int bulls = 0, cows = 0;
		// corner case
		if(secret == null || secret.length() == 0) return bulls + "A" + cows + "B";

		HashMap<Character, Integer> sMap = new HashMap<>();
		HashMap<Character, Integer> gMap = new HashMap<>();
		// assume secret and guess has the same length
		for(int i = 0; i < secret.length(); i ++) {
			// check if secret[i] and guess[i] are identical or not
			// If so then guess[i] is a bull, thus don't need to include
			// secret[i] in sSet
			char sChar = secret.charAt(i);
			char gChar = guess.charAt(i);

			if(sChar == gChar) bulls ++;
			else {
				// not equal. Then we guarantee that chars in gSet so far are
				// not the bulls but can be candidate of cows
				if(gMap.containsKey(sChar)) {
					int tmp = gMap.get(sChar);
					cows ++;
					tmp --;
					if(tmp > 0) gMap.put(sChar, tmp);
					else gMap.remove(sChar);

				}else {
					if(!sMap.containsKey(sChar)) sMap.put(sChar, 1);
					else sMap.put(sChar, sMap.get(sChar) + 1);
				}

				// then it is the turn of guess side
				if(sMap.containsKey(gChar)) {
					int tmp = sMap.get(gChar);
					cows ++;
					tmp --;
					if(tmp > 0) sMap.put(gChar, tmp);
					else 		sMap.remove(gChar);
				} else {
					if(!gMap.containsKey(gChar)) gMap.put(gChar, 1);
					else gMap.put(gChar, gMap.get(gChar) + 1);
				}
			}
		}

		return bulls + "A" + cows + "B";
    }

	public static void main(String [] args) {

		String s = "0";
		String g = "1";

		Solution sol = new Solution();

		System.out.println(sol.getHint(s, g));
	}
}


text: <img src="<?php echo base_url(); ?>public/assets/images/live-chat-left_do.gif" />


text:
layout: post
title: Pretty blonde Elsa teases the camera before getting fucked
titleinfo: pornvd
desc: Watch Pretty blonde Elsa teases the camera before getting fucked. Pornhub is the ultimate xxx porn and sex site.
---

Pretty blonde Elsa teases the camera before getting fucked

Watch Pretty blonde Elsa teases the camera before getting fucked. Pornhub is the ultimate xxx porn and sex site.