text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Grid\Definition;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class Filter
{
    /**
     * @var string
     */
    private $name;

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

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

    /**
     * @var bool
     */
    private $enabled = true;

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

    /**
     * @var array
     */
    private $options = [];

    /**
     * @var array
     */
    private $formOptions = [];

    /**
     * @var mixed
     */
    private $criteria;

    /**
     * @var int
     *
     * Position equals to 100 to ensure that wile sorting filters by position ASC
     * the filters positioned by default will be last
     */
    private $position = 100;

    /**
     * @param string $name
     * @param string $type
     */
    private function __construct(string $name, string $type)
    {
        $this->name = $name;
        $this->type = $type;

        $this->label = $name;
    }

    /**
     * @param string $name
     * @param string $type
     *
     * @return self
     */
    public static function fromNameAndType(string $name, string $type): self
    {
        return new self($name, $type);
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getType(): string
    {
        return $this->type;
    }

    /**
     * @return mixed
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * @param mixed $label
     */
    public function setLabel($label): void
    {
        $this->label = $label;
    }

    /**
     * @return bool
     */
    public function isEnabled(): bool
    {
        return $this->enabled;
    }

    /**
     * @param bool $enabled
     */
    public function setEnabled(bool $enabled): void
    {
        $this->enabled = $enabled;
    }

    /**
     * @return string|null
     */
    public function getTemplate(): ?string
    {
        return $this->template;
    }

    /**
     * @param string $template
     */
    public function setTemplate(string $template): void
    {
        $this->template = $template;
    }

    /**
     * @return array
     */
    public function getOptions(): array
    {
        return $this->options;
    }

    /**
     * @param array $options
     */
    public function setOptions(array $options): void
    {
        $this->options = $options;
    }

    /**
     * @return array
     */
    public function getFormOptions(): array
    {
        return $this->formOptions;
    }

    /**
     * @param array $formOptions
     */
    public function setFormOptions(array $formOptions): void
    {
        $this->formOptions = $formOptions;
    }

    /**
     * @return int
     */
    public function getPosition(): int
    {
        return $this->position;
    }

    /**
     * @param int $position
     */
    public function setPosition(int $position): void
    {
        $this->position = $position;
    }

    /**
     * @return mixed
     */
    public function getCriteria()
    {
        return $this->criteria;
    }

    /**
     * @param mixed $criteria
     */
    public function setCriteria($criteria)
    {
        $this->criteria = $criteria;
    }
}

redpajama_set_name: RedPajamaGithub


text:
[![PayPal][paypal-img]][paypal-url]

# Endless Sky Library

A wiki like library of data from the game Endless Sky.

[ES Library](https://OpenGameMods-group.github.io/ES-Library/)

[paypal-url]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=KV78TWKWKKK3S
[paypal-img]: https://img.shields.io/badge/donate-PayPal-blue.svg?style=flat-square


text:
<?php

namespace PhpSpec\Loader;

use PhpSpec\Util\MethodAnalyser;
use PhpSpec\Locator\ResourceManagerInterface;
use ReflectionClass;
use ReflectionMethod;

class ResourceLoader
{
    /**
     * @var ResourceManagerInterface
     */
    private $manager;
    /**
     * @var MethodAnalyser
     */
    private $methodAnalyser;

    /**
     * @param ResourceManagerInterface $manager
     */
    public function __construct(ResourceManagerInterface $manager, MethodAnalyser $methodAnalyser = null)
    {
        $this->manager = $manager;
        $this->methodAnalyser = $methodAnalyser ?: new MethodAnalyser();
    }

    /**
     * @param string       $locator
     * @param integer|null $line
     *
     * @return Suite
     */
    public function load($locator, $line = null)
    {
        $suite = new Suite();
        foreach ($this->manager->locateResources($locator) as $resource) {
            if (!class_exists($resource->getSpecClassname()) && is_file($resource->getSpecFilename())) {
                require_once $resource->getSpecFilename();
            }
            if (!class_exists($resource->getSpecClassname())) {
                continue;
            }

            $reflection = new ReflectionClass($resource->getSpecClassname());

            if ($reflection->isAbstract()) {
                continue;
            }
            if (!$reflection->implementsInterface('PhpSpec\SpecificationInterface')) {
                continue;
            }

            $spec = new Node\SpecificationNode($resource->getSrcClassname(), $reflection, $resource);
            foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                if (!preg_match('/^[Ii](?:ts|t)/', $method->getName())) {
                    continue;
                }
                if (null !== $line && !$this->lineIsInsideMethod($line, $method)) {
                    continue;
                }

                $example
                    = new Node\ExampleNode(ucfirst($this->smartExampleNameSplitter($method->getName())),
                    $method);

                if ($this->methodAnalyser->reflectionMethodIsEmpty($method)) {
                    $example->markAsPending();
                }

                $spec->addExample($example);
            }

            $suite->addSpecification($spec);
        }

        return $suite;
    }

    /**
     * @param int              $line
     * @param ReflectionMethod $method
     *
     * @return bool
     */
    private function lineIsInsideMethod($line, ReflectionMethod $method)
    {
        $line = intval($line);

        return $line >= $method->getStartLine() && $line <= $method->getEndLine();
    }
    /**
     * Detects underscore_case vs camelCase or PascalCase and splits into words
     * accordingly.
     *
     * @param $name
     *
     * @return string
     *
     * @author Michael Cummings <mgcummings@yahoo.com>
     */
    private function smartExampleNameSplitter($name)
    {
        if ('_' === $name[2] || '_' === $name[3]) {
            return str_replace('_', ' ', $name);
        }
        $split = preg_split('/(^[^A-Z]+|[A-Z][^A-Z]+)/', $name, null,
            PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        return strtolower(implode(' ', $split));
    }
}


text:
<?php

namespace Drupal\pathauto\Plugin\pathauto\AliasType;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\ContextAwarePluginBase;
use Drupal\pathauto\AliasTypeBatchUpdateInterface;
use Drupal\pathauto\AliasTypeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A pathauto alias type plugin for entities with canonical links.
 *
 * @AliasType(
 *   id = "canonical_entities",
 *   deriver = "\Drupal\pathauto\Plugin\Deriver\EntityAliasTypeDeriver"
 * )
 */
class EntityAliasTypeBase extends ContextAwarePluginBase implements AliasTypeInterface, AliasTypeBatchUpdateInterface, ContainerFactoryPluginInterface {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The language manager service.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The entity manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The path prefix for this entity type.
   *
   * @var string
   */
  protected $prefix;

  /**
   * Constructs a EntityAliasTypeBase instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ModuleHandlerInterface $module_handler, LanguageManagerInterface $language_manager, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->moduleHandler = $module_handler;
    $this->languageManager = $language_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('module_handler'),
      $container->get('language_manager'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getLabel() {
    $definition = $this->getPluginDefinition();
    // Cast the admin label to a string since it is an object.
    // @see \Drupal\Core\StringTranslation\TranslationWrapper
    return (string) $definition['label'];
  }

  /**
   * {@inheritdoc}
   */
  public function getTokenTypes() {
    $definition = $this->getPluginDefinition();
    return $definition['types'];
  }

  /**
   * {@inheritdoc}
   */
  public function batchUpdate(&$context) {
    if (!isset($context['sandbox']['current'])) {
      $context['sandbox']['count'] = 0;
      $context['sandbox']['current'] = 0;
    }

    $entity_type = $this->entityTypeManager->getDefinition($this->getEntityTypeId());
    $id_key = $entity_type->getKey('id');

    $query = db_select($entity_type->get('base_table'), 'base_table');
    $query->leftJoin('url_alias', 'ua', "CONCAT('" . $this->getSourcePrefix() . "' , base_table.$id_key) = ua.source");
    $query->addField('base_table', $id_key, 'id');
    $query->isNull('ua.source');
    $query->condition('base_table.' . $id_key, $context['sandbox']['current'], '>');
    $query->orderBy('base_table.' . $id_key);
    $query->addTag('pathauto_bulk_update');
    $query->addMetaData('entity', $this->getEntityTypeId());

    // Get the total amount of items to process.
    if (!isset($context['sandbox']['total'])) {
      $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();

      // If there are no entities to update, then stop immediately.
      if (!$context['sandbox']['total']) {
        $context['finished'] = 1;
        return;
      }
    }

    $query->range(0, 25);
    $ids = $query->execute()->fetchCol();

    $this->bulkUpdate($ids);
    $context['sandbox']['count'] += count($ids);
    $context['sandbox']['current'] = max($ids);
    $context['message'] = t('Updated alias for %label @id.', array('%label' => $entity_type->getLabel(), '@id' => end($ids)));

    if ($context['sandbox']['count'] != $context['sandbox']['total']) {
      $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
    }
  }

  /**
   * Returns the entity type ID.
   *
   * @return string
   *   The entity type ID.
   */
  protected function getEntityTypeId() {
    return $this->getDerivativeId();
  }

  /**
   * Update the URL aliases for multiple entities.
   *
   * @param array $ids
   *   An array of entity IDs IDs.
   * @param array $options
   *   An optional array of additional options.
   */
  protected function bulkUpdate(array $ids, array $options = array()) {
    $options += array('message' => FALSE);

    $entities = $this->entityTypeManager->getStorage($this->getEntityTypeId())->loadMultiple($ids);
    foreach ($entities as $entity) {
      // Update aliases for the entity's default language and its translations.
      foreach ($entity->getTranslationLanguages() as $langcode => $language) {
        $translated_entity = $entity->getTranslation($langcode);
        \Drupal::service('pathauto.generator')->updateEntityAlias($translated_entity, 'bulkupdate', $options);
      }
    }

    if (!empty($options['message'])) {
      drupal_set_message(\Drupal::translation()->formatPlural(count($ids), 'Updated 1 %label URL alias.', 'Updated @count %label URL aliases.'), array('%label' => $this->getLabel()));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = [];
    $dependencies['module'][] = $this->entityTypeManager->getDefinition($this->getEntityTypeId())->getProvider();
    return $dependencies;
  }

  /**
   * {@inheritdoc}
   */
  public function applies($object) {
    return $object instanceof FieldableEntityInterface && $object->getEntityTypeId() == $this->getEntityTypeId();
  }

  /**
   * {@inheritdoc}
   */
  public function getSourcePrefix() {
    if (empty($this->prefix)) {
      $entity_type = $this->entityTypeManager->getDefinition($this->getEntityTypeId());
      $path = $entity_type->getLinkTemplate('canonical');
      $this->prefix = substr($path, 0, strpos($path, '{'));
    }
    return $this->prefix;
  }

}


text:
from os import listdir, chdir
from os.path import dirname, abspath, isfile, join
from subprocess import call
import sys

def run_python( file ):
    run_cmd( "python3 " + file )

def run_cmd( cmdline, expected_ret_code=0 ):
    if expected_ret_code:
        print ( "\033[90mRunning: '%s' \t(expecting %s ret code)\033[0m" % ( cmdline, expected_ret_code ) )
    else:
        print ( "\033[90mRunning: '%s'\033[0m" % ( cmdline, ) )
    try:
        retcode = call( cmdline, shell=True )
        if retcode < 0:
            print ( "\033[0;41mTest failed, child was terminated by signal %s\033[0m" % ( -retcode, ), file=sys.stderr )
        else:
            if expected_ret_code == "nonzero":
                if retcode == 0:
                    print ( "\033[0;41mExpected nonzero return code but was %s\033[0m" % ( retcode, ), file=sys.stderr )
            elif retcode != expected_ret_code:
                print ( "\033[0;41mExpected return code %s but was %s\033[0m" % ( expected_ret_code, retcode ), file=sys.stderr )
    except OSError as e:
        print ( "Execution failed: %s" % ( e, ), file=sys.stderr )
        raise

current_script_dir = dirname( abspath( __file__ ) )
chdir( current_script_dir )

options = """-vquiet -nobc -notx"""

# print options and quit
run_cmd( """txc -help >/dev/null""" )

# invalid options should return 1
run_cmd( """txc -foobar 2>/dev/null""", 1 )

# empty source file
run_cmd( """echo "" | txc -nojit """ + options)

# minimal source file containing syntax error, should return 1
run_cmd( """echo "unrecoverably bad syntax {" | txc -nojit """ + options + """ 2>/dev/null""", 1 )

# minimal source file containing semantic error, should return 2
run_cmd( """echo "X : Int = 1.1;" | txc -nojit -compileall """ + options + """ 2>/dev/null""", 2 )

# run minimal source file (implicit 'return 0')
run_cmd( """echo "main() : ;" | txc -jit """ + options )

# run minimal source file with explicit 'return 0'
run_cmd( """echo "main()->Int : return 0" | txc -jit """ + options )

# test assertions
run_cmd( """echo "main()->Int : { assert TRUE;  return 0; }" | txc -jit """ + options )
run_cmd( """echo "main()->Int : { assert FALSE; return 0; }" | txc -jit """ + options + """ >/dev/null""", "nonzero" )


text:
package com.thinkaurelius.titan.diskstorage.configuration;

/**
 * @author Matthias Broecheler (me@matthiasb.com)
 */
public interface ConcurrentWriteConfiguration extends WriteConfiguration {

    public<O> void set(String key, O value, O expectedValue);

}


text:
package com.test.dao;

public class UserDaoImpl {
	public void updateUser() {
		System.out.println("update user");
//		Object proxy = AopContext.currentProxy();
//		((UserDaoImpl) proxy).deleteUser();
	}

	public void deleteUser() {
		System.out.println("delete user");
	}

}


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

	<title>{% block title %}{{ title }}{% endblock %}</title>

	<meta name="viewport" content="width=device-width"/>

	<meta name="Description" content="{{ page.templateData.metaDescription }}" />

	<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://feeds.feedburner.com/NakedItchyFeet" />

	<link href="{{ page|basePath }}styles/styles.css" rel="stylesheet" type="text/css">

				{% if page.prettyUrl === '/' -%}
					Naked Itchy Feet
				{%- else -%}
					Naked Itchy Feet
				{%- endif %}

							Blog

							Our Map

							About Us

							Follow Us

		{% block bodyContent %}{% endblock %}

	{% if bodyId !== 'map' -%}

	{%- endif %}

	{% for path in options.jsLibs -%}

	{% endfor %}


text:
package com.hp.ov.sdk.resources.network;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(format = { "pretty", "html:target/cucumber" },
    glue = { "com.hp.ov.sdk.resources" },
    features = "classpath:cucumber/network/fabric.feature",
    monochrome = true,
    tags = "@getAll, @get, @update")

public class FabricBDDTestSynergy {

}


text:
  <link rel="stylesheet" href="../resources/examples.css">

  <link rel="stylesheet" href="../resources/monokai_sublime.css">

// sketch.js
function setup() {
  createCanvas( windowWidth, windowHeight )

  drums = EDrums('x*o*x*o-')
  follow = Follow( drums )
}

function draw() {
  background( follow.getValue() * 255 )
}


text:
'use strict';

describe('', function () {

    var module;
    var dependencies;
    dependencies = [];

    var hasModule = function (module) {
        return dependencies.indexOf(module) >= 0;
    };

    beforeEach(function () {

        // Get module
        module = angular.module('smac');
        dependencies = module.requires;
    });

    it('should load config module', function () {
        expect(hasModule('smac.config')).to.be.ok;
    });

    it('should load filters module', function () {
        expect(hasModule('smac.filters')).to.be.ok;
    });

    it('should load directives module', function () {
        expect(hasModule('smac.directives')).to.be.ok;
    });

    it('should load services module', function () {
        expect(hasModule('smac.services')).to.be.ok;
    });

});


text:
// (C) Copyright 2015 Moodle Pty Ltd.
//
// 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.

import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';

import { CoreDelegate, CoreDelegateHandler } from '@classes/delegate';
import { CoreUtils } from '@services/utils/utils';
import { CoreEvents } from '@singletons/events';
import { CoreUserProfile, CoreUserProvider } from './user';
import { makeSingleton } from '@singletons';
import { CoreCourses, CoreCourseUserAdminOrNavOptionIndexed } from '@features/courses/services/courses';
import { CoreSites } from '@services/sites';

/**
 * Interface that all user profile handlers must implement.
 */
export interface CoreUserProfileHandler extends CoreDelegateHandler {
    /**
     * The highest priority is displayed first.
     */
    priority: number;

    /**
     * A type should be specified among these:
     * - TYPE_COMMUNICATION: will be displayed under the user avatar. Should have icon. Spinner not used.
     * - TYPE_NEW_PAGE: will be displayed as a list of items. Should have icon. Spinner not used.
     *     Default value if none is specified.
     * - TYPE_ACTION: will be displayed as a button and should not redirect to any state. Spinner use is recommended.
     */
    type: string;

    /**
     * If isEnabledForUser Cache should be enabled.
     */
    cacheEnabled?: boolean;

    /**
     * Whether or not the handler is enabled for a context.
     *
     * @param context Context.
     * @param contextId Context ID.
     * @param navOptions Navigation options for the course.
     * @param admOptions Admin options for the course.
     * @return Whether or not the handler is enabled for a user.
     */
    isEnabledForContext?(
        context: CoreUserDelegateContext,
        contextId: number,
        navOptions?: CoreCourseUserAdminOrNavOptionIndexed,
        admOptions?: CoreCourseUserAdminOrNavOptionIndexed,
    ): Promise<boolean>;

    /**
     * Whether or not the handler is enabled for a user.
     *
     * @param user User object.
     * @param context Context.
     * @param contextId Context ID.
     * @return Whether or not the handler is enabled for a user.
     */
    isEnabledForUser?(user: CoreUserProfile, context: CoreUserDelegateContext, contextId: number): Promise<boolean>;

    /**
     * Returns the data needed to render the handler.
     *
     * @param user User object.
     * @param context Context.
     * @param contextId Context ID.
     * @return Data to be shown.
     */
    getDisplayData(user: CoreUserProfile, context: CoreUserDelegateContext, contextId: number): CoreUserProfileHandlerData;
}

/**
 * Data needed to render a user profile handler. It's returned by the handler.
 */
export interface CoreUserProfileHandlerData {
    /**
     * Title to display.
     */
    title: string;

    /**
     * Name of the icon to display. Mandatory for TYPE_COMMUNICATION.
     */
    icon?: string;

    /**
     * Additional class to add to the HTML.
     */
    class?: string;

    /**
     * If enabled, element will be hidden. Only for TYPE_NEW_PAGE and TYPE_ACTION.
     */
    hidden?: boolean;

    /**
     * If enabled will show an spinner. Only for TYPE_ACTION.
     */
    spinner?: boolean;

    /**
     * If the handler has badge to show or not. Only for TYPE_NEW_PAGE.
     */
    showBadge?: boolean;

    /**
     * Text to display on the badge. Only used if showBadge is true and only for TYPE_NEW_PAGE.
     */
    badge?: string;

    /**
     * Accessibility text to add on the badge. Only used if showBadge is true and only for TYPE_NEW_PAGE.
     */
    badgeA11yText?: string;

    /**
     * If true, the badge number is being loaded. Only used if showBadge is true and only for TYPE_NEW_PAGE.
     */
    loading?: boolean;

    /**
     * Action to do when clicked.
     *
     * @param event Click event.
     * @param user User object.
     * @param context Context.
     * @param contextId Context ID.
     */
    action(event: Event, user: CoreUserProfile, context: CoreUserDelegateContext, contextId?: number): void;
}

/**
 * Data returned by the delegate for each handler.
 */
export interface CoreUserProfileHandlerToDisplay {
    /**
     * Name of the handler.
     */
    name?: string;

    /**
     * Data to display.
     */
    data: CoreUserProfileHandlerData;

    /**
     * The highest priority is displayed first.
     */
    priority?: number;

    /**
     * The type of the handler. See CoreUserProfileHandler.
     */
    type: string;
}

/**
 * Service to interact with plugins to be shown in user profile. Provides functions to register a plugin
 * and notify an update in the data.
 */
@Injectable({ providedIn: 'root' })
export class CoreUserDelegateService extends CoreDelegate<CoreUserProfileHandler> {

    /**
     * User profile handler type for communication.
     */
    static readonly TYPE_COMMUNICATION = 'communication';
    /**
     * User profile handler type for new page.
     */
    static readonly TYPE_NEW_PAGE = 'newpage';
    /**
     * User profile handler type for actions.
     */
    static readonly TYPE_ACTION = 'action';

    /**
     * Update handler information event.
     */
    static readonly UPDATE_HANDLER_EVENT = 'CoreUserDelegate_update_handler_event';

    /**
     * Cache object that checks enabled for use.
     */
    protected enabledForUserCache: Record<string, Record<string, boolean>> = {};

    protected featurePrefix = 'CoreUserDelegate_';

    // Hold the handlers and the observable to notify them for each user.
    protected userHandlers: Record<number, Record<string, CoreUserDelegateHandlersData>> = {};

    constructor() {
        super('CoreUserDelegate', true);

        CoreEvents.on(CoreUserDelegateService.UPDATE_HANDLER_EVENT, (data) => {
            const handlersData = this.getHandlersData(data.userId, data.context, data.contextId);

            // Search the handler.
            const handler = handlersData.handlers.find((userHandler) => userHandler.name == data.handler);

            if (!handler) {
                return;
            }

            // Update the data and notify.
            Object.assign(handler.data, data.data);
            handlersData.observable.next(handlersData.handlers);
        });

        CoreEvents.on(CoreEvents.LOGOUT, () => {
            this.clearHandlerCache();
        });

        CoreEvents.on(CoreUserProvider.PROFILE_REFRESHED, (data) => {
            const context = data.courseId ? CoreUserDelegateContext.COURSE : CoreUserDelegateContext.SITE;
            this.clearHandlerCache(data.userId, context, data.courseId);
        });
    }

    /**
     * Check if handlers are loaded for a certain user and context.
     *
     * @param userId User ID.
     * @param context Context.
     * @param contextId Context ID.
     * @return True if handlers are loaded, false otherwise.
     */
    areHandlersLoaded(userId: number, context: CoreUserDelegateContext, contextId?: number): boolean {
        return this.getHandlersData(userId, context, contextId).loaded;
    }

    /**
     * Clear current user handlers.
     *
     * @param userId The user to clear. Undefined for all users.
     * @param context Context.
     * @param contextId Context ID.
     */
    clearUserHandlers(userId?: number, context?: CoreUserDelegateContext, contextId?: number): void {
        if (!userId) {
            this.userHandlers = {};
        } else if (!context) {
            delete this.userHandlers[userId];
        } else {
            const handlersData = this.getHandlersData(userId, context, contextId);

            handlersData.handlers = [];
            handlersData.observable.next([]);
            handlersData.loaded = false;
        }
    }

    /**
     * Get the profile handlers for a user.
     *
     * @param user The user object.
     * @param context Context.
     * @param contextId Context ID.
     * @return Resolved with the handlers.
     */
    getProfileHandlersFor(
        user: CoreUserProfile,
        context: CoreUserDelegateContext,
        contextId?: number,
    ): Subject<CoreUserProfileHandlerToDisplay[]> {
        this.calculateUserHandlers(user, context, contextId);

        return this.getHandlersData(user.id, context, contextId).observable;
    }

    /**
     * Get the profile handlers for a user.
     *
     * @param user The user object.
     * @param context Context.
     * @param contextId Context ID.
     * @return Promise resolved when done.
     */
    protected async calculateUserHandlers(
        user: CoreUserProfile,
        context: CoreUserDelegateContext,
        contextId?: number,
    ): Promise<void> {
        // Get course options.
        const courses = await CoreCourses.getUserCourses(true);
        const courseIds = courses.map((course) => course.id);

        const options = await CoreCourses.getCoursesAdminAndNavOptions(courseIds);

        const courseId = context === CoreUserDelegateContext.COURSE && contextId ? contextId : CoreSites.getCurrentSiteHomeId();

        const navOptions = options.navOptions[courseId];
        const admOptions = options.admOptions[courseId];

        const handlersData = this.getHandlersData(user.id, context, contextId);
        handlersData.handlers = [];

        await CoreUtils.allPromises(Object.keys(this.enabledHandlers).map(async (name) => {
            // Checks if the handler is enabled for the user.
            const handler = this.handlers[name];

            try {
                const enabled = await this.getAndCacheEnabledForUserFromHandler(
                    handler,
                    user,
                    context,
                    courseId,
                    navOptions,
                    admOptions,
                );

                if (enabled) {
                    handlersData.handlers.push({
                        name: name,
                        data: handler.getDisplayData(user, context, courseId),
                        priority: handler.priority || 0,
                        type: handler.type || CoreUserDelegateService.TYPE_NEW_PAGE,
                    });
                }
            } catch {
                // Nothing to do here, it is not enabled for this user.
            }
        }));

        // Sort them by priority.
        handlersData.handlers.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
        handlersData.loaded = true;
        handlersData.observable.next(handlersData.handlers);
    }

    /**
     * Helper funtion to get enabled for user from the handler.
     *
     * @param handler Handler object.
     * @param user User object.
     * @param context Context.
     * @param contextId Context ID.
     * @param navOptions Navigation options for the course.
     * @param admOptions Admin options for the course.
     * @return Whether or not the handler is enabled for a user.
     */
    protected async getAndCacheEnabledForUserFromHandler(
        handler: CoreUserProfileHandler,
        user: CoreUserProfile,
        context: CoreUserDelegateContext,
        contextId: number,
        navOptions: CoreCourseUserAdminOrNavOptionIndexed = {},
        admOptions: CoreCourseUserAdminOrNavOptionIndexed = {},
    ): Promise<boolean> {
        if (handler.isEnabledForContext) {
            const enabledOnCourse = await handler.isEnabledForContext(context, contextId, navOptions, admOptions);

            if (!enabledOnCourse) {
                // If is not enabled in the course, is not enabled for the user.
                // Do not cache if this is false.
                return false;
            }
        }

        if (!handler.cacheEnabled) {
            if (!handler.isEnabledForUser) {
                // True by default.
                return true;
            }

            return handler.isEnabledForUser(user, context, contextId);
        }

        if (this.enabledForUserCache[handler.name] === undefined) {
            this.enabledForUserCache[handler.name] = {};
        }

        const cacheKey = this.getCacheKey(user.id, context, contextId);
        const cache = this.enabledForUserCache[handler.name][cacheKey];

        if (cache !== undefined) {
            return cache;
        }

        let enabled = true; // Default value.
        if (handler.isEnabledForUser) {
            enabled = await handler.isEnabledForUser(user, context, contextId);
        }

        this.enabledForUserCache[handler.name][cacheKey] = enabled;

        return enabled;
    }

    /**
     * Clear handler enabled for user cache.
     * If a userId and context are specified, it will only delete the entry for that user and context.
     *
     * @param userId User ID.
     * @param context Context.
     * @param contextId Context ID.
     */
    protected clearHandlerCache(userId?: number, context?: CoreUserDelegateContext, contextId?: number): void {
        if (userId && context) {
            const cacheKey = this.getCacheKey(userId, context, contextId);

            Object.keys(this.enabledHandlers).forEach((name) => {
                const cache = this.enabledForUserCache[name];

                if (cache) {
                    delete cache[cacheKey];
                }
            });
        } else {
            this.enabledForUserCache = {};
        }
    }

    /**
     * Get a cache key to identify a user and context.
     *
     * @param userId User ID.
     * @param context Context.
     * @param contextId Context ID.
     * @return Cache key.
     */
    protected getCacheKey(userId: number, context: CoreUserDelegateContext, contextId?: number): string {
        return `${userId}#${this.getContextKey(context, contextId)}`;
    }

    /**
     * Get a string to identify a context.
     *
     * @param context Context.
     * @param contextId Context ID.
     * @return String to identify the context.
     */
    protected getContextKey(context: CoreUserDelegateContext, contextId?: number): string {
        return `${context}#${contextId ?? 0}`;
    }

    /**
     * Get handlers data for a user and context.
     *
     * @param userId User ID.
     * @param context Context.
     * @param contextId Context ID.
     * @return Handlers data.
     */
    protected getHandlersData(userId: number, context: CoreUserDelegateContext, contextId?: number): CoreUserDelegateHandlersData {
        // Initialize the data if it doesn't exist.
        const contextKey = this.getContextKey(context, contextId);
        this.userHandlers[userId] = this.userHandlers[userId] || {};

        if (!this.userHandlers[userId][contextKey]) {
            this.userHandlers[userId][contextKey] = {
                loaded: false,
                handlers: [],
                observable: new BehaviorSubject<CoreUserProfileHandlerToDisplay[]>([]),
            };
        }

        return this.userHandlers[userId][contextKey];
    }

}

export const CoreUserDelegate = makeSingleton(CoreUserDelegateService);

/**
 * Handlers data for a user and context.
 */
type CoreUserDelegateHandlersData = {
    loaded: boolean; // Whether the handlers are loaded.
    handlers: CoreUserProfileHandlerToDisplay[]; // List of handlers.
    observable: Subject<CoreUserProfileHandlerToDisplay[]>; // Observable to notify the handlers.
};

/**
 * Context levels enumeration.
 */
export enum CoreUserDelegateContext {
    SITE = 'site',
    COURSE = 'course',
    USER_MENU = 'user_menu',
}

/**
 * Data passed to UPDATE_HANDLER_EVENT event.
 */
export type CoreUserUpdateHandlerData = {
    handler: string; // Name of the handler.
    userId: number; // User affected.
    context: CoreUserDelegateContext; // Context affected.
    contextId?: number; // ID related to the context.
    data: Record<string, unknown>; // Data to set to the handler.
};


text:
package com.orientechnologies.orient.core.query.live;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;

import com.orientechnologies.common.concur.resource.OCloseable;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseInternal;
import com.orientechnologies.orient.core.db.ODatabaseListener;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.hook.ODocumentHookAbstract;
import com.orientechnologies.orient.core.record.impl.ODocument;

/**
 * Created by luigidellaquila on 16/03/15.
 */
public class OLiveQueryHook extends ODocumentHookAbstract implements ODatabaseListener {

  static class OLiveQueryOps implements OCloseable {

    protected Map<ODatabaseDocument, List<ORecordOperation>> pendingOps  = new ConcurrentHashMap<ODatabaseDocument, List<ORecordOperation>>();
    OLiveQueryQueueThread                                    queueThread = new OLiveQueryQueueThread();
    Object                                                   threadLock  = new Object();

    @Override
    public void close() {
      queueThread.stopExecution();
      try {
        queueThread.join();
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
      pendingOps.clear();
    }
  }

  public OLiveQueryHook(ODatabaseDocumentTx db) {
    super(db);
    getOpsReference(db);
    db.registerListener(this);
  }

  private static OLiveQueryOps getOpsReference(ODatabaseInternal db) {
    return (OLiveQueryOps) db.getStorage().getResource("LiveQueryOps", new Callable<Object>() {
      @Override
      public Object call() throws Exception {
        return new OLiveQueryOps();
      }
    });
  }

  public static Integer subscribe(Integer token, OLiveQueryListener iListener, ODatabaseInternal db) {
    OLiveQueryOps ops = getOpsReference(db);
    synchronized (ops.threadLock) {
      if (!ops.queueThread.isAlive()) {
        ops.queueThread = ops.queueThread.clone();
        ops.queueThread.start();
      }
    }

    return ops.queueThread.subscribe(token, iListener);
  }

  public static void unsubscribe(Integer id, ODatabaseInternal db) {
    try {
      OLiveQueryOps ops = getOpsReference(db);
      synchronized (ops.threadLock) {
        ops.queueThread.unsubscribe(id);
      }
    } catch (Exception e) {
      OLogManager.instance().warn(OLiveQueryHook.class, "Error on unsubscribing client");
    }
  }

  @Override
  public void onCreate(ODatabase iDatabase) {

  }

  @Override
  public void onDelete(ODatabase iDatabase) {
    OLiveQueryOps ops = getOpsReference((ODatabaseInternal) iDatabase);
    synchronized (ops.pendingOps) {
      ops.pendingOps.remove(iDatabase);
    }
  }

  @Override
  public void onOpen(ODatabase iDatabase) {

  }

  @Override
  public void onBeforeTxBegin(ODatabase iDatabase) {

  }

  @Override
  public void onBeforeTxRollback(ODatabase iDatabase) {

  }

  @Override
  public void onAfterTxRollback(ODatabase iDatabase) {
    OLiveQueryOps ops = getOpsReference((ODatabaseInternal) iDatabase);
    synchronized (ops.pendingOps) {
      ops.pendingOps.remove(iDatabase);
    }
  }

  @Override
  public void onBeforeTxCommit(ODatabase iDatabase) {

  }

  @Override
  public void onAfterTxCommit(ODatabase iDatabase) {
    OLiveQueryOps ops = getOpsReference((ODatabaseInternal) iDatabase);
    List<ORecordOperation> list;
    synchronized (ops.pendingOps) {
      list = ops.pendingOps.remove(iDatabase);
    }
    // TODO sync
    if (list != null) {
      for (ORecordOperation item : list) {
        ops.queueThread.enqueue(item);
      }
    }
  }

  @Override
  public void onClose(ODatabase iDatabase) {
    OLiveQueryOps ops = getOpsReference((ODatabaseInternal) iDatabase);
    synchronized (ops.pendingOps) {
      ops.pendingOps.remove(iDatabase);
    }
  }

  @Override
  public void onBeforeCommand(OCommandRequestText iCommand, OCommandExecutor executor) {

  }

  @Override
  public void onAfterCommand(OCommandRequestText iCommand, OCommandExecutor executor, Object result) {

  }

  @Override
  public void onRecordAfterCreate(ODocument iDocument) {
    addOp(iDocument, ORecordOperation.CREATED);
  }

  @Override
  public void onRecordAfterUpdate(ODocument iDocument) {
    addOp(iDocument, ORecordOperation.UPDATED);
  }

  @Override
  public RESULT onRecordBeforeDelete(ODocument iDocument) {
    addOp(iDocument, ORecordOperation.DELETED);
    return RESULT.RECORD_NOT_CHANGED;
  }

  protected void addOp(ODocument iDocument, byte iType) {
    ODatabaseDocument db = database;
    OLiveQueryOps ops = getOpsReference((ODatabaseInternal) db);
    if (db.getTransaction() == null || !db.getTransaction().isActive()) {

      // TODO synchronize
      ORecordOperation op = new ORecordOperation(iDocument, iType);
      ops.queueThread.enqueue(op);
      return;
    }
    ORecordOperation result = new ORecordOperation(iDocument, iType);
    synchronized (ops.pendingOps) {
      List<ORecordOperation> list = ops.pendingOps.get(db);
      if (list == null) {
        list = new ArrayList<ORecordOperation>();
        ops.pendingOps.put(db, list);
      }
      list.add(result);
    }
  }

  @Override
  public boolean onCorruptionRepairDatabase(ODatabase iDatabase, String iReason, String iWhatWillbeFixed) {
    return false;
  }

  @Override
  public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() {
    return DISTRIBUTED_EXECUTION_MODE.BOTH;
  }
}


text:
package com.jtattoo.plaf.luna;

import javax.swing.*;
import javax.swing.plaf.*;

import com.jtattoo.plaf.*;

/**
 * @author  Michael Hagen
 */
public class LunaRootPaneUI extends BaseRootPaneUI {

    public static ComponentUI createUI(JComponent c) {
        return new LunaRootPaneUI();
    }

    public BaseTitlePane createTitlePane(JRootPane root) {
        return new LunaTitlePane(root, this);
    }
}


text:
import argparse
import cPickle
import glob
import os
import numpy as np
import pynet.datasets.preprocessor as procs

parser = argparse.ArgumentParser(description='pass numpy data file through an AutoEncoder,'
                                          + ' and save the encoded npy files')
parser.add_argument('--model', metavar='PATH', help='path for the model')
parser.add_argument('--preprocessor', metavar='NAME', help='name of the preprocessor')
parser.add_argument('--dataset', metavar='PATH', help='path to the numpy data file')
parser.add_argument('--output_spec_dtype',  default='f8', help='''dtype of the generated spec files f4|f8, default=f8''')
# parser.add_argument('--output_dir', metavar='DIR',
#                   help='directory to which to save the generated spec files')
parser.add_argument('--output_dir', metavar='DIR', help='''output dir for the mcep file''')
parser.add_argument('--specnames', metavar='PATH', help='''path to specnames npy files''')

args = parser.parse_args()

dtype = args.output_spec_dtype
outdir = args.output_dir
filename_files = args.specnames

assert dtype in ['f4', 'f8']

print 'opening model.. ' + args.model
with open(args.model) as m:
    model = cPickle.load(m)

datafiles = glob.glob(args.dataset)
filename_files = glob.glob(args.specnames)

data_paths = sorted(datafiles)
filename_paths = sorted(filename_files)

print 'npy Data paths: ', data_paths
print 'specnames paths: ', filename_paths

if not os.path.exists(args.output_dir):
    os.mkdir(args.output_dir)

assert len(filename_paths) == len(data_paths) and len(filename_paths) > 0

for f_path, fp in zip(data_paths, filename_paths):

    print 'opening.. ' + f_path
    data_fin = open(f_path)
    dataset_raw = np.load(data_fin)

    if args.preprocessor:
        proc = getattr(procs, args.preprocessor)()
        print 'applying preprocessing: ' + args.preprocessor
        dataset_proc = proc.apply(dataset_raw)
        if proc.__class__.__name__ == "Scale":
            print "global_max", proc.max
            print "global_min", proc.min

    else:
        dataset_proc = dataset_raw

    del dataset_raw
    print 'encoding..'
    dataset_out = model.encode(dataset_proc)
    del dataset_proc

    print '..opening specnames %s'%os.path.basename(fp)
    spec_fin = open(fp)
    f_arr = np.load(spec_fin)

    d_arr = dataset_out.astype(dtype)
    del dataset_out
    num_exp = [int(num) for f_name, num in f_arr]
    assert sum(num_exp) == d_arr.shape[0], 'number of examples in data array is different from the known number'

    pointer = 0
    for f_name, num in f_arr:
        print 'f_name, num_exp : %s, %s'%(f_name, num)
        f_name = f_name.rstrip('.f4')
        f_name = f_name.rstrip('.f8')
        d_arr[pointer:pointer+int(num)].tofile(outdir + '/' + f_name+'.%s'%dtype, format=dtype)
        pointer += int(num)

    assert pointer == d_arr.shape[0], 'did not recur until the end of array'

    data_fin.close()
    spec_fin.close()
    del d_arr

print 'All files saved to ' + outdir


text:
package com.francetelecom.clara.cloud.logicalmodel.samplecatalog;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

import com.francetelecom.clara.cloud.commons.MavenReference;

public class SampleAppPropertiesTest {

	SampleAppProperties mavenRefCatalog;

	@Before
	public void setup() {
		mavenRefCatalog = new SampleAppProperties();
	}

	@Test
	public void testGetSpringooEarMavenRef() {
		MavenReference ear = mavenRefCatalog.getMavenReference("springoo","ear");
		checkMavenReference(ear,"ear");
	}

	@Test
	public void testGetPaasWarMavenRef() {
		MavenReference ear = mavenRefCatalog.getMavenReference("elpaaso-tomcat","war");
		checkMavenReference(ear,"war");
	}

	@Test
	public void testGetConfigProbeEarMavenRef() {
		MavenReference ear = mavenRefCatalog.getMavenReference("config-probe","ear");
		checkMavenReference(ear,"ear");
	}

	@Test
	public void checkSimpleProbeJarMavenRef() {
		MavenReference jar = mavenRefCatalog.getMavenReference("simple-probe", "jar");
		checkMavenReference(jar, "jar");
	}

	@Test
	public void checkJeeProbeEarMavenRef() {
		MavenReference ear = mavenRefCatalog.getMavenReference("jeeprobe", "ear");
		checkMavenReference(ear, "ear");
	}

	private void checkMavenReference(MavenReference mr, String type) {

		assertNotNull(mr);
		assertNotNull("group-id is null "+mr, mr.getGroupId());
		assertNotNull("artifact-id is null "+mr, mr.getArtifactId());
		assertNotNull("version is null "+mr, mr.getVersion());
		assertEquals("invalid type " + mr, type, mr.getExtension());
//		assertNotNull("classifier is null "+mr,mr.getClassifier());

		String VERSION_PATTERN = "(\\d+\\.)*.*";
		assertTrue("version is valid "+mr, mr.getVersion().matches(VERSION_PATTERN));
	}

}


text:
({
    onClick: function(component, event, helper) {
        if (component._recentlyClicked) {
            return false;
        }

        if (event && $A.util.getBooleanValue(component.get("v.stopClickPropagation"))) {
            $A.util.squash(event);
        }

        var concreteCmp = component.getConcreteComponent();
        var concreteHelper = concreteCmp.helper;
        concreteHelper.handleTriggerPress(concreteCmp);
        helper.fireMenuTriggerPress(component);

        if ($A.util.getBooleanValue(component.get("v.disableDoubleClicks"))) {
            component._recentlyClicked = true;
            window.setTimeout($A.getCallback(function recentlyClicked() { component._recentlyClicked = false; }), 350);
        }
    },

    focus: function(component) {
        var concreteCmp = component.getConcreteComponent();
        //var concreteHelper = concreteCmp.helper || concreteCmp.getDef().getHelper();
        var concreteHelper = concreteCmp.helper;
        if (concreteHelper.focus) {
        	concreteHelper.focus(concreteCmp);
        }
    }
})// eslint-disable-line semi


text:
package org.hisp.dhis.programrule;

import java.util.List;

import org.hisp.dhis.program.Program;

/**
 *
 * @author markusbekken
 */
public interface ProgramRuleVariableService
{
    String ID = ProgramRuleVariableService.class.getName();

    /**
     * Adds an {@link ProgramRuleVariable}
     *
     * @param programRuleVariable The to ProgramRuleVariable add.
     * @return A generated unique id of the added {@link ProgramRuleVariable}.
     */
    int addProgramRuleVariable( ProgramRuleVariable programRuleVariable );

    /**
     * Deletes a {@link ProgramRuleVariable}
     *
     * @param programRuleVariable The ProgramRuleVariable to delete.
     */
    void deleteProgramRuleVariable( ProgramRuleVariable programRuleVariable );

    /**
     * Updates an {@link ProgramRuleVariable}.
     *
     * @param programRuleVariable The ProgramRuleVariable to update.
     */
    void updateProgramRuleVariable( ProgramRuleVariable programRuleVariable );

    /**
     * Returns a {@link ProgramRuleVariable}.
     *
     * @param id the id of the ProgramRuleVariable to return.
     * @return the ProgramRuleVariable with the given id
     */
    ProgramRuleVariable getProgramRuleVariable( int id );

    /**
     * Returns all {@link ProgramRuleVariable}.
     *
     * @return a List of all ProgramRuleVariable, or an empty List if
     * there are no ProgramRuleVariables.
     */
    List<ProgramRuleVariable> getAllProgramRuleVariable();

    /**
     * Get validation by {@link Program}
     *
     * @param program Program
     * @return ProgramRuleVariable list
     */
    List<ProgramRuleVariable> getProgramRuleVariable( Program program );
}


text:
package br.com.devfest.norte.wear;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import br.com.devfest.norte.R;

/**
 * A simple activity to show that the process of collection and submission of a session feedback has
 * finished. Note that there would be no indication of success or failure of the process.
 */
public class FinishActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finish);
        findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        Typeface typeFace = Typeface.createFromAsset(getAssets(), "RobotoCondensed-Light.ttf");
        TextView thanksText = (TextView) findViewById(R.id.thanks_text);
        thanksText.setTypeface(typeFace);
    }
}


text:
Amazing CSS

        <md-content>
            <md-tabs md-dynamic-height md-border-bottom>
                <md-tab label="Double Ring">
                    <md-content class="md-padding">
                        <double-ring text="doubleRing"></double-ring>
                        <md-button class="md-primary" target="_blank" href="http://codepen.io/fixcl/pen/lvCFr">Taken from here</md-button>
                    </md-content>
                </md-tab>
                <md-tab label="Mona Lisa">
                    <md-content class="md-padding">
                        <mona-lisa></mona-lisa>
                        <md-button class="md-primary" target="_blank" href="http://codepen.io/fixcl/pen/HaqBf">Taken from here</md-button>
                    </md-content>
                </md-tab>
                <md-tab label="Wall Clock">
                    <md-content class="md-padding">
                        <wall-clock></wall-clock>
                        <md-button class="md-primary" target="_blank" href="http://codepen.io/fixcl/pen/cvJmb">Taken from here</md-button>
                    </md-content>
                </md-tab>
            </md-tabs>
        </md-content>


text:
import styled from 'styled-components';

export default styled.div`
  width: 100%;
  max-width: 860px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 5rem;
`;


text:
<?php

declare(strict_types=1);

namespace Prooph\EventMachineTest\Messaging;

use Prooph\EventMachine\Eventing\GenericJsonSchemaEvent;
use Prooph\EventMachine\JsonSchema\JsonSchema;
use Prooph\EventMachineTest\BasicTestCase;

final class GenericJsonSchemaMessageTest extends BasicTestCase
{
    /**
     * @test
     */
    public function it_gets_payload_property()
    {
        $userWasRegistered = new GenericJsonSchemaEvent(
            'UserWasRegistered',
            ['username' => 'John'],
            JsonSchema::object(['username' => JsonSchema::string()])->toArray(),
            $this->getJsonSchemaAssertion()
        );

        $this->assertEquals('John', $userWasRegistered->get('username'));
    }

    /**
     * @test
     */
    public function it_throws_exception_if_payload_key_does_not_exist()
    {
        $userWasRegistered = new GenericJsonSchemaEvent(
            'UserWasRegistered',
            ['username' => 'John'],
            JsonSchema::object(['username' => JsonSchema::string()])->toArray(),
            $this->getJsonSchemaAssertion()
        );

        $this->expectException(\BadMethodCallException::class);
        $this->expectExceptionMessage('Message payload of UserWasRegistered does not contain a key name.');

        $userWasRegistered->get('name');
    }

    /**
     * @test
     */
    public function it_returns_default_if_payload_key_does_not_exist()
    {
        $userWasRegistered = new GenericJsonSchemaEvent(
            'UserWasRegistered',
            ['username' => 'John'],
            JsonSchema::object(['username' => JsonSchema::string()])->toArray(),
            $this->getJsonSchemaAssertion()
        );

        $this->assertEquals('Noname', $userWasRegistered->getOrDefault('name', 'Noname'));
    }
}


text:
package statusreaders

import (
	"context"
	"fmt"

	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"sigs.k8s.io/cli-utils/pkg/kstatus/polling/engine"
	"sigs.k8s.io/cli-utils/pkg/kstatus/polling/event"
	"sigs.k8s.io/cli-utils/pkg/kstatus/status"
	"sigs.k8s.io/cli-utils/pkg/object"
)

func newPodControllerStatusReader(mapper meta.RESTMapper, podStatusReader resourceTypeStatusReader) *podControllerStatusReader {
	return &podControllerStatusReader{
		mapper:          mapper,
		podStatusReader: podStatusReader,
		groupKind: schema.GroupKind{
			Group: "",
			Kind:  "Pod",
		},
		statusFunc:                status.Compute,
		statusForGenResourcesFunc: statusForGeneratedResources,
	}
}

// podControllerStatusReader encapsulates the logic needed to compute the status
// for resource types that act as controllers for pods. This is quite common, so
// the logic is here instead of duplicated in each resource specific StatusReader.
type podControllerStatusReader struct {
	mapper          meta.RESTMapper
	podStatusReader resourceTypeStatusReader
	groupKind       schema.GroupKind

	statusFunc func(u *unstructured.Unstructured) (*status.Result, error)
	// TODO(mortent): See if we can avoid this. For now it is useful for testing.
	statusForGenResourcesFunc statusForGenResourcesFunc
}

func (p *podControllerStatusReader) readStatus(ctx context.Context, reader engine.ClusterReader, obj *unstructured.Unstructured) (*event.ResourceStatus, error) {
	identifier := object.UnstructuredToObjMetadata(obj)

	podResourceStatuses, err := p.statusForGenResourcesFunc(ctx, p.mapper, reader, p.podStatusReader, obj,
		p.groupKind, "spec", "selector")
	if err != nil {
		return errResourceToResourceStatus(err, obj)
	}

	res, err := p.statusFunc(obj)
	if err != nil {
		return errResourceToResourceStatus(err, obj, podResourceStatuses...)
	}

	// If the status comes back as pending, we take a look at the pods to make sure
	// none of them are in the failed state. If at least one of them are, then
	// it is unlikely (but not impossible) that the status of the PodController will become
	// Current without some kind of intervention.
	if res.Status == status.InProgressStatus {
		var failedPods []*event.ResourceStatus
		for _, podResourceStatus := range podResourceStatuses {
			if podResourceStatus.Status == status.FailedStatus {
				failedPods = append(failedPods, podResourceStatus)
			}
		}
		if len(failedPods) > 0 {
			return &event.ResourceStatus{
				Identifier:         identifier,
				Status:             status.FailedStatus,
				Resource:           obj,
				Message:            fmt.Sprintf("%d pods have failed", len(failedPods)),
				GeneratedResources: podResourceStatuses,
			}, nil
		}
	}

	return &event.ResourceStatus{
		Identifier:         identifier,
		Status:             res.Status,
		Resource:           obj,
		Message:            res.Message,
		GeneratedResources: podResourceStatuses,
	}, nil
}


text:
> A lightweight wrapper around the array.

## API

```js
var cellophane = require('cellophane');
```

### Constructor

- [`cellophane([array])`](#cellophanearray)

### Methods

- [`.any(fn)`](#anyfn)
- [`.any(op, val)`](#anyop-val)
- [`.any(key, op, val)`](#anykey-op-val)
- [`.append(obj)`](#appendobj)
- [`.compact()`](#compact)
- [`.contains(obj [, opts])`](#containsobj--opts)
- [`.each(fn)`](#eachfn)
- [`.every(fn)`](#everyfn)
- [`.every(op, val)`](#everyop-val)
- [`.every(key, op, val)`](#everykey-op-val)
- [`.filter(fn)`](#filterfn)
- [`.filter(op, val)`](#filterop-val)
- [`.filter(key, op, val)`](#filterkey-op-val)
- [`.first([n])`](#firstn)
- [`.fold(fn, acc)`](#foldfn-acc)
- [`.foldRight(fn, acc)`](#foldrightfn-acc)
- [`.get(i)`](#geti)
- [`.indexOf(obj [, opts])`](#indexofobj--opts)
- [`.insert(obj, i)`](#insertobj-i)
- [`.last([n])`](#lastn)
- [`.limit(n)`](#limitn)
- [`.map(fn)`](#mapfn)
- [`.max([key])`](#maxkey)
- [`.min([key])`](#minkey)
- [`.prepend(obj)`](#prependobj)
- [`.remove(obj [, opts])`](#removeobj--opts)
- [`.removeAt(i)`](#removeati)
- [`.reverse()`](#reverse)
- [`.size()`](#size)
- [`.slice(i [, j])`](#slicei--j)
- [`.sort(comp)`](#sortcomp)
- [`.sort([opts])`](#sortopts)
- [`.sortBy(key [, opts])`](#sortbykey--opts)
- [`.unique([opts])`](#uniqueopts)
- [`.unwrap()`](#unwrap)

--

### cellophane([array])

Constructs a new Cellophane object. If `array` was specified, sets the Cellophane object's "internal" array to `array`. Throws if `array` is not an array.

```js
var a = cellophane();
var b = cellophane([]);
var c = cellophane([1, 2, 3]);
```

[↩](#constructor)

### .any(fn)

Returns `true` if the [`fn` iterator](#iterator-function-signature) is truthy for any object in the array.

```js
var c = cellophane([1, 2, 3]);

c.any(function(val, i, array) {
  return val > 1;
}); //=> true

c.any(function(val, i, array) {
  return val > 3;
}); //=> false
```

[↩](#methods)

### .any(op, val)

Returns `true` if the comparison with `val` using the [`op` operator](#operators-for-comparing-values) returns `true` for any object in the array.

```js
var c = cellophane([1, 2, 3]);

c.any('>', 1); //=> true
c.any('>', 3); //=> false
```

[↩](#methods)

### .any(key, op, val)

Returns `true` if the comparison with `val` using the [`op` operator](#operators-for-comparing-values) returns `true` for the value at `key` of any object in the array. `key` can be a [dot-delimited path](#accessing-nested-properties).

```js
var c = cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]);

c.any('foo', '>', 1); //=> true
c.any('foo', '>', 3); //=> false
```

[↩](#methods)

### .append(obj)

Adds `obj` to the end of the array, returning the result as a new Cellophane object.

*Aliases:* `add`, `push`

```js
cellophane([1, 2]).append(3); //=> cellophane([1, 2, 3])
```

[↩](#methods)

### .compact()

Returns a new Cellophane object with falsy values removed.

```js
cellophane([0, 1, 2, 3]).compact(); //=> cellophane([1, 2, 3])
```

[↩](#methods)

### .contains(obj [, opts])

Returns `true` if the array contains `obj`, with objects [compared by value](#compare-by-value). For strict comparison, set `opts.strict` to `true`.

```js
var c = cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]);

c.contains({ foo: 3 }); //=> true
c.contains({ foo: 3 }, { strict: true }); //=> false
```

[↩](#methods)

### .each(fn)

Calls the [`fn` iterator](#iterator-function-signature) on each object in the array, and returns the original Cellophane object. Return `false` in the `fn` iterator to break from the loop.

*Alias:* `forEach`

```js
cellophane([1, 2, 3]).each(function(val, i, array) {
  console.log(val, i, array);
  //=> 1, 0, [1, 2, 3]
  //=> 2, 1, [1, 2, 3]
  if (val === 2) {
    return false;
  }
});
```

[↩](#methods)

### .every(fn)

Returns `true` if the [`fn` iterator](#iterator-function-signature) is truthy for every object in the array.

```js
var c = cellophane([1, 2, 3]);

c.every(function(val, i, array) {
  return val < 4;
}); //=> true

c.every(function(val, i, array) {
  return val < 3;
}); //=> false
```

[↩](#methods)

### .every(op, val)

Returns `true` if the comparison with `val` using the [`op` operator](#operators-for-comparing-values) returns `true` for every object in the array.

```js
var c = cellophane([1, 2, 3]);

c.every('<', 4); //=> true
c.every('<', 3); //=> false
```

[↩](#methods)

### .every(key, op, val)

Returns `true` if the comparison with `val` using the [`op` operator](#operators-for-comparing-values) returns `true` for the value at `key` of every object in the array. `key` can be a [dot-delimited path](#accessing-nested-properties).

```js
var c = cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]);

c.every('foo', '<', 4); //=> true
c.every('foo', '<', 3); //=> false
```

[↩](#methods)

### .filter(fn)

Filters the array using the [`fn` iterator](#iterator-function-signature), returning the filtered result as a new Cellophane object.

```js
cellophane([1, 2, 3]).filter(function(val, i, array) {
  return val > 1;
}); //=> cellophane([2, 3])
```

[↩](#methods)

### .filter(op, val)

Filters the array. Objects that return `true` when compared with `val` using the [`op` operator](#operators-for-comparing-values) will be included in the filtered result. Returns the filtered result as a new Cellophane object.

```js
cellophane([1, 2, 3]).filter('>', 1); //=> cellophane([2, 3])
```

[↩](#methods)

### .filter(key, op, val)

Filters the array. Objects whose value at `key` returns `true` when compared with `val` using the [`op` operator](#operators-for-comparing-values) will be included in the filtered result. Returns the filtered result as a new Cellophane object. `key` can be a [dot-delimited path](#accessing-nested-properties).

```js
cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]).filter('foo', '>', 1);
//=> cellophane([
//     { foo: 2 },
//     { foo: 3 }
//   ])
```

[↩](#methods)

### .first([n])

Returns the first object in the array. If `n` is specified, returns the first `n` objects of the array as a new Cellophane object.

```js
var c = cellophane([1, 2, 3]);

c.first(); //=> 1
c.first(2); //=> cellophane([1, 2])
```

[↩](#methods)

### .fold(fn, acc)

Accumulates the objects in the array to a single value, with the accumulator value initialised to `acc`. Returns the final value of `acc`. If `acc` is an array, returns it wrapped in a new Cellophane object. The `fn` iterator takes 4 arguments:
- `acc` — The current value of the accumulator.
- `val` — The current value of the array being iterated over.
- `i` — The current index.
- `array` — The Cellophane object’s internal array.

*Aliases:* `foldLeft`, `foldl`, `reduce`, `reduceLeft`

```js
var c = cellophane([1, 2, 3]);

c.fold(function(acc, val, i, array) {
  return acc + val;
}, 0); //=> 6

c.fold(function(acc, val, i, array) {
  acc.push(val * 10);
  return acc;
}, []); //=> cellophane([10, 20, 30])
```

[↩](#methods)

### .foldRight(fn, acc)

Just like [`fold`](#foldfn-acc), but the array is iterated over from right to left.

*Aliases:* `foldr`, `reduceRight`

[↩](#methods)

### .get(i)

Returns the object at index `i` of the array, or `undefined` if `i` is an invalid index. If `i` is negative, indexing is from the *end* of the array (ie. index `-1` refers to the last object in the array, and so on).

```js
var c = cellophane([1, 2, 3]);

c.get(0); //=> 1
c.get(1); //=> 2
c.get(2); //=> 3
c.get(3); //=> undefined

c.get(-1); //=> 3
c.get(-2); //=> 2
c.get(-3); //=> 1
```

[↩](#methods)

### .indexOf(obj [, opts])

Returns the index of the first instance of `obj` in the array, with objects [compared by value](#compare-by-value). For strict comparison, set `opts.strict` to `true`. Returns `-1` if `obj` is not found in the array.

```js
var c = cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 2 },
  { foo: 3 }
]);

c.indexOf({ foo: 2 }); //=> 1

c.indexOf({ foo: 3 }); //=> 2
c.indexOf({ foo: 3 }, { strict: true }); //=> -1
```

[↩](#methods)

### .insert(obj, i)

Inserts `obj` at index `i` of the array, returning the result as a new Cellophane object. If `i` is negative, indexing is from the *end* of the array (ie. index `-1` refers to the last object in the array, and so on). If `i` is beyond the bounds of the original array, the resulting array is “expanded” accordingly.

```js
var c = cellophane([1, 2, 3]);

c.insert('foo', 0); //=> cellophane(['foo', 1, 2, 3])
c.insert('foo', 3); //=> cellophane([1, 2, 3, 'foo'])
c.insert('foo', 4); //=> cellophane([1, 2, 3, undefined, 'foo'])

c.insert('foo', -1); //=> cellophane([1, 2, 3, 'foo'])
c.insert('foo', -4); //=> cellophane(['foo', 1, 2, 3])
c.insert('foo', -5); //=> cellophane(['foo', undefined, 1, 2, 3])
```

[↩](#methods)

### .last([n])

Returns the last object in the array. If `n` is specified, returns the last `n` objects of the array as a new Cellophane object.

```js
var c = cellophane([1, 2, 3]);

c.last(); //=> 3
c.last(2); //=> cellophane([2, 3])
```

[↩](#methods)

### .limit(n)

If `n` is positive, returns the first `n` objects of the array as a new Cellophane object. Else returns the last `|n|` objects of the array as a new Cellophane object.

```js
var c = cellophane([1, 2, 3]);

c.limit(2); //=> cellophane([1, 2])
c.limit(-2); //=> cellophane([2, 3])
```

[↩](#methods)

### .map(fn)

Maps the array over the [`fn` iterator](#iterator-function-signature), returning the result as a new Cellophane object.

```js
cellophane([1, 2, 3]).map(function(val, i, array) {
  return val * 10;
}); //=> cellophane([10, 20, 30])
```

[↩](#methods)

### .max([key])

Returns the largest object in the array. If `key` was specified, compares the objects based on the value corresponding to `key`. `key` can be a [dot-delimited path](#accessing-nested-properties).

*Aliases:* `maximum`, `largest`

```js
cellophane([1, 2, 3]).max(); //=> 3

cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]).max('foo'); //=> { foo: 3 }
```

[↩](#methods)

### .min([key])

Returns the smallest object in the array. If `key` was specified, compares the objects based on the value corresponding to `key`. `key` can be a [dot-delimited path](#accessing-nested-properties).

*Aliases:* `minimum`, `smallest`

```js
cellophane([1, 2, 3]).min(); //=> 1

cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]).min('foo'); //=> { foo: 1 }
```

[↩](#methods)

### .prepend(obj)

Adds `obj` to the start of the array, returning the result as a new Cellophane object.

```js
cellophane([2, 3]).prepend(1); //=> cellophane([1, 2, 3])
```

[↩](#methods)

### .remove(obj [, opts])

Removes all objects that are equal to `obj` from the array, with objects [compared by value](https://github.com/substack/node-deep-equal). For strict comparison, set `opts.strict` to `true`. Returns the result as a new Cellophane object.

```js
cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 },
  { foo: 1 }
]).remove({ foo: 1 });
//=> cellophane([
//     { foo: 2 },
//     { foo: 3 }
//   ])

cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 },
  { foo: 1 }
]).remove({ foo: 1 }, { strict: true });
//=> cellophane([
//     { foo: 1 },
//     { foo: 2 },
//     { foo: 3 },
//     { foo: 1 }
//   ])
```

[↩](#methods)

### .removeAt(i)

Removes the object at index `i` of the array, returning the result as a new Cellophane object.

```js
cellophane([1, 2, 3]).removeAt(1); //=> cellophane([1, 3])
```

[↩](#methods)

### .reverse()

Returns a new Cellophane object with the ordering of its objects reversed.

```js
cellophane([1, 2, 3]).reverse(); //=> cellophane([3, 2, 1])
```

[↩](#methods)

### .size()

Returns the array size.

*Alias:* `length`

```js
cellophane([]).size(); //=> 0
cellophane([1, 2, 3]).size(); //=> 3
```

[↩](#methods)

### .slice(i [, j])

Takes a [slice](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) of the array and returns it as a new Cellophane object.

*Alias:* `subarray`

```js
cellophane([1, 2, 3]).slice(1, 3); //=> cellophane([2, 3])
```

[↩](#methods)

### .sort(comp)

[Sorts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) the array using the `comp` comparator function, returning the sorted result as a new Cellophane object. `comp` takes two arguments `a` and `b`, and must return:
- a negative value if `a` is to be ordered before `b`, or
- a positive value if `a` is to be ordered after `b`, or
- `0` if the ordering of `a` and `b` (with respect to each other) should be left unchanged.

```js
cellophane([3, 1, 2]).sort(function(a, b) {
  return a < b ? -1 : 1;
}); //=> cellophane([1, 2, 3])
```

[↩](#methods)

### .sort([opts])

Sorts the array in ascending order, returning the sorted result as a new Cellophane object. Set `opts.order` to `'desc'` to sort in descending order.

```js
cellophane([3, 1, 2]).sort(); //=> cellophane([1, 2, 3])
cellophane([3, 1, 2]).sort({ order: 'desc' }); //=> cellophane([3, 2, 1])
```

[↩](#methods)

### .sortBy(key [, opts])

Sorts the array of objects in ascending order based on the value corresponding to `key` of each object, returning the sorted result as a new Cellophane object. `key` can be a [dot-delimited path](#accessing-nested-properties). To sort in descending order, set `opts.order` to `'desc'`.

```js
var c = cellophane([
  { foo: 3 },
  { foo: 1 },
  { foo: 2 },
]);

c.sortBy('foo');
//=> cellophane([
//     { foo: 1 },
//     { foo: 2 },
//     { foo: 3 }
//   ])

c.sortBy('foo', { order: 'desc' });
//=> cellophane([
//     { foo: 3 },
//     { foo: 2 },
//     { foo: 1 }
//   ])
```

[↩](#methods)

### .unique([opts])

Removes duplicates removed from the array, with objects [compared by value](https://github.com/substack/node-deep-equal). For strict comparison, set `opts.strict` to `true`. Returns the result as a new Cellophane object.

```js
var c = cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 },
  { foo: 1 }
]);

c.unique();
//=> cellophane([
//     { foo: 1 },
//     { foo: 2 },
//     { foo: 3 }
//   ])

c.unique({ strict: true });
//=> cellophane([
//     { foo: 1 },
//     { foo: 2 },
//     { foo: 3 },
//     { foo: 1 }
//   ])
```

[↩](#methods)

### .unwrap()

Returns a *copy* of the Cellophane object’s “internal” array.

```js
cellophane([1, 2, 3]).unwrap(); //=> [1, 2, 3]
```

[↩](#methods)

## Usage notes

### Accessing the “internal” array

We can get the Cellophane object’s “internal” array on its `.array` attribute:

```js
var original = cellophane([{ foo: 1 }, { foo: 2 }, { foo: 3 }]);

console.log(original.array); //=> [{ foo: 1 }, { foo: 2 }, { foo: 3 }]
```

### Methods always return a *copy*

A Cellophane object is designed to be *immutable*. So, for all methods (apart from [`each`](#eachfn)) that returns a Cellophane object, it is actually a *copy* of the original Cellophane object that is returned:

```js
var filtered = original.filter('foo', '>', 1);

console.log(filtered === original); //=> false
```

By *copy*, we mean that while `filtered.array` and `original.array` are different arrays, and refer to *different* objects in memory…

```js
console.log(filtered.array === original.array); //=> false
```

…they actually contain references to the *same* objects:

```js
console.log(filtered.array[0] === original.array[1]); //=> true
console.log(filtered.array[1] === original.array[2]); //=> true
```

### Iterator function signature

For all methods that take an iterator `fn` (called over each object in the array), note that the iterator is passed 3 arguments:

- `val` — The current object of the array being iterated over.
- `i` — The index of the current object.
- `array` — The Cellophane object’s internal array.

The exceptions are the [`fold`](#foldfn-acc) and [`foldr`](#foldrfn-acc) methods; their `fn` iterator takes an additional `acc` accumulator argument.

### Compare by value

In the [`contains`](#containsobj--opts), [`indexOf`](#indexofobj--opts), and [`remove`](#removeobj--opts) methods, the default behavior is to compare objects by value. For example:

```js
cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]).contains({ foo: 3 }); //=> true
```

See [deep-equal](https://github.com/substack/node-deep-equal).

To use strict comparison (where objects `a` and `b` are considered as equal if and only if `a === b`), set `opts.strict` to `true`.

```js
var opts = { strict: true };

cellophane([
  { foo: 1 },
  { foo: 2 },
  { foo: 3 }
]).contains({ foo: 3 }, opts); //=> false
```

### Operators for comparing values

In the [`any`](#anyop-val), [`every`](#everyop-val), and [`filter`](#filterop-val) methods, the `op` argument must be one of the following strings:

- `'=='`
- `'==='`
- `'!='`
- `'!=='`
- `'<'`
- `'>'`
- `'<='`
- `'>='`

See [Versus.js](https://github.com/yuanqing/versus#usage).

### Accessing nested properties

In the [`any`](#anykey-op-val), [`every`](#everykey-op-val), [`filter`](#filterkey-op-val), and [`sortBy`](#sortbykey--opts) methods, access a nested object property by specifying a dot-delimited path as the `key`. For example:

```js
cellophane([
  { foo: { bar: 1 } },
  { foo: { bar: 2 } },
  { foo: { bar: 3 } }
]).any('foo.bar', '>', 0); //=> true
```

See [Jaunt.js](https://github.com/yuanqing/jaunt#jauntgetobj-path).

## Installation

Install via [npm](https://npmjs.com):

```bash
$ npm i --save cellophane
```

## Changelog

- 0.1.0
  - Initial release

## License

[MIT](https://github.com/yuanqing/cellophane/blob/master/LICENSE)


text:
from __future__ import division

import unittest

import numpy as np

from wyrm.types import Data
from wyrm.processing import swapaxes

class TestSwapaxes(unittest.TestCase):

    def setUp(self):
        raw = np.arange(2000).reshape(-1, 5)
        channels = ['ca1', 'ca2', 'cb1', 'cb2', 'cc1']
        time = np.linspace(0, 4000, 400, endpoint=False)
        fs = 100
        marker = [[100, 'foo'], [200, 'bar']]
        self.dat = Data(raw, [time, channels], ['time', 'channels'], ['ms', '#'])
        self.dat.fs = fs
        self.dat.markers = marker

    def test_swapaxes(self):
        """Swapping axes."""
        new = swapaxes(self.dat, 0, 1)
        self.assertTrue((new.axes[0] == self.dat.axes[1]).all())
        self.assertTrue((new.axes[1] == self.dat.axes[0]).all())
        self.assertEqual(new.names[0], self.dat.names[1])
        self.assertEqual(new.names[1], self.dat.names[0])
        self.assertEqual(new.units[0], self.dat.units[1])
        self.assertEqual(new.units[1], self.dat.units[0])
        self.assertEqual(new.data.shape[::-1], self.dat.data.shape)
        np.testing.assert_array_equal(new.data.swapaxes(0, 1), self.dat.data)

    def test_swapaxes_copy(self):
        """Swapaxes must not modify argument."""
        cpy = self.dat.copy()
        swapaxes(self.dat, 0, 1)
        self.assertEqual(cpy, self.dat)

    def test_swapaxes_twice(self):
        """Swapping the same axes twice must result in original."""
        dat = swapaxes(self.dat, 0, 1)
        dat = swapaxes(dat, 0, 1)
        self.assertEqual(dat, self.dat)

if __name__ == '__main__':
    unittest.main()


text:
package types

import (
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/docker/infrakit/spi/group"
	"github.com/docker/infrakit/spi/instance"
)

// Spec is the configuration schema for the plugin, provided in group.Spec.Properties
type Spec struct {
	Instance   InstancePlugin
	Flavor     FlavorPlugin
	Allocation AllocationMethod
}

// AllocationMethod defines the type of allocation and supervision needed by a flavor's Group.
type AllocationMethod struct {
	Size       uint
	LogicalIDs []instance.LogicalID
}

// InstancePlugin is the structure that describes an instance plugin.
type InstancePlugin struct {
	Plugin     string
	Properties *json.RawMessage // this will be the Spec of the plugin
}

// FlavorPlugin describes the flavor configuration
type FlavorPlugin struct {
	Plugin     string
	Properties *json.RawMessage // this will be the Spec of the plugin
}

// ParseProperties parses the group plugin properties JSON document in a group configuration.
func ParseProperties(config group.Spec) (Spec, error) {
	parsed := Spec{}
	if err := json.Unmarshal([]byte(RawMessage(config.Properties)), &parsed); err != nil {
		return parsed, fmt.Errorf("Invalid properties: %s", err)
	}
	return parsed, nil
}

// MustParse can be wrapped over ParseProperties to panic if parsing fails.
func MustParse(s Spec, e error) Spec {
	if e != nil {
		panic(e)
	}
	return s
}

func stableFormat(v interface{}) []byte {
	// Marshal the JSON to ensure stable key ordering.  This allows structurally-identical JSON to yield the same
	// hash even if the fields are reordered.

	unstable, err := json.Marshal(v)
	if err != nil {
		panic(err)
	}

	props := map[string]interface{}{}
	err = json.Unmarshal(unstable, &props)
	if err != nil {
		panic(err)
	}

	stable, err := json.MarshalIndent(props, "  ", "  ") // sorts the fields
	if err != nil {
		panic(err)
	}
	return stable
}

// InstanceHash computes a stable hash of the document in InstancePluginProperties.
func (c Spec) InstanceHash() string {
	// TODO(wfarner): This does not consider changes made by plugins that are not represented by user
	// configuration changes, such as if a plugin is updated.  We may be able to address this by resolving plugin
	// names to a versioned plugin identifier.

	hasher := sha1.New()
	hasher.Write(stableFormat(c.Instance))
	hasher.Write(stableFormat(c.Flavor))
	return base64.URLEncoding.EncodeToString(hasher.Sum(nil))
}

// RawMessage converts a pointer to a raw message to a copy of the value. If the pointer is nil, it returns
// an empty raw message.  This is useful for structs where fields are json.RawMessage pointers for bi-directional
// marshal and unmarshal (value receivers will encode base64 instead of raw json when marshaled), so bi-directional
// structs should use pointer fields.
func RawMessage(r *json.RawMessage) (raw json.RawMessage) {
	if r != nil {
		raw = *r
	}
	return
}


text:
package util

import (
	"fmt"
	"math/rand"
	"sort"
	"testing"
)

func shuffleSeries(slice []string) {
	for i := len(slice) - 1; i > 0; i-- {
		j := rand.Intn(i + 1)
		slice[i], slice[j] = slice[j], slice[i]
	}
}

func genRandString(i int) string {
	return fmt.Sprintf("metrictank.stats.env.instance%d.input.plugin%d.metrics_received.counter32", i/10, i)
}

func TestNaturalSort(t *testing.T) {

	numRandStrings := 10000
	randInput := make([]string, 0, numRandStrings)
	for i := 0; i < numRandStrings; i++ {
		randInput = append(randInput, genRandString(i))
	}

	shuffledRandInput := make([]string, numRandStrings)
	copy(shuffledRandInput, randInput)
	shuffleSeries(shuffledRandInput)

	cases := []struct {
		in     []string
		sorted []string
	}{
		{
			[]string{"series.name3.this4", "series.name2.this6", "series.name3.this20"},
			[]string{"series.name2.this6", "series.name3.this4", "series.name3.this20"},
		},
		{
			[]string{"series00030", "series0003d", "series0003"},
			[]string{"series0003", "series0003d", "series00030"},
		},
		{
			shuffledRandInput,
			randInput,
		},
	}
	for i, c := range cases {
		sorted := make([]string, len(c.in))
		copy(sorted, c.in)
		sort.Sort(NaturalSortStringSlice(sorted))

		for j := range sorted {
			if sorted[j] != c.sorted[j] {
				t.Fatalf("case %d: mismatch at pos %d. Expected %s but got %s", i, j, sorted[j], c.sorted[j])
			}
		}
	}
}

func BenchmarkNaturalSort_100(b *testing.B) {
	benchmarkNaturalSort(b, 100)
}

func BenchmarkNaturalSort_10000(b *testing.B) {
	benchmarkNaturalSort(b, 10000)
}

func BenchmarkNaturalSort_100000(b *testing.B) {
	benchmarkNaturalSort(b, 100000)
}

func benchmarkNaturalSort(b *testing.B, numSeries int) {
	var input []string
	for i := 0; i < numSeries; i++ {
		input = append(input, genRandString(i))
	}
	shuffleSeries(input)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		sort.Sort(NaturalSortStringSlice(input))
	}
}


text:
namespace ReferenceApiWeblessUmbraco.Areas.HelpPage.ModelDescriptions
{
    public class DictionaryModelDescription : KeyValuePairModelDescription
    {
    }
}


text:
module OData
  # An OData::Entity represents a single record returned by the service. All
  # Entities have a type and belong to a specific namespace. They are written
  # back to the service via the EntitySet they came from. OData::Entity
  # instances should not be instantiated directly; instead, they should either
  # be read or instantiated from their respective OData::EntitySet.
  class Entity
    # The Entity type name
    attr_reader :type
    # The OData::Service's namespace
    attr_reader :namespace
    # The OData::Service's identifying name
    attr_reader :service_name
    # Links to other OData entitites
    attr_reader :links
    # List of errors on entity
    attr_reader :errors

    PROPERTY_NOT_LOADED = :not_loaded

    # Initializes a bare Entity
    # @param options [Hash]
    def initialize(options = {})
      @type = options[:type]
      @namespace = options[:namespace]
      @service_name = options[:service_name]
      @links = options[:links] || {}
      @errors = []
    end

    # Returns name of Entity from Service specified type.
    # @return [String]
    def name
      @name ||= type.gsub(/#{namespace}\./, '')
    end

    # Get property value
    # @param property_name [to_s]
    # @return [*]
    def [](property_name)
      if get_property(property_name).is_a?(::OData::ComplexType)
        get_property(property_name)
      else
        get_property(property_name).value
      end
    rescue NoMethodError
      raise ArgumentError, "Unknown property: #{property_name}"
    end

    # Set property value
    # @param property_name [to_s]
    # @param value [*]
    def []=(property_name, value)
      properties[property_name.to_s].value = value
    rescue NoMethodError
      raise ArgumentError, "Unknown property: #{property_name}"
    end

    def get_property(property_name)
      prop_name = property_name.to_s
      # Property is lazy loaded
      if properties_xml_value.has_key?(prop_name)
        property = instantiate_property(prop_name, properties_xml_value[prop_name])
        set_property(prop_name, property.dup)
        properties_xml_value.delete(prop_name)
      end
      properties[prop_name]
    end

    def property_names
      [@properties_xml_value.andand.keys, @properties.andand.keys].compact.flatten
    end

    def associations
      @associations ||= OData::Association::Proxy.new(self)
    end

    # Create Entity with provided properties and options.
    # @param new_properties [Hash]
    # @param options [Hash]
    # @param [OData::Entity]
    def self.with_properties(new_properties = {}, options = {})
      entity = OData::Entity.new(options)
      entity.instance_eval do
        service.properties_for_entity(name).each do |property_name, instance|
          set_property(property_name, instance)
        end

        new_properties.each do |property_name, property_value|
          self[property_name.to_s] = property_value
        end
      end
      entity
    end

    # Create Entity from XML document with provided options.
    # @param xml_doc [Nokogiri::XML]
    # @param options [Hash]
    # @return [OData::Entity]
    def self.from_xml(xml_doc, options = {})
      return nil if xml_doc.nil?
      entity = OData::Entity.new(options)
      process_properties(entity, xml_doc)
      process_feed_property(entity, xml_doc, 'title')
      process_feed_property(entity, xml_doc, 'summary')
      process_links(entity, xml_doc)
      entity
    end

    # Converts Entity to its XML representation.
    # @return [String]
    def to_xml
      builder = Nokogiri::XML::Builder.new do |xml|
        xml.entry('xmlns'           => 'http://www.w3.org/2005/Atom',
                  'xmlns:data'      => 'http://schemas.microsoft.com/ado/2007/08/dataservices',
                  'xmlns:metadata'  => 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata',
                  'xmlns:georss'    => 'http://www.georss.org/georss',
                  'xmlns:gml'       => 'http://www.opengis.net/gml',
                  'xml:base'        => 'http://services.odata.org/OData/OData.svc/') do
          xml.category(term: "#{namespace}.#{type}",
                       scheme: 'http://schemas.microsoft.com/ado/2007/08/dataservices/scheme')
          xml.author { xml.name }

          xml.content(type: 'application/xml') do
            xml['metadata'].properties do
              properties.keys.each do |name|
                next if name == primary_key
                get_property(name).to_xml(xml)
              end
            end
          end
        end
      end
      builder.to_xml
    end

    # Returns the primary key for the Entity.
    # @return [String]
    def primary_key
      service.primary_key_for(name)
    end

    def is_new?
      self[primary_key].nil?
    end

    def any_errors?
      !errors.empty?
    end

    private

    def instantiate_property(property_name, value)
      value_type = service.get_property_type(name, property_name)
      klass = ::OData::PropertyRegistry[value_type]

      if klass.nil? && value_type =~ /^#{namespace}\./
        type_name = value_type.gsub(/^#{namespace}\./, '')
        property = ::OData::ComplexType.new(name: type_name, service: service)
        value.element_children.each do |node|
          property[node.name] = node.content
        end
        property
      elsif klass.nil?
        raise RuntimeError, "Unknown property type: #{value_type}"
      else
        value_content = value.content unless value.nil?
        klass.new(property_name, value_content)
      end
    end

    def properties
      @properties ||= {}
    end

    def properties_xml_value
      @properties_xml_value ||= {}
    end

    def service
      @service ||= OData::ServiceRegistry[service_name]
    end

    def set_property(name, property)
      properties[name.to_s] = property
    end

    # Instantiating properties takes time, so we can lazy load properties by passing xml_value and lookup when needed
    def set_property_lazy_load(name, xml_value )
      properties_xml_value[name.to_s] = xml_value
    end

    def self.process_properties(entity, xml_doc)
      entity.instance_eval do
        xml_doc.xpath('./content/properties/*').each do |property_xml|
          property_name = property_xml.name
          if property_xml.attributes['null'] &&
              property_xml.attributes['null'].value == 'true'
            xml_value = nil
          else
            xml_value = property_xml
          end
          # Doing lazy loading here because instantiating each object takes a long time
          set_property_lazy_load(property_name, xml_value)
        end
      end
    end

    def self.process_feed_property(entity, xml_doc, property_name)
      entity.instance_eval do
        xml_value = xml_doc.xpath("./#{property_name}").first
        property_name = service.send("get_#{property_name}_property_name", name)
        return if property_name.nil?
        # Doing lazy loading here because instantiating each object takes a long time
        set_property_lazy_load(property_name, xml_value)
      end
    end

    def self.process_links(entity, xml_doc)
      entity.instance_eval do
        service.navigation_properties[name].each do |nav_name, details|
          xml_doc.xpath("./link[@title='#{nav_name}']").each do |node|
            next if node.attributes['type'].nil?
            next unless node.attributes['type'].value =~ /^application\/atom\+xml;type=(feed|entry)$/i
            link_type = node.attributes['type'].value =~ /type=entry$/i ? :entry : :feed
            new_links = instance_variable_get(:@links)
            new_links[nav_name] = {
                type: link_type,
                href: node.attributes['href'].value
            }
            instance_variable_set(:@links, new_links)
          end
        end
      end
    end
  end
end


text:
/* ini.h example that simply dumps an INI file without comments */

#include <stdio.h>
#include <string.h>
#include "../ini.h"

static int dumper(void* user, const char* section, const char* name,
                  const char* value)
{
    static char prev_section[50] = "";

    if (strcmp(section, prev_section)) {
        printf("%s[%s]\n", (prev_section[0] ? "\n" : ""), section);
        strncpy(prev_section, section, sizeof(prev_section));
        prev_section[sizeof(prev_section) - 1] = '\0';
    }
    printf("%s = %s\n", name, value);
    return 1;
}

int main(int argc, char* argv[])
{
    int error;

    if (argc <= 1) {
        printf("Usage: ini_dump filename.ini\n");
        return 1;
    }

    error = ini_parse(argv[1], dumper, NULL);
    if (error < 0) {
        printf("Can't read '%s'!\n", argv[1]);
        return 2;
    }
    else if (error) {
        printf("Bad config file (first error on line %d)!\n", error);
        return 3;
    }
    return 0;
}


text:
namespace url {

COMPONENT_EXPORT(URL) BASE_DECLARE_FEATURE(kUseIDNA2008NonTransitional);

// Returns true if Chrome is using IDNA 2008 in Non-Transitional mode.
COMPONENT_EXPORT(URL) bool IsUsingIDNA2008NonTransitional();
}  // namespace url

#endif  // URL_URL_FEATURES_H_


text:
package org.workflow.core.activity;

import com.fasterxml.jackson.annotation.*;
import org.workflow.core.model.RequestVariable;

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

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "action",
        "variables"
})
public class TaskApprovalRequest {

    @JsonProperty("action")
    private String action;
    @JsonProperty("variables")
    private List<RequestVariable> variables = null;

    @JsonProperty("action")
    public String getAction() {
        return action;
    }

    @JsonProperty("action")
    public void setAction(String action) {
        this.action = action;
    }

    @JsonProperty("variables")
    public List<RequestVariable> getVariables() {
        return variables;
    }

    @JsonProperty("variables")
    public void setVariables(List<RequestVariable> variables) {
        this.variables = variables;
    }
}


text:
                    <form dojoType="dijit.form.Form" id="scriptForm" name="scriptform" action="" method="POST">

                            Equation(s):

                            <textarea id="scriptEquation" required="true" name="scriptEquation"
                                      cols="30" rows="5" placeHolder="One equation per line"></textarea>

                            Kernel/Function Name:

                            <input id="kernelName" dojoType="dijit.form.ValidationTextBox"
                                   type="text" required="true" name="kernelName"
                                   missingMessage="Oops! You forgot to name your kernel!" />

                            Commandline args to pass to BTO:

                            Search type

[Close]

Search Type

                            <input type="radio" id="search_ga" name="search_type" value="1" checked onClick="javascript:show_ga_opts();" /> Genetic Algorithm (recommended)

                            <input type="radio" id="search_ex" name="search_type" value="2" onClick="javascript:hide_ga_opts();" /> Exhaustive (very long running time)

                            <input type="test" id="limit" value="6" style="width:3em;" />
                            Exhaustive search time limit (min)

                            <input type="radio" id="search_rand" name="search_type" value="3" onClick="javascript:hide_ga_opts();" /> Random

                            <input type="radio" id="search_ortho" name="search_type" value="4" onClick="javascript:hide_ga_opts();" /> Orthogonal

                            <input type="radio" id="search_thread" name="search_type" value="5" onClick="javascript:hide_ga_opts();" /> Thread Search

                                Genetic Algorithm advanced options:

                                <input type="checkbox" id="ga_nomaxfuse" /> Disable maximum loop fusion

                                <input type="checkbox" id="ga_noglobalthread" /> Disable global Thread search

                                <input type="checkbox" id="ga_exthread" /> Additional exhaustive Thread search

                                <input type="text" id="ga_timelimit" value="10" style="width:3em;" /> Search time (s)

                                <input type="text" id="ga_popsize" value="10" style="width:3em;" /> Population size

                            Repetitions for empirical tests

                            <input type="text" id="emp_reps" value="5" style="width:3em;" />

                            Precision

                            <input type="radio" id="precision_double" name="precision" value="1" checked /> Double

                            <input type="radio" id="precision_float"  name="precision" value="2" /> Float

                            <input type="checkbox" id="correctness" name="correctness" />
                            Correctness testing

[Close]

Correctness Testing

                            Testing size (start:stop:step)

[Close]

Testing Size

                            <input type="text" id="test_param" name="test_param" value="3000:3000:1" />

                            Thread and cache tiling

[Close]

Tiling

                            <input type="text" id="level1" name="level1" value="thread 2:8:2"> Level 1 (outer/primary)

                            <input type="text" id="level2" name="level2" value=""> Level 2 (inner)

                            Additional args to send

                            <input type="text" id="addtl" value="" />

                            <button class="scriptButton" type="reset" onclick="clearKernelEquation()">
                                Reset
                            </button>
                            <button class="scriptButton" type="submit" name="submitButton" onclick="submitEquation()">
                                Check Script
                            </button>

                            Please verify the following variable types before submitting. (This parser is not yet perfect!)

                            <button class="scriptButton" type="button" name="Submit" id="codeSubmitButton" style="display:none" onclick="runScript()">
                               Generate Code with BTO
                            </button>

                    </form>


text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=UTF-8"><META HTTP-EQUIV="Refresh" CONTENT="0; URL=2002/06/28/dynamic-xhtml-competition/index.html"><TITLE>Page has moved</TITLE>

Click here...


text: fasm mtldr.asm ..\mtldr_for_installer


text:
<?php

declare(strict_types=1);

namespace Arcanedev\SeoHelper\Contracts\Entities;

use Arcanedev\SeoHelper\Contracts\Renderable;

/**
 * Interface  TwitterCard
 *
 * @author    ARCANEDEV <arcanedev.maroc@gmail.com>
 */
interface TwitterCard extends Renderable
{
    /* -----------------------------------------------------------------
     |  Constants
     | -----------------------------------------------------------------
     */

    const TYPE_APP                 = 'app';
    const TYPE_GALLERY             = 'gallery';
    const TYPE_PHOTO               = 'photo';
    const TYPE_PLAYER              = 'player';
    const TYPE_PRODUCT             = 'product';
    const TYPE_SUMMARY             = 'summary';
    const TYPE_SUMMARY_LARGE_IMAGE = 'summary_large_image';

    /* -----------------------------------------------------------------
     |  Getters & Setters
     | -----------------------------------------------------------------
     */

    /**
     * Set the card type.
     *
     * @param  string  $type
     *
     * @return $this
     */
    public function setType($type);

    /**
     * Set card site.
     *
     * @param  string  $site
     *
     * @return $this
     */
    public function setSite($site);

    /**
     * Set card title.
     *
     * @param  string  $title
     *
     * @return $this
     */
    public function setTitle($title);

    /**
     * Set card description.
     *
     * @param  string  $description
     *
     * @return $this
     */
    public function setDescription($description);

    /**
     * Add image to the card.
     *
     * @param  string  $url
     *
     * @return $this
     */
    public function addImage($url);

    /**
     * Add many metas to the card.
     *
     * @param  array  $metas
     *
     * @return $this
     */
    public function addMetas(array $metas);

    /**
     * Add a meta to the card.
     *
     * @param  string        $name
     * @param  string|array  $content
     *
     * @return $this
     */
    public function addMeta($name, $content);

    /**
     * Get all supported card types.
     *
     * @return array
     */
    public function types();

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Reset the card.
     *
     * @return $this
     */
    public function reset();
}


text:
layout: post
author: alexreher
title: "alexreher's clicky turtle"
---

I call it TurplePircleCurtle:

<iframe src="https://trinket.io/embed/python/ba6ee402e7" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

First I added the option to move with keys and create a turtle at the point where you clicked. From there I initially tried to add boundary detection and have the click send a turtle in the direction of the click from the tina point. It didn't work so I just sent it a distance of 100. Finally I added some graphical variation based on quadrant to make it look a little cooler.


text:
package com.llmaps.dm.common;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Vojtech Krizek
 */
public class CommonTest {

	@Test
	public void testGetName() {
		Common instance = new Common();
		assertEquals("Data Miner", instance.getName());
	}

}