text:
package org.wso2.carbon.security.deployment;

import java.net.URL;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisModule;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.AxisServiceGroup;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEvent;
import org.apache.axis2.engine.AxisObserver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyComponent;
import org.apache.neethi.PolicyEngine;
import org.apache.neethi.PolicyReference;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.core.RegistryResources;
import org.wso2.carbon.core.Resources;
import org.wso2.carbon.core.persistence.PersistenceFactory;
import org.wso2.carbon.core.persistence.PersistenceUtils;
import org.wso2.carbon.core.persistence.file.ModuleFilePersistenceManager;
import org.wso2.carbon.core.persistence.file.ServiceGroupFilePersistenceManager;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.jdbc.utils.Transaction;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.security.SecurityConstants;
import org.wso2.carbon.security.SecurityScenario;
import org.wso2.carbon.security.SecurityScenarioDatabase;
import org.wso2.carbon.security.SecurityServiceHolder;
import org.wso2.carbon.security.util.RahasUtil;
import org.wso2.carbon.security.util.ServerCrypto;
import org.wso2.carbon.security.util.ServicePasswordCallbackHandler;
import org.wso2.carbon.security.util.XmlConfiguration;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import org.wso2.carbon.utils.PreAxisConfigurationPopulationObserver;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

/**
 * This is a deployment interceptor which handles service specific security configurations on
 * service deployment events. It is also published as an OSGi service, so that Carbon core can
 * add this to the AxisConfiguration.
 *
 * NOTE: This is a special type of AxisObserver, which can be used only within an OSGi framework
 * hence should not be added to the axis2.xml directly. If done so, it will throw NPEs, since
 * the registry & userRealm references are set through the OSGi decalative service framework.
 *
 * @scr.component name="org.wso2.carbon.security.deployment.SecurityDeploymentInterceptor"
 * immediate="true"
 * @scr.reference name="registry.service"
 *                interface="org.wso2.carbon.registry.core.service.RegistryService"
 *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
 *                unbind="unsetRegistryService"
 * @scr.reference name="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
 * cardinality="1..1" policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
 */

public class SecurityDeploymentInterceptor implements AxisObserver {
    private static final Log log = LogFactory.getLog(SecurityDeploymentInterceptor.class);

    protected void activate(ComponentContext ctxt) {
        BundleContext bundleCtx = ctxt.getBundleContext();
        try {
	    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
            carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);

            loadSecurityScenarios(SecurityServiceHolder.getRegistryService().getConfigSystemRegistry(),
                                  bundleCtx);
        } catch (Exception e) {
            String msg = "Cannot load security scenarios";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }

        try {
            addKeystores();
        } catch (Exception e) {
            String msg = "Cannot add keystores";
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
        // Publish the OSGi service
        Dictionary props = new Hashtable();
        props.put(CarbonConstants.AXIS2_CONFIG_SERVICE, AxisObserver.class.getName());
        bundleCtx.registerService(AxisObserver.class.getName(), this, props);

        PreAxisConfigurationPopulationObserver preAxisConfigObserver =
                new PreAxisConfigurationPopulationObserver() {
                    public void createdAxisConfiguration(AxisConfiguration axisConfiguration) {
                    	init(axisConfiguration);
                        axisConfiguration.addObservers(SecurityDeploymentInterceptor.this);
                    }
                };
        bundleCtx.registerService(PreAxisConfigurationPopulationObserver.class.getName(),
                                  preAxisConfigObserver, null);

        // Publish an OSGi service to listen tenant configuration context creation events
        Dictionary properties = new Hashtable();
        properties.put(CarbonConstants.AXIS2_CONFIG_SERVICE,
                       Axis2ConfigurationContextObserver.class.getName());
        bundleCtx.registerService(Axis2ConfigurationContextObserver.class.getName(),
                                                new SecurityDeploymentListener(), properties);
    }

    public void init(AxisConfiguration axisConfig) {

    }

    public void moduleUpdate(AxisEvent event, AxisModule module) {
        // This method will not be used
    }

    public void serviceGroupUpdate(AxisEvent event, AxisServiceGroup serviceGroup) {
        // This method will not be used
    }

    public void serviceUpdate(AxisEvent axisEvent, AxisService axisService) {
        int eventType = axisEvent.getEventType();
        String serviceGroupId = axisService.getAxisServiceGroup().getServiceGroupName();

        if (eventType == AxisEvent.SERVICE_DEPLOY) {

		} else if (eventType == AxisEvent.SERVICE_REMOVE) {

			try {
				//TODO: https://wso2.org/jira/browse/WSAS-1602
//				UserRealm userRealm = SecurityServiceHolder.getRegistryService().getUserRealm(
//						tenantId);
//				AuthorizationManager acAdmin = userRealm.getAuthorizationManager();
//				String resourceName = serviceGroupId + "/" + axisService.getName();
//				String[] roles = acAdmin.getAllowedRolesForResource(resourceName,
//						UserCoreConstants.INVOKE_SERVICE_PERMISSION);
//				for (int i = 0; i < roles.length; i++) {
//					acAdmin.clearRoleAuthorization(roles[i], resourceName,
//							UserCoreConstants.INVOKE_SERVICE_PERMISSION);
//				}
			} catch (Exception e) {
				throw new RuntimeException(
						"Error while removing security while undeploying the service "
								+ axisService.getName(), e);
			}
		}

    }

    private void loadSecurityScenarios(Registry registry,
                                       BundleContext bundleContext) throws Exception {

        // TODO: Load into all tenant DBs
        // Load security scenarios
        URL resource = bundleContext.getBundle().getResource("/scenarios/scenario-config.xml");
        XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.openStream(),
                                                                 SecurityConstants.SECURITY_NAMESPACE);

        OMElement[] elements = xmlConfiguration.getElements("//ns:Scenario");
        try {
            boolean transactionStarted = Transaction.isStarted();
            if (!transactionStarted) {
                registry.beginTransaction();
            }

            for (OMElement scenarioEle : elements) {
                SecurityScenario scenario = new SecurityScenario();
                String scenarioId = scenarioEle.getAttribute(SecurityConstants.ID_QN)
                        .getAttributeValue();

                scenario.setScenarioId(scenarioId);
                scenario.setSummary(scenarioEle.getFirstChildWithName(SecurityConstants.SUMMARY_QN)
                        .getText());
                scenario.setDescription(scenarioEle.getFirstChildWithName(
                        SecurityConstants.DESCRIPTION_QN).getText());
                scenario.setCategory(scenarioEle.getFirstChildWithName(SecurityConstants.CATEGORY_QN)
                        .getText());
                scenario.setWsuId(scenarioEle.getFirstChildWithName(SecurityConstants.WSUID_QN)
                        .getText());
                scenario.setType(scenarioEle.getFirstChildWithName(SecurityConstants.TYPE_QN).getText());

                String resourceUri = SecurityConstants.SECURITY_POLICY + "/" + scenarioId;

                for (Iterator modules = scenarioEle.getFirstChildWithName(SecurityConstants.MODULES_QN)
                        .getChildElements(); modules.hasNext();) {
                    String module = ((OMElement) modules.next()).getText();
                    scenario.addModule(module);
                }

                // Save it in the DB
                SecurityScenarioDatabase.put(scenarioId, scenario);

                // Store the scenario in the Registry
                if (!scenarioId.equals(SecurityConstants.SCENARIO_DISABLE_SECURITY) &&
                        !scenarioId.equals(SecurityConstants.POLICY_FROM_REG_SCENARIO)) {
                    Resource scenarioResource = new ResourceImpl();
                    scenarioResource.
                            setContentStream(bundleContext.getBundle().
                                    getResource("scenarios/" + scenarioId + "-policy.xml").openStream());
                    scenarioResource.setMediaType("application/policy+xml");
                    if (!registry.resourceExists(resourceUri)) {
                        registry.put(resourceUri, scenarioResource);
                    }

                    // Cache the resource in-memory in order to add it to the newly created tenants
                    SecurityServiceHolder.addPolicyResource(resourceUri, scenarioResource);
                }
            }
            if (!transactionStarted) {
                registry.commitTransaction();
            }
        } catch (Exception e) {
            registry.rollbackTransaction();
            throw e;
        }
    }

    private void addKeystores() throws Exception {
        Registry registry = SecurityServiceHolder.getRegistryService().getGovernanceSystemRegistry();
        try {
            boolean transactionStarted = Transaction.isStarted();
            if (!transactionStarted) {
                registry.beginTransaction();
            }
            if (!registry.resourceExists(SecurityConstants.KEY_STORES)) {
                Collection kstores = registry.newCollection();
                registry.put(SecurityConstants.KEY_STORES, kstores);

                Resource primResource = registry.newResource();
                if (!registry.resourceExists(RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE)) {
                    registry.put(RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE,
                                 primResource);
                }
            }
            if (!transactionStarted) {
                registry.commitTransaction();
            }
        } catch (Exception e) {
            registry.rollbackTransaction();
            throw e;
        }
    }

    private void applySecurityParameters(AxisService service, SecurityScenario secScenario) {

    }

    public void addParameter(Parameter param) throws AxisFault {
        // This method will not be used
    }

    public void deserializeParameters(OMElement parameterElement) throws AxisFault {
        // This method will not be used
    }

    public Parameter getParameter(String name) {
        // This method will not be used
        return null;
    }

    public ArrayList getParameters() {
        // This method will not be used
        return new ArrayList();
    }

    public boolean isParameterLocked(String parameterName) {
        // This method will not be used
        return false;
    }

    public void removeParameter(Parameter param) throws AxisFault {
        // This method will not be used
    }

    protected void setRegistryService(RegistryService registryService) {
        SecurityServiceHolder.setRegistryService(registryService);
    }

    protected void setRealmService(RealmService realmService) {
        SecurityServiceHolder.setRealmService(realmService);
    }

    protected void unsetRealmService(RealmService realmService) {
        SecurityServiceHolder.setRealmService(null);
    }

    protected void unsetRegistryService(RegistryService registryService) {
        SecurityServiceHolder.setRegistryService(registryService);    // TODO: Serious OSGi bug here. FIXME Thilina
    }
}


text:
package org.livingdoc.api.documents;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

import org.junit.platform.commons.annotation.Testable;

@Testable
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExecutableDocument {
    String value();

    Class<?>[] fixtureClasses() default {};
}

redpajama_set_name: RedPajamaGithub


text:
from random import choice
from pygame import Surface, image

class Event():
	def __init__(self, xPos, name = None, resourcePath = ""):
		self.goodOrBad = choice([-1, 1])
		self.surface = Surface((0, 0)).convert()
		self.randomEvents = [self.river, self.house]
		self.name = name
		self.resourcePath = resourcePath
		self.xPos = xPos
		self.eventTime = ""
		if (self.name is not None):
			if (self.name == "river"):
				self.river()
			elif (self.name == "house"):
				self.house()
		else:
			self.event = choice(self.randomEvents)()
		self.eventPos = self.xPos
		self.posX = (-self.eventPos * 40) + 1280

	def river(self):
		self.surface = Surface((100, 400)).convert()
		self.surface.fill((30, 144, 255))
		self.eventName = "river"

	def house(self):
		self.surface = image.load(self.resourcePath + "img/house.png")
		self.eventName = "house"

	def update(self, moveValue):
		self.posX += 2 * moveValue


text:
<!DOCTYPE HTML>

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>Source - src/js/__formlist.js</title>
	<meta name="generator" content="JsDoc Toolkit" />

	<link media="all" rel="stylesheet" href="../../css/common.css" type="text/css" />
	<link media="all" rel="stylesheet" href="../../css/bootstrap.min.css" type="text/css" />
	<link media="all" rel="stylesheet" href="../../css/prettify.css" type="text/css" />
	<link media="print" rel="stylesheet" href="../../css/print.css" type="text/css" />

				JsDoc Reference

Class Index

File Index

Classes

Cache

Connection

Date

Form

DataXML Inner

Nodeset Inner

FormHTML Inner

Branch

GUI

Print

Settings

State

StorageLocal

String

_global_

/*jslint browser:true, devel:true, jquery:true, smarttabs:true*//*global gui, Form, StorageLocal, Connection, Modernizr, getGetVariable, vkbeautify*/
var /** @type {Connection} */connection;
var /** @type {StorageLocal} */store;
var /** @type {Settings}*/settings;

window.addEventListener("load",function() {
	// Set a timeout...
	setTimeout(function(){
		// Hide the address bar!
		window.scrollTo(0, 1);
	}, 0);
});

$(document).ready(function(){
	"use strict";
	var url;

	connection = new Connection();
	store = new StorageLocal();

	$('[title]').tooltip();

	gui.setup();

	/*** TEMPORARY FIX? https://github.com/twitter/bootstrap/issues/4550 ***/
	$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
	/*********************/

	$('.url-helper a')
		.click(function(){
			var helper, placeholder, value;
			$(this).parent().addClass('active').siblings().removeClass('active');
			helper = $(this).attr('data-value');
			placeholder = (helper === 'formhub' || helper === 'formhub_uni') ? 'enter formhub account' :
				(helper === 'appspot') ? 'enter appspot subdomain' : 'e.g. formhub.org/johndoe';
			value = (helper === 'formhub_uni') ? 'formhub_u' : '';

			$('input#server').attr('placeholder', placeholder);
			if ( $('input#server').val() !== value ){
				$('input#server').val(value).trigger('change');
			}
		})
		.andSelf().find('[data-value="formhub"]').click();

	$('input').change(function(){
		if ($(this).val().length > 0){
			$('.go').click();
		}
		return false;
	});

	$('.go').click(function(){
		var props,
			frag = $('input#server').val(),
			type = $('.url-helper li.active > a').attr('data-value');
		if ($('progress').css('display') === 'none'){
			props = {
				server: connection.oRosaHelper.fragToServerURL(type, frag),
				helper: $('.url-helper li.active > a').attr('data-value'),
				inputValue: $('input#server').val()
			};
			if (props.server){
				$('progress').show();
				connection.getFormlist(props.server, {
					success: function(resp, msg){
						processFormlistResponse(resp, msg, props);
					}
				});
			}
		}
	});

	$('#form-list').on('click', 'a', function(){
		console.log('caught click');
		var server, id,
			href = $(this).attr('href');

		//request a url first by launching this in enketo
		if ( !href || href === "" || href==="#" ){
			console.log('going to request enketo url');
			server = $(this).attr('data-server');
			id = $(this).attr('id');
			connection.getSurveyURL(server, id, {
				success: function(resp, msg){
					resp.serverURL = server;
					resp.formId = id;
					processSurveyURLResponse(resp, msg);
				}
			});
		}
		else{
			location.href=href;
		}
		return false;
	});

	loadPreviousState();
});

function loadPreviousState(){
	var i, list,
		server = store.getRecord('__current_server');
	if (server){
		$('.url-helper li').removeClass('active').find('[data-value="'+server.helper+'"]').parent('li').addClass('active');
		$('input#server').val(server.inputValue);
		list = store.getRecord('__server_'+server.url);
		gui.parseFormlist(list, $('#form-list'));
	}
}

function processFormlistResponse(resp, msg, props){
	var helper, inputValue;
	console.log('processing formlist response');
	if (typeof resp === 'object' && !$.isEmptyObject(resp)){
		store.setRecord('__server_' + props.server, resp, false, true);
		store.setRecord('__current_server', {'url': props.server, 'helper': props.helper, 'inputValue': props.inputValue}, false, true);
	}
	$('progress').hide();
	gui.parseFormlist(resp, $('#form-list'));
}

/**
 * Adds urls to links
 * @param  {?Object.<string, string>} resp [description]
 * @param  {string} msg  [description]
 */
function processSurveyURLResponse(resp, msg){
	var record,
		url = resp.url || null,
		server = resp.serverURL || null,
		id = resp.formId || null;
	console.debug(resp);
	console.debug('processing link to:  '+url);
	if (url && server && id){
		record = store.getRecord('__server_'+server) || {};
		record[id]['url'] = url;
		store.setRecord('__server_'+server, record, false, true);
		$('a[id="'+id+'"][data-server="'+server+'"]').attr('href', url).click();
	}
	else{
		//TODO: add error handling
	}
}

Documentation generated by JsDoc Toolkit 2.4.0 on Fri Dec 07 2012 17:49:17 GMT-0700 (MST)


text:
using UnityEngine;
using System.Collections;
using System;

public class Tools : MonoBehaviour {
	public enum Regulated : int{
		unknown,
		up,
		down,
	};

	public static Regulated RandomRegulated(){
		return (Regulated) (UnityEngine.Random.Range(0, Enum.GetNames(typeof(Regulated)).Length));
	}
}


text:
angular.module("app").factory("FlashService", function($q, $http, $rootScope) {

  var that = this;
  var upcomingMessages = [];
  var currentMessages = [];

  var getCurrentMessages = function() {
    return currentMessages;
  };

  var addCurrentMessage = function(message) {
    currentMessages.push({
      message: message
    });
    $rootScope.$emit('currentFlashMessageUpdated', currentMessages);
  };

  var addMessage = function(message) {
    upcomingMessages.push({
      message: message
    });
  };

  $rootScope.$on('$routeChangeSuccess', function() {
    currentMessages = upcomingMessages;
    upcomingMessages = [];
  });

  return {
    getCurrentMessages: getCurrentMessages,
    addCurrentMessage: addCurrentMessage,
    addMessage: addMessage
  };
});


text:
<?php

namespace Refinery29\ApiOutput\Serializer\Error;

use Refinery29\ApiOutput\Resource\Error\ErrorCollection as Input;
use Refinery29\ApiOutput\Resource\TopLevelResource;
use Refinery29\ApiOutput\Serializer\HasSerializer;

class ErrorCollection implements TopLevelResource
{
    /**
     * @var Input
     */
    protected $resource;

    /**
     * @param HasSerializer $serializer
     *
     * @throws \Exception
     */
    public function __construct(HasSerializer $serializer)
    {
        if (!$serializer instanceof Input) {
            throw new \Exception('Invalid Resource provided for serailzer');
        }

        $this->resource = $serializer;
    }

    /**
     * @return string
     */
    public function getTopLevelName()
    {
        return 'errors';
    }

    /**
     * @return array
     */
    public function getOutput()
    {
        $output = [];

        foreach ($this->resource->getErrors() as $error) {
            $output[] = $error->getSerializer()->getOutput();
        }

        return $output;
    }
}


text:
package Paws::Lightsail::CreateDomainEntryResult;
  use Moose;
  has Operation => (is => 'ro', isa => 'Paws::Lightsail::Operation', traits => ['NameInRequest'], request_name => 'operation' );

  has _request_id => (is => 'ro', isa => 'Str');

### main pod documentation begin ###

=head1 NAME

Paws::Lightsail::CreateDomainEntryResult

=head1 ATTRIBUTES

=head2 Operation => L<Paws::Lightsail::Operation>

An array of key-value pairs containing information about the operation.

=head2 _request_id => Str

=cut

1;


text:
<!DOCTYPE html>
<html lang="en" ng-app="app">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Video</title>
    <link rel="shortcut icon" href="favicon.ico" />
    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="lib/ui-animate/anim-in-out.css">
    <link rel="stylesheet" href="lib/videojs/video-js.min.css">
</head>

<body>
    <div ui-view></div>

    <script src="lib/jquery/jquery.js"></script>

    <script src="lib/angular/angular.js"></script>
    <script src="lib/oclazyload/oclazyload.js"></script>
    <script src="lib/ui-router/angular-ui-router.js"></script>

    <script src="lib/videojs/video.js"></script>
    <script src="lib/videojs/ie8/videojs-ie8.js"></script>

    <script src="lib/angular/angular-animate.js"></script>
    <script src="lib/angular/angular-touch.js"></script>
    <script src="lib/ui-animate/anim-in-out.js"></script>

    <script src="lib/bootstrap/js/bootstrap.js"></script>
    <script src="lib/ui-bootstrap/ui-bootstrap-tpls.js"></script>

    <script src="lib/translate/angular-translate.js"></script>
    <script src="lib/translate/angular-translate-storage-local.js"></script>
    <script src="lib/translate/angular-translate-storage-cookie.js"></script>
    <script src="lib/translate/angular-translate-loader-static-files.js"></script>

    <script src="app.module.js"></script>
    <script src="app.config.js"></script>
    <script src="app.route.oclazy.js"></script>
</body>

</html>


text:
package es.tid.cosmos.api.controllers

import org.scalatest.FlatSpec
import org.scalatest.matchers.MustMatchers
import play.api.libs.json.Json
import play.api.test._
import play.api.test.Helpers._

import es.tid.cosmos.api.controllers.cluster.CreateClusterParams
import es.tid.cosmos.api.controllers.pages.WithSampleSessions
import es.tid.cosmos.api.mocks.SampleClusters
import es.tid.cosmos.api.profile.ClusterSecret
import es.tid.cosmos.servicemanager.ClusterName
import es.tid.cosmos.servicemanager.clusters.ClusterId
import es.tid.cosmos.servicemanager.services.Hdfs

class ClustersIT
  extends FlatSpec with MustMatchers with AuthBehaviors with MaintenanceModeBehaviors {

  val validCreationParams =
    Json.toJson(CreateClusterParams(ClusterName("cluster_new"), 6, Seq(Hdfs.name), shared = false))
  val inValidCreationParams = Json.obj("invalid" -> "json")
  val resourcePath = "/cosmos/v1/cluster"
  val listClusters = FakeRequest(GET, resourcePath)
  val createCluster = FakeRequest(POST, resourcePath).withJsonBody(validCreationParams)

  "Cluster listing" must behave like rejectingUnauthenticatedRequests(listClusters)

  it must behave like enabledWhenUnderMaintenance(listClusters)

  "Cluster creation" must behave like rejectingUnauthenticatedRequests(createCluster)

  it must behave like enabledOnlyForOperatorsWhenUnderMaintenance(createCluster)

  it must "create shared clusters by default" in new WithSampleSessions {
    val resource = regUserInGroup.doRequest(FakeRequest(POST, resourcePath)
      .withJsonBody(Json.obj("name" -> "cluster_new", "size" -> 6)))
    status(resource) must equal (CREATED)
    contentType(resource) must be (Some("application/json"))
  }

  "The clusters resource" must "list user clusters" in new WithSampleSessions with SampleClusters {
    val user1 = new RegisteredUserSession("user1", "User 1")
    val user2 = new RegisteredUserSession("user2", "User 2")
    val ownCluster = SampleClusters.RunningClusterProps.id
    val otherCluster = ClusterId.random()
    store.withTransaction { implicit c =>
      store.cluster.register(ownCluster, user1.cosmosProfile.id, ClusterSecret.random())
      store.cluster.register(otherCluster, user2.cosmosProfile.id, ClusterSecret.random())
    }

    val resource = user1.doRequest(listClusters)

    store.withTransaction { implicit c =>
      status(resource) must equal (OK)
      contentType(resource) must be (Some("application/json"))
      contentAsString(resource) must include (ownCluster.toString)
      contentAsString(resource) must include (SampleClusters.RunningClusterProps.name.underlying)
      contentAsString(resource) must not include otherCluster.toString
    }
  }

  it must "start a new cluster if no services are specified" in new WithSampleSessions {
    val resource = regUserInGroup.doRequest(FakeRequest(POST, resourcePath)
      .withJsonBody(Json.obj("name" -> "cluster_new", "size" -> 6)))
    status(resource) must equal (CREATED)
    contentType(resource) must be (Some("application/json"))
    val location = header("Location", resource)
    location must be ('defined)
    contentAsString(resource) must include (location.get)
    store.withConnection { implicit c =>
      store.cluster.ownedBy(regUserInGroup.cosmosProfile.id) must have length 1
    }
  }

  it must "start a new cluster if some services are specified" in new WithSampleSessions {
    val resource = regUserInGroup.doRequest(createCluster)
    status(resource) must equal (CREATED)
    contentType(resource) must be (Some("application/json"))
    val location = header("Location", resource)
    location must be ('defined)
    contentAsString(resource) must include (location.get)
    store.withConnection { implicit c =>
      store.cluster.ownedBy(regUserInGroup.cosmosProfile.id) must have length 1
    }
  }

  it must "reject cluster creation with invalid payload" in new WithSampleSessions {
    val resource =
      regUserInGroup.doRequest(FakeRequest(POST, resourcePath).withJsonBody(inValidCreationParams))
    status(resource) must equal (BAD_REQUEST)
  }
}


text:
<?php

/**
 * A node representing an expression in brackets: { and  }.
 *
 * @author Tomasz Jędrzejewski
 * @copyright Invenzzia Group <http://www.invenzzia.org/> and contributors.
 * @license http://www.invenzzia.org/license/new-bsd New BSD License
 * @package XML
 */
class Opt_Xml_Expression extends Opt_Xml_Node
{
	/**
	 * The expression stored in the node.
	 * @var String
	 */
	private $_expression;

	/**
	 * Initializes the expression node. The argument determines the
	 * expression that it represents.
	 * @param String $expression The expression represented by the node.
	 */
	public function __construct($expression)
	{
		$this->_expression = $expression;
	} // end __construct();

	/**
	 * Returns the expression stored in the node.
	 * @return String
	 */
	public function getExpression()
	{
		return $this->_expression;
	} // end getExpression();

	/**
	 * Sets a new expression for the node.
	 * @param String $expression The new expression.
	 */
	public function setExpression($expression)
	{
		$this->_expression = $expression;
	} // end setExpression();

	/**
	 * Returns the expression stored in the node.
	 * @return String
	 */
	public function __toString()
	{
		return $this->_expression;
	} // end __toString();

	/**
	 * This function is executed by the compiler during the second compilation stage,
	 * processing.
	 */
	public function preMigrate(Opt_Compiler_Class $compiler)
	{
		$this->set('hidden', false);
	} // end preMigrate();

	/**
	 * This function is executed by the compiler during the second compilation stage,
	 * after processing the child nodes.
	 */
	public function postMigrate(Opt_Compiler_Class $compiler)
	{

	} // end postMigrate();

	/**
	 * This function is executed by the compiler during the second compilation stage,
	 * processing.
	 */
	public function preProcess(Opt_Compiler_Class $compiler)
	{
		$this->set('hidden', false);
		// Empty expressions will be caught by the try... catch.
		try
		{
			$found = $compiler->detectExpressionEngine((string)$this, $compiler->getDefaultExpressionEngine());
			if($found === null)
			{
				throw new Opt_Xml_Exception('Default expression engine for curly bracket expressions is not defined.');
			}

			$result = $compiler->parseExpression($found[1], $found[0]);
			switch($result['type'])
			{
				case Opt_Expression_Interface::ASSIGNMENT:
					$this->addAfter(Opt_Xml_Buffer::TAG_BEFORE, $result['bare'].'; ');
					break;
				case Opt_Expression_Interface::SCALAR:
					if($result['escaping'] == false)
					{
						$this->addAfter(Opt_Xml_Buffer::TAG_BEFORE, $result['bare']);
						$this->set('nophp', true);
						break;
					}
					// TODO: Add escaping for scalar values.
				default:
					$this->addAfter(Opt_Xml_Buffer::TAG_BEFORE, 'echo '.$result['escaped'].'; ');
			}
		}
		catch(Opt_EmptyExpression_Exception $e){}
	} // end preProcess();

	/**
	 * This function is executed by the compiler during the second compilation stage,
	 * processing, after processing the child nodes.
	 */
	public function postProcess(Opt_Compiler_Class $compiler)
	{

	} // end postProcess();

	/**
	 * This function is executed by the compiler during the third compilation stage,
	 * linking.
	 */
	public function preLink(Opt_Compiler_Class $compiler)
	{
		$compiler->appendOutput($this->buildCode(Opt_Xml_Buffer::TAG_BEFORE));
	//	$this->_closeComments($item, $output);
	} // end preLink();

	/**
	 * This function is executed by the compiler during the third compilation stage,
	 * linking, after linking the child nodes.
	 */
	public function postLink(Opt_Compiler_Class $compiler)
	{

	} // end postLink();
} // end Opt_Xml_Expression;


text:
package fr.adrienbrault.idea.symfony2plugin.tests.dic;

import fr.adrienbrault.idea.symfony2plugin.dic.ServiceMap;
import fr.adrienbrault.idea.symfony2plugin.dic.ServiceMapParser;
import fr.adrienbrault.idea.symfony2plugin.dic.container.ServiceInterface;
import org.junit.Assert;
import org.junit.Test;

import java.io.ByteArrayInputStream;

/**
 * @author Adrien Brault <adrien.brault@gmail.com>
 * @see fr.adrienbrault.idea.symfony2plugin.dic.ServiceMapParser
 */
public class ServiceMapParserTest extends Assert {

    @Test
    public void testParse() throws Exception {
        ServiceMapParser serviceMapParser = new ServiceMapParser();

        String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<container>" +
                "<service id=\"adrienbrault\" class=\"AdrienBrault\\Awesome\"/>" +
                "<service id=\"secret\" class=\"AdrienBrault\\Secret\" public=\"false\"/>" +
                "<service id=\"translator\" alias=\"adrienbrault\"/>" +
                "<service id=\"translator_private\" alias=\"adrienbrault\" public=\"false\"/>" +
            "</container>";

        ServiceMap serviceMap = serviceMapParser.parse(new ByteArrayInputStream(xmlString.getBytes()));

        assertTrue(serviceMap.getIds().contains("adrienbrault"));
        assertTrue(serviceMap.getIds().contains("secret"));
        assertTrue(serviceMap.getIds().contains("translator"));
        assertTrue(serviceMap.getIds().contains("translator_private"));

        ServiceInterface translator = serviceMap.getServices().stream().filter(s -> "translator".equals(s.getId())).findFirst().get();
        assertEquals("AdrienBrault\\Awesome", translator.getClassName());
        assertTrue("AdrienBrault\\Awesome", translator.isPublic());

        ServiceInterface translatorPrivate = serviceMap.getServices().stream().filter(s -> "translator_private".equals(s.getId())).findFirst().get();
        assertEquals("AdrienBrault\\Awesome", translatorPrivate.getClassName());
        assertFalse("AdrienBrault\\Awesome", translatorPrivate.isPublic());

        assertFalse(
            serviceMap.getServices().stream().filter(s -> "secret".equals(s.getId())).findFirst().get().isPublic()
        );
    }
}


text:
<TITLE>Review for Deep Blue Sea (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Deep Blue Sea (1999)

reviewed by
David Sunga

DEEP BLUE SEA (1999)

Rating: 3.5 stars (out of 4.0)
********************************
Key to rating system:
2.0 stars - Debatable
2.5 stars - Some people may like it
3.0 stars - I liked it
3.5 stars - I am biased in favor of the movie
4.0 stars - I felt the movie's impact personally or it stood out
*********************************
A Movie Review by David Sunga

Directed by: Renny Harlin

Written by: Duncan Kennedy, Donna Powers and Wayne Powers

Starring: Saffron Burrows, Thomas Jane, Samuel L. Jackson, LL Cool J,
Michael Rapaport

Russell Franklin: Samuel L. Jackson
Carter Blake: Thomas Jane
Susan McAlester: Saffron Burrows
Sherman `Preacher' Dudley: LL Cool J
Tom Scoggins: Michael Rapaport

Synopsis:
In a floating research facility called Aquatica, proteins are harvested
from the brains of three mako sharks as part of research on a cure for
Alzheimer's disease. Mako sharks, a species where the female is much larger
than the male, are some of the fastest, highest leaping fish in the world,
as well as possibly the most the most intelligent type of shark and a
leader in attacks on boats. An unfortunate consequence of the Aquatica
research is that it enhances the size, invulnerability, and intelligence of
the three sharks. The humans seem firmly in control, but when an accident
happens, guess who's got the upper hand?

Opinion:
Who will survive? The beautiful but ice-cold lady scientist, the reformed
convict? The depressed research assistant or her smokaholic boyfriend, the
baby-faced engineer, the rich financier, or the cook? DEEP BLUE SEA is no
cliches and all surprises. It'll put you on the edge of your seat more
times than the original Jurassic Park. DEEP BLUE SEA was the funnest movie
I've seen all summer, and I highly recommend it for an outing of scary fun
and entertainment.

Reviewed by David Sunga
July 28, 1999

Copyright © 1999 by David Sunga
This review and others like it can be found at
THE CRITIC ZOO: http://www.criticzoo.com
email: zookeeper@criticzoo.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package com.island.starpixel.blocchi.solidi.porte;
import com.island.starpixel.blocchi.solidi.*;
public abstract class Porta extends Solido
{
	public String descrizioneItaliano()
	{
		return"SOLO LE PERSONE POSSONO PASSARCI";
	}
	public String descrizioneInglese()
	{
		return"ONLY PERSON CAN PASS OVER IT";
	}
}


text:
select  count(*)
from store_sales
    ,household_demographics
    ,time_dim, store
where ss_sold_time_sk = time_dim.t_time_sk
    and ss_hdemo_sk = household_demographics.hd_demo_sk
    and ss_store_sk = s_store_sk
    and time_dim.t_hour = 20
    and time_dim.t_minute >= 30
    and household_demographics.hd_dep_count = 7
    and store.s_store_name = 'ese'
order by count(*)
limit 100

-- end query 1 in stream 0 using template ../query_templates_qualified/query96.tpl


text:
package com.atulgpt.www.timetrix;

import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls
 * to be used with AppCompat.
 */
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {

    private AppCompatDelegate mDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getDelegate ().installViewFactory ();
        getDelegate ().onCreate (savedInstanceState);
        super.onCreate (savedInstanceState);
    }

    @Override
    protected void onStop() {
        super.onStop ();
        getDelegate ().onStop ();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy ();
        getDelegate ().onDestroy ();
    }

    private AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create (this, null);
        }
        return mDelegate;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate (savedInstanceState);
        getDelegate ().onPostCreate (savedInstanceState);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume ();
        getDelegate ().onPostResume ();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged (newConfig);
        getDelegate ().onConfigurationChanged (newConfig);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate ().setContentView (layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate ().setContentView (view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate ().setContentView (view, params);
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate ().addContentView (view, params);
    }

    public void invalidateOptionsMenu() {
        getDelegate ().invalidateOptionsMenu ();
    }

    @Override
    public MenuInflater getMenuInflater() {
        return getDelegate ().getMenuInflater ();
    }

    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged (title, color);
        getDelegate ().setTitle (title);
    }

    public ActionBar getSupportActionBar() {
        return getDelegate ().getSupportActionBar ();
    }

    public void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate ().setSupportActionBar (toolbar);
    }
}


text:
//
//  MCBaseListViewController.m
//  CityOutdoors
//
//  Created by Marius Ciocanel on 06/11/2012.
//  Copyright (c) 2012 Marius Ciocanel. All rights reserved.
//

#import "MCBaseListViewController.h"
#import "MCFeatureDetailViewController.h"

@interface MCBaseListViewController ()
@end

@implementation MCBaseListViewController

- (void)viewDidLoad{
    [super viewDidLoad];
	[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(contextDidSave:)
                                                 name:NSManagedObjectContextDidSaveNotification
                                               object:nil];
}

-(void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle: @"Back"
								   style: UIBarButtonItemStyleBordered
								   target: nil action: nil];
	[self.navigationItem setBackBarButtonItem:backButton];

}
#pragma mark - Methods to be overridden in subclasses

-(void)loadListElements {

}

- (void)refresh {
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),
				   ^{
					   [self loadListElements];
					   dispatch_async(dispatch_get_main_queue(),
									  ^{
/*
										  [self.pullToRefreshView finishLoading];
*/
										  [self.tableView reloadData];
									  });
				   });
}

- (void)refreshFromRemoteData {

}

- (void)contextDidSave:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSManagedObjectContext *mergeContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
		mergeContext.persistentStoreCoordinator = [[MCAppDataModel sharedDataModel] persistentStoreCoordinator];
		[mergeContext setMergePolicy:NSOverwriteMergePolicy];
        [mergeContext mergeChangesFromContextDidSaveNotification:notification];

        [self refresh];
    });
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [[self.fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
	NSInteger rows = [sectionInfo numberOfObjects];
    return rows;
}

#pragma mark - Table View Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	UIStoryboard *featureStoryboard = [UIStoryboard storyboardWithName:@"Feature" bundle:nil];
	MCFeatureDetailViewController *featureDetailVC = [featureStoryboard instantiateViewControllerWithIdentifier:@"MCFeatureDetailViewController"];

	MCCollectionItem *item = [self.fetchedResultsController objectAtIndexPath:indexPath];
	featureDetailVC.collectionItem = item;
	featureDetailVC.managedContext = item.managedObjectContext;
	[self.navigationController pushViewController:featureDetailVC animated:YES];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end


text:
import { TestBed } from '@angular/core/testing';

import { HowToSnippetComponent } from './how-to-snippet.component';

describe('About Component', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({declarations: [HowToSnippetComponent]});
  });

  it('should ...', () => {
    const fixture = TestBed.createComponent(HowToSnippetComponent);
    fixture.detectChanges();
    expect(fixture.nativeElement.children[0].textContent).toContain('Bookmarking for Developers & Co');
  });

});


text:
layout: post
title: Java 8 Lambda Expression
date: 2017-07-09
comments: true
tags: [Java]
---

### Introduction:
Lambda is a magic expression in Java 8, which makes tens
or hundreds of lines become one line, and makes code concise and easy.
This post will introduce using lambda expression for thread pool and
stream.

### Thread pool lambda expression
Recently I am using Java thread pool, and Mateusz reminds me to try
lambda expression. It really opens a new world to me. Instead of
implementing another class implements runnable (or extends thread), I
can use one line to express everything.

Here let's see a short example I write.

```java
// Create 5 threads in pool
ExecutorService executor = Executors.newFixedThreadPool(5);

Runnable task = () -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("The current thread is " + threadName);
}

executor.submit(task);
```

One awesome point using Lambda expression is that we don't need to create another class for thread, which means we don't need pass a lot of parameter and construct the class.

If you want to see the thread execution result, you can also use a
Future object to get the thread execution result;

```java
Future<String[]> future = executor.submit(task);
System.out.println("The execution of thread 0 is " + future.get()[0]);
```

### Stream

I am not going to talk about the inputstream. Instead, using stream to
manipulate list is another awesome lambda expression in Java 8.

```java
List<String> list = Arrays.asList("e1", "e2", "e3");

list.stream()
    .filter(s -> s.contains("1"))
    .map(String::toUpperCase)

// Out
E1
```
It's similar the list operation in Perl.

Anyway, Java 8 is more powerful than ever. I do see it learns a lot powerful strength from other language. Still remember how exhausting to write a thread class, now with Lambda expression, everything is becoming so concise and beautiful.


text:
<manifest package="com.gcm.client"
          xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

    <permission
        android:name="${applicationId}.permission.C2D_MESSAGE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>

    <application>

        <service android:name="com.gcm.client.RegistrationIntentService" android:exported="false"/>

        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
                <action android:name="com.google.android.c2dm.intent.REGISTRATION"/> <!-- Required for support devices below kitkat -->
                <category android:name="${applicationId}"/>
            </intent-filter>
        </receiver>

        <service
            android:name="com.gcm.client.GcmMessagingListener" android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            </intent-filter>
        </service>

        <service
            android:exported="false"
            android:name="com.gcm.client.InstanceIDService">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>

    </application>

</manifest>


text:
package com.github.ltsopensource.jobclient.support;

import com.github.ltsopensource.core.domain.JobResult;

import java.util.List;

/**
 * @author Robert HG (254963746@qq.com) on 8/29/14.
 */
public interface JobCompletedHandler {

    /**
     * 处理返回结果
     */
    void onComplete(List<JobResult> jobResults);
}


text:
require "active_support"
require "active_support/test_case"

ActiveSupport.test_order = :random

module Spring
  module Test
    class << self
      attr_accessor :root
    end

    require_relative "application"
    require_relative "application_generator"
    require_relative "rails_version"
    require_relative "watcher_test"
    require_relative "acceptance_test"
  end
end


text:
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/rancher/sparse-tools/log"
	"github.com/rancher/sparse-tools/sparse"
)

func main() {
	defaultNonVerboseLogLevel := log.LevelWarn // set if -verbose is false
	// Command line parsing
	verbose := flag.Bool("verbose", false, "verbose mode")
	flag.Usage = func() {
		const usage = "fold <Options> <SrcOrChildFile> <DstOrParentFile>"
		const examples = `
Examples:
  fold child.snapshot parent.snapshot`
		fmt.Fprintf(os.Stderr, "\nUsage of %s:\n", os.Args[0])
		fmt.Fprintln(os.Stderr, usage)
		flag.PrintDefaults()
		fmt.Fprintln(os.Stderr, examples)
	}
	flag.Parse()

	args := flag.Args()
	if len(args) < 1 {
		cmdError("missing file paths")
	}
	if len(args) < 2 {
		cmdError("missing destination file path")
	}
	if len(args) > 2 {
		cmdError("too many arguments")
	}

	srcPath := args[0]
	dstPath := args[1]
	if *verbose {
		fmt.Fprintf(os.Stderr, "Folding %s to %s...\n", srcPath, dstPath)
	} else {
		log.LevelPush(defaultNonVerboseLogLevel)
		defer log.LevelPop()
	}

	err := sparse.FoldFile(srcPath, dstPath)
	if err != nil {
		os.Exit(1)
	}
}

func cmdError(msg string) {
	fmt.Fprintln(os.Stderr, "Error:", msg)
	flag.Usage()
	os.Exit(2)
}


text:
require 'spec_helper'

describe PeopleQuery do
  context '.inactive_since' do
    it 'returns the right users' do
      not_recently_seen_without_balance = create(:person, last_seen_at: 200.days.ago)

      recent_last_seen = create(:person, last_seen_at: 89.days.ago)

      not_recently_seen_with_recent_transaction = create(:person, last_seen_at: 100.days.ago)
      transaction = create(:transaction)
      create(:split, item: not_recently_seen_with_recent_transaction, amount: 1000, txn: transaction)
      create(:split, account: Account::Liability.instance, amount: 1000, txn: transaction)

      truly_inactive_with_balance = create(:person, last_seen_at: 91.days.ago)
      transaction = create(:transaction)
      create(:split, item: truly_inactive_with_balance, amount: 1000, txn: transaction, created_at: 100.days.ago)
      create(:split, account: Account::Liability.instance, amount: 1000, txn: transaction, created_at: 100.days.ago)

      results = PeopleQuery.new.inactive_since(90.days.ago)

      expect(results).to contain_exactly(truly_inactive_with_balance)
    end

    it 'returns the user with a balance virtual attributes' do
      inactive_person_with_balance = create(:person, last_seen_at: 100.days.ago)
      transaction = create(:transaction)
      create(:split, item: inactive_person_with_balance, amount: 1000, txn: transaction, created_at: 100.days.ago)
      create(:split, account: Account::Liability.instance, amount: 1000, txn: transaction, created_at: 100.days.ago)

      results = PeopleQuery.new.inactive_since(Time.zone.now - 90.days)

      expect(results[0].balance).to eq 1000
    end

    it 'returns a user with a previous inactivity fee split' do
      person = create(:person, last_seen_at: 200.days.ago)

      transaction = create(:transaction)
      create(:split, item: person, amount: 1000, txn: transaction, created_at: 100.days.ago)
      create(:split, account: Account::Liability.instance, amount: 1000, txn: transaction, created_at: 100.days.ago)

      ChargeUserInactivityFee.charge!

      results = PeopleQuery.new.inactive_since(90.days.ago)

      expect(results).to contain_exactly person
    end
  end
end


text:
/*
 * File:    startup.c
 * Purpose: Generic Kinetis startup code
 *
 * Notes:
 */

#include "common.h"

#if (defined(IAR))
	#pragma section = ".data"
	#pragma section = ".data_init"
	#pragma section = ".bss"
	#pragma section = "CodeRelocate"
	#pragma section = "CodeRelocateRam"
#endif

/********************************************************************/
void
common_startup(void)
{

#if (defined(CW))
    extern char __START_BSS[];
    extern char __END_BSS[];
    extern uint32 __DATA_ROM[];
    extern uint32 __DATA_RAM[];
    extern char __DATA_END[];
#endif

    /* Declare a counter we'll use in all of the copy loops */
    uint32 n;

    /* Declare pointers for various data sections. These pointers
     * are initialized using values pulled in from the linker file
     */
    uint8 * data_ram, * data_rom, * data_rom_end;
    uint8 * bss_start, * bss_end;

    /* Get the addresses for the .data section (initialized data section) */
	#if (defined(CW))
        data_ram = (uint8 *)__DATA_RAM;
	    data_rom = (uint8 *)__DATA_ROM;
	    data_rom_end  = (uint8 *)__DATA_END; /* This is actually a RAM address in CodeWarrior */
	    n = data_rom_end - data_ram;
    #elif (defined(IAR))
		data_ram = __section_begin(".data");
		data_rom = __section_begin(".data_init");
		data_rom_end = __section_end(".data_init");
		n = data_rom_end - data_rom;
	#endif

	/* Copy initialized data from ROM to RAM */
	while (n--)
		*data_ram++ = *data_rom++;

    /* Get the addresses for the .bss section (zero-initialized data) */
	#if (defined(CW))
		bss_start = (uint8 *)__START_BSS;
		bss_end = (uint8 *)__END_BSS;
	#elif (defined(IAR))
		bss_start = __section_begin(".bss");
		bss_end = __section_end(".bss");
	#endif

    /* Clear the zero-initialized data section */
    n = bss_end - bss_start;
    while(n--)
      *bss_start++ = 0;

	/* Get addresses for any code sections that need to be copied from ROM to RAM.
	 * The IAR tools have a predefined keyword that can be used to mark individual
	 * functions for execution from RAM. Add "__ramfunc" before the return type in
	 * the function prototype for any routines you need to execute from RAM instead
	 * of ROM. ex: __ramfunc void foo(void);
	 */
	#if (defined(IAR))
		uint8* code_relocate_ram = __section_begin("CodeRelocateRam");
		uint8* code_relocate = __section_begin("CodeRelocate");
		uint8* code_relocate_end = __section_end("CodeRelocate");

		/* Copy functions from ROM to RAM */
		n = code_relocate_end - code_relocate;
		while (n--)
			*code_relocate_ram++ = *code_relocate++;
	#endif
}
/********************************************************************/


text:
<ion-header>
  <ion-navbar color="navbar">
    <ion-title>Location</ion-title>
    <ion-buttons end>
      <button ion-button icon-only (click)="shareDetails($event)">
        <ion-icon ios="ios-share-outline" md="md-share"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
<ion-content>
  <ion-list *ngIf="location">
    <ion-item text-wrap>

{{location.name}}

    </ion-item>
    <ion-item text-wrap>

{{location.address}}

    </ion-item>
    <ion-item text-wrap>

{{location.description}}

    </ion-item>
    <ion-item text-wrap>
      <ion-icon color="dark" ios="ios-medkit" md="md-medkit" *ngFor="let unit of location.units | rangeNumber"></ion-icon>
    </ion-item>
    <ion-item *ngIf="staticMap">

    </ion-item>
  </ion-list>
</ion-content>


text:
package com.planet_ink.coffee_mud.Abilities.Fighter;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Fighter_CircleParry extends FighterSkill
{
	public String ID() { return "Fighter_CircleParry"; }
	public String name(){ return "Circle Parry";}
	public String displayText(){ return "";}
	protected int canAffectCode(){return CAN_MOBS;}
	protected int canTargetCode(){return 0;}
	public int abstractQuality(){return Ability.QUALITY_BENEFICIAL_SELF;}
    public int classificationCode(){ return Ability.ACODE_SKILL|Ability.DOMAIN_EVASIVE;}
	public boolean isAutoInvoked(){return true;}
	public boolean canBeUninvoked(){return false;}

	boolean lastTime=false;

	public boolean anyWeapons(MOB mob)
	{
		for(int i=0;i<mob.inventorySize();i++)
		{
			Item I=mob.fetchInventory(i);
			if((I!=null)
			   &&((I.amWearingAt(Item.WORN_WIELD))
			      ||(I.amWearingAt(Item.WORN_HELD))))
				return true;
		}
		return false;
	}

	public boolean okMessage(Environmental myHost, CMMsg msg)
	{
		if((affected==null)||(!(affected instanceof MOB)))
			return true;

		MOB mob=(MOB)affected;

		if(msg.amITarget(mob)
		   &&(CMLib.flags().aliveAwakeMobileUnbound(mob,true))
		   &&(msg.targetMinor()==CMMsg.TYP_WEAPONATTACK)
		   &&(mob.rangeToTarget()==0))
		{
			if((msg.tool()!=null)&&(msg.tool() instanceof Item))
			{
				Item attackerWeapon=(Item)msg.tool();
				if((!anyWeapons(mob))
				&&(attackerWeapon!=null)
				&&(attackerWeapon instanceof Weapon)
				&&(mob.charStats().getBodyPart(Race.BODY_HAND)>0)
				&&(CMLib.flags().canBeSeenBy(msg.source(),mob))
				&&(((Weapon)attackerWeapon).weaponClassification()!=Weapon.CLASS_FLAILED)
				&&(((Weapon)attackerWeapon).weaponClassification()!=Weapon.CLASS_NATURAL)
				&&(((Weapon)attackerWeapon).weaponClassification()!=Weapon.CLASS_RANGED)
				&&(((Weapon)attackerWeapon).weaponClassification()!=Weapon.CLASS_THROWN))
				{
					CMMsg msg2=CMClass.getMsg(mob,msg.source(),this,CMMsg.MSG_NOISYMOVEMENT,"<S-NAME> circle-parr(ys) "+attackerWeapon.name()+" attack from <T-NAME>!");
					if((proficiencyCheck(null,mob.charStats().getStat(CharStats.STAT_DEXTERITY)-90+(2*getXLEVELLevel(mob)),false))
					&&(!lastTime)
					&&(mob.location().okMessage(mob,msg2)))
					{
						lastTime=true;
						mob.location().send(mob,msg2);
						helpProficiency(mob);
						return false;
					}
					lastTime=false;
				}
			}
		}
		return true;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Trypethelium leucotrypum Nyl.

### Remarks
null


text:
module Claim
  class AdvocateClaim < BaseClaim
    route_key_name 'advocates_claim'

    include ProviderDelegation

    has_many :basic_fees,
             foreign_key: :claim_id,
             class_name: 'Fee::BasicFee',
             dependent: :destroy,
             inverse_of: :claim,
             validate: proc { |claim| claim.step_validation_required?(:basic_fees) }
    has_many :fixed_fees, -> { reorder(:fee_type_id) },
             foreign_key: :claim_id,
             class_name: 'Fee::FixedFee',
             dependent: :destroy,
             inverse_of: :claim,
             validate: proc { |claim| claim.step_validation_required?(:fixed_fees) }
    has_one :interim_claim_info,
            foreign_key: :claim_id,
            dependent: :destroy,
            inverse_of: :claim,
            validate: proc { |claim| claim.step_validation_required?(:miscellaneous_fees) }

    accepts_nested_attributes_for :basic_fees, reject_if: all_blank_or_zero, allow_destroy: true
    accepts_nested_attributes_for :fixed_fees, reject_if: all_blank_or_zero, allow_destroy: true
    accepts_nested_attributes_for :interim_claim_info, reject_if: :all_blank, allow_destroy: false

    validates_with ::Claim::AdvocateClaimValidator, unless: proc { |c| c.disable_for_state_transition.eql?(:all) }
    validates_with ::Claim::AdvocateClaimSubModelValidator

    delegate :requires_cracked_dates?, to: :case_type, allow_nil: true

    after_initialize do
      instantiate_basic_fees
    end

    before_validation do
      set_supplier_number
      assign_total_attrs
    end

    SUBMISSION_STAGES = [
      {
        name: :case_details,
        transitions: [
          { to_stage: :defendants }
        ]
      },
      {
        name: :defendants,
        transitions: [
          {
            to_stage: :offence_details,
            condition: ->(claim) { !claim.fixed_fee_case? }
          },
          {
            to_stage: :fixed_fees,
            condition: ->(claim) { claim.fixed_fee_case? }
          }
        ],
        dependencies: %i[case_details]
      },
      {
        name: :offence_details,
        transitions: [
          { to_stage: :basic_fees }
        ],
        dependencies: %i[case_details defendants]
      },
      {
        name: :basic_fees,
        transitions: [
          { to_stage: :miscellaneous_fees }
        ],
        dependencies: %i[case_details defendants offence_details]
      },
      {
        name: :fixed_fees,
        transitions: [
          { to_stage: :miscellaneous_fees }
        ],
        dependencies: %i[case_details defendants]
      },
      {
        name: :miscellaneous_fees,
        transitions: [
          { to_stage: :travel_expenses }
        ]
      },
      {
        name: :travel_expenses,
        transitions: [
          { to_stage: :supporting_evidence }
        ]
      },
      { name: :supporting_evidence }
    ].freeze

    def assign_total_attrs
      # TODO: understand if this check is really needed
      # left it here mostly to ensure the new changes do
      # not impact anything API related
      return if from_api?
      assign_fees_total(%i[basic_fees fixed_fees misc_fees]) if fees_changed?
      assign_expenses_total if expenses_changed?
      return unless total_changes_required?
      assign_total
      assign_vat
    end

    def total_changes_required?
      fees_changed? || expenses_changed?
    end

    def fees_changed?
      %i[basic fixed misc].any? { |fee_type| public_send("#{fee_type}_fees_changed?") }
    end

    def basic_fees_changed?
      basic_fees.any?(&:changed?)
    end

    def fixed_fees_changed?
      fixed_fees.any?(&:changed?)
    end

    def eligible_case_types
      CaseType.agfs
    end

    def eligible_basic_fee_types
      # TODO: this should return a list based on the current given fee scheme
      # rather than conditionally return scheme 10 specifically
      # TBD once all the fee scheme work is integrated
      return Fee::BasicFeeType.unscoped.agfs_scheme_10s.order(:position) if agfs_reform?
      Fee::BasicFeeType.agfs_scheme_9s
    end

    def eligible_fixed_fee_types
      Claims::FetchEligibleFixedFeeTypes.new(self).call
    end

    def external_user_type
      :advocate
    end

    def agfs?
      self.class.agfs?
    end

    def final?
      true
    end

    def eligible_advocate_categories
      Claims::FetchEligibleAdvocateCategories.for(self)
    end

    def update_claim_document_owners
      documents.each { |d| d.update_column(:external_user_id, external_user_id) }
    end

    def discontinuance?
      case_type&.fee_type_code.eql?('GRDIS')
    end

    private

    # create a blank fee for every basic fee type not passed to Claim::AdvocateClaim.new
    def instantiate_basic_fees
      return unless case_type.present? && !case_type.is_fixed_fee?
      return unless editable?

      fee_type_ids = basic_fees.map(&:fee_type_id)
      eligible_basic_fee_type_ids = eligible_basic_fee_types.map(&:id)
      not_eligible_ids = fee_type_ids - eligible_basic_fee_type_ids
      self.basic_fees = basic_fees.reject { |fee| not_eligible_ids.include?(fee.fee_type_id) }
      eligible_basic_fee_types.each do |basic_fee_type|
        next if fee_type_ids.include?(basic_fee_type.id)
        basic_fees.build(fee_type: basic_fee_type, quantity: 0, amount: 0)
      end
    end

    def cleaner
      Cleaners::AdvocateClaimCleaner.new(self)
    end
  end
end


text:
import {todoInjectables} from './TodoService';

// Include injectables that you want to have globally throughout our app
export var appServicesInjectables: Array<any> = [
  todoInjectables
];


text:
import cli = require('@rushstack/ts-command-line');
import type { MigrateDownOptions, MigrateUpOptions } from './types';
import type { Umzug } from './umzug';

export abstract class ApplyMigrationsAction extends cli.CommandLineAction {
	private _params: ReturnType<typeof ApplyMigrationsAction._defineParameters>;
	declare actionName: 'up' | 'down';

	protected constructor(
		protected readonly umzug: Umzug,
		cliOptions: cli.ICommandLineActionOptions & { actionName: 'up' | 'down' }
	) {
		super(cliOptions);
	}

	private static _defineParameters(action: ApplyMigrationsAction) {
		const verb = ApplyMigrationsAction.getVerb(action.actionName);

		return {
			to: action.defineStringParameter({
				parameterLongName: '--to',
				argumentName: 'NAME',
				// prettier-ignore
				description: `All migrations up to and including this one should be ${verb}. ${verb === 'reverted' ? 'Pass "0" to revert all.' : ''}`.trim(),
			}),
			step: action.defineIntegerParameter({
				parameterLongName: '--step',
				argumentName: 'COUNT',
				// prettier-ignore
				description: `Run this many migrations. If not specified, ${verb === 'reverted' ? 'one' : 'all'} will be ${verb}.`,
			}),
			name: action.defineStringListParameter({
				parameterLongName: '--name',
				argumentName: 'MIGRATION',
				description: `Explicity declare migration name(s) to be ${verb}.`,
			}),
			rerun: action.defineChoiceParameter({
				parameterLongName: '--rerun',
				description: `Specify what action should be taken when a migration that has already been ${verb} is passed to --name.`,
				alternatives: ['THROW', 'SKIP', 'ALLOW'],
				defaultValue: 'THROW',
			}),
		};
	}

	onDefineParameters(): void {
		this._params = ApplyMigrationsAction._defineParameters(this);
	}

	private static getVerb(direction: 'up' | 'down') {
		return {
			up: 'applied',
			down: 'reverted',
		}[direction];
	}

	async onExecute(): Promise<void> {
		const {
			to: { value: to },
			step: { value: step },
			name: { values: nameArray },
			rerun: { value: rerun },
		} = this._params;

		// string list parameters are always defined. When they're empty it means nothing was passed.
		const maybeNameArray = nameArray.length > 0 ? nameArray : undefined;

		if (to && maybeNameArray) {
			throw new Error(`Can't specify 'to' and 'name' together`);
		}

		if (to && typeof step === 'number') {
			throw new Error(`Can't specify 'to' and 'step' together`);
		}

		if (typeof step === 'number' && maybeNameArray) {
			throw new Error(`Can't specify 'step' and 'name' together`);
		}

		if (rerun !== 'THROW' && !maybeNameArray) {
			throw new Error(`Can't specify 'rerun' without 'name'`);
		}

		const params = {
			to: to === '0' ? 0 : to,
			step,
			migrations: maybeNameArray,
			rerun,
		};
		const actions = {
			up: async () => this.umzug.up(params as MigrateUpOptions),
			down: async () => this.umzug.down(params as MigrateDownOptions),
		};
		const result = await actions[this.actionName]();

		const verb = ApplyMigrationsAction.getVerb(this.actionName);

		this.umzug.options.logger?.info({ event: this.actionName, message: `${verb} ${result.length} migrations.` });
	}
}

export class UpAction extends ApplyMigrationsAction {
	constructor(umzug: Umzug) {
		super(umzug, {
			actionName: 'up',
			summary: 'Applies pending migrations',
			documentation: 'Performs all migrations. See --help for more options',
		});
	}
}

export class DownAction extends ApplyMigrationsAction {
	constructor(umzug: Umzug) {
		super(umzug, {
			actionName: 'down',
			summary: 'Revert migrations',
			documentation:
				'Undoes previously-applied migrations. By default, undoes the most recent migration only. Use --help for more options. Useful in development to start from a clean slate. Use with care in production!',
		});
	}
}

export class ListAction extends cli.CommandLineAction {
	private _params: ReturnType<typeof ListAction._defineParameters>;

	constructor(private readonly action: 'pending' | 'executed', private readonly umzug: Umzug) {
		super({
			actionName: action,
			summary: `Lists ${action} migrations`,
			documentation: `Prints migrations returned by \`umzug.${action}()\`. By default, prints migration names one per line.`,
		});
	}

	private static _defineParameters(action: cli.CommandLineAction) {
		return {
			json: action.defineFlagParameter({
				parameterLongName: '--json',
				description:
					`Print ${action.actionName} migrations in a json format including names and paths. This allows piping output to tools like jq. ` +
					`Without this flag, the migration names will be printed one per line.`,
			}),
		};
	}

	onDefineParameters(): void {
		this._params = ListAction._defineParameters(this);
	}

	async onExecute(): Promise<void> {
		const migrations = await this.umzug[this.action]();
		const formatted = this._params.json.value
			? JSON.stringify(migrations, null, 2)
			: migrations.map(m => m.name).join('\n');
		// eslint-disable-next-line no-console
		console.log(formatted);
	}
}

export class CreateAction extends cli.CommandLineAction {
	private _params: ReturnType<typeof CreateAction._defineParameters>;

	constructor(readonly umzug: Umzug) {
		super({
			actionName: 'create',
			summary: 'Create a migration file',
			documentation:
				'Generates a placeholder migration file using a timestamp as a prefix. By default, mimics the last existing migration, or guesses where to generate the file if no migration exists yet.',
		});
	}

	private static _defineParameters(action: cli.CommandLineAction) {
		return {
			name: action.defineStringParameter({
				parameterLongName: '--name',
				argumentName: 'NAME',
				description: `The name of the migration file. e.g. my-migration.js, my-migration.ts or my-migration.sql. Note - a prefix will be added to this name, usually based on a timestamp. See --prefix`,
				required: true,
			}),
			prefix: action.defineChoiceParameter({
				parameterLongName: '--prefix',
				description:
					'The prefix format for generated files. TIMESTAMP uses a second-resolution timestamp, DATE uses a day-resolution timestamp, and NONE removes the prefix completely',
				alternatives: ['TIMESTAMP', 'DATE', 'NONE'],
				defaultValue: 'TIMESTAMP',
			}),
			folder: action.defineStringParameter({
				parameterLongName: '--folder',
				argumentName: 'PATH',
				description: `Path on the filesystem where the file should be created. The new migration will be created as a sibling of the last existing one if this is omitted.`,
			}),
			allowExtension: action.defineStringListParameter({
				parameterLongName: '--allow-extension',
				argumentName: 'EXTENSION',
				environmentVariable: 'UMZUG_ALLOW_EXTENSION',
				description: `Allowable extension for created files. By default .js, .ts and .sql files can be created. To create txt file migrations, for example, you could use '--name my-migration.txt --allow-extension .txt'`,
			}),
			skipVerify: action.defineFlagParameter({
				parameterLongName: '--skip-verify',
				description:
					`By default, the generated file will be checked after creation to make sure it is detected as a pending migration. This catches problems like creation in the wrong folder, or invalid naming conventions. ` +
					`This flag bypasses that verification step.`,
			}),
			allowConfusingOrdering: action.defineFlagParameter({
				parameterLongName: '--allow-confusing-ordering',
				description:
					`By default, an error will be thrown if you try to create a migration that will run before a migration that already exists. ` +
					`This catches errors which can cause problems if you change file naming conventions. ` +
					`If you use a custom ordering system, you can disable this behavior, but it's strongly recommended that you don't! ` +
					`If you're unsure, just ignore this option.`,
			}),
		};
	}

	onDefineParameters(): void {
		this._params = CreateAction._defineParameters(this);
	}

	async onExecute(): Promise<void> {
		await this.umzug
			.create({
				// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
				name: this._params.name.value!,
				prefix: this._params.prefix.value as 'TIMESTAMP' | 'DATE' | 'NONE',
				folder: this._params.folder.value,
				allowExtension:
					this._params.allowExtension.values.length > 0 ? this._params.allowExtension.values[0] : undefined,
				allowConfusingOrdering: this._params.allowConfusingOrdering.value,
				skipVerify: this._params.skipVerify.value,
			})
			.catch((e: Error) => {
				Object.entries(this._params)
					.filter(entry => entry[0] !== 'name')
					.forEach(([name, param]) => {
						// replace `skipVerify` in error messages with `--skip-verify`, etc.
						e.message = e.message?.split(name).join(param.longName);
					});
				throw e;
			});
	}
}

export type CommandLineParserOptions = {
	toolFileName?: string;
	toolDescription?: string;
};

export class UmzugCLI extends cli.CommandLineParser {
	constructor(readonly umzug: Umzug, commandLineParserOptions: CommandLineParserOptions = {}) {
		super({
			toolFilename: commandLineParserOptions.toolFileName ?? '<script>',
			toolDescription: commandLineParserOptions.toolDescription ?? 'Umzug migrator',
		});

		this.addAction(new UpAction(umzug));
		this.addAction(new DownAction(umzug));
		this.addAction(new ListAction('pending', umzug));
		this.addAction(new ListAction('executed', umzug));
		this.addAction(new CreateAction(umzug));
	}

	onDefineParameters(): void {}
}


text:
// MIT © 2017 azu
import * as React from "react";
import Combokeys from "combokeys";
import { BaseContainer } from "../../../BaseContainer";
import { SubscriptionListState } from "../../Subscription/SubscriptionList/SubscriptionListStore";
import { createShowSubscriptionContentsUseCase } from "../../../../../use-case/subscription/ShowSubscriptionContentsUseCase";
import debounce from "lodash.debounce";
import { SubscriptionContentsState } from "../../Subscription/SubscriptionContents/SubscriptionContentsStore";
import { ScrollToNextContentUseCase } from "../../Subscription/SubscriptionContents/use-case/ScrollToNextContentUseCase";
import { ScrollToPrevContentUseCase } from "../../Subscription/SubscriptionContents/use-case/ScrollToPrevContentUseCase";
import { createMarkAsReadToServerUseCase } from "../../../../../use-case/subscription/MarkAsReadToServerUseCase";
import { createOpenSubscriptionContentInNewTabUseCase } from "../../../../../use-case/subscription/OpenSubscriptionContentInNewTabUseCase";
import { createUpdateHeaderMessageUseCase } from "../../../../../use-case/app/UpdateHeaderMessageUseCase";
import { SubscriptionIdentifier } from "../../../../../domain/Subscriptions/Subscription";
import {
    TurnOffContentsFilterUseCase,
    TurnOnContentsFilterUseCase
} from "../../Subscription/SubscriptionContents/use-case/ToggleFilterContents";
import { createFetchMoreSubscriptContentsUseCase } from "../../../../../use-case/subscription/FetchMoreSubscriptContentsUseCase";
import { ToggleAllListGroupUseCase } from "../../Subscription/SubscriptionList/use-case/ToggleAllListGroupUseCase";
import { createReleaseFocusSubscriptionUseCase } from "../../../../../use-case/subscription/ReleaseFocusSubscriptionUseCase";
import { FaMapSigns as MapSigns } from "react-icons/fa";

const DEBOUNCE_TIME = 32;
const IGNORE_NODE_NAME_PATTERN = /webview/i;
const isIgnoreNode = (event: Event): boolean => {
    const target = event.target as HTMLElement;
    if (!target) {
        return false;
    }
    if (!target.nodeName) {
        return false;
    }
    return IGNORE_NODE_NAME_PATTERN.test(target.nodeName);
};

/**
 * Scroll by screen size ratio
 * @param {HTMLElement} target
 * @param {number} ratio
 * @param {"up" | "down"} direction
 */
const scrollByScrollSize = (target: HTMLElement, ratio: number, direction: "up" | "down") => {
    const directionOperator = direction === "down" ? 1 : -1;
    ratio = ratio || 1;
    target.scrollBy(0, (window.innerHeight / 2) * directionOperator * ratio);
};

export interface ShortcutKeyContainerProps {
    subscriptionContents: SubscriptionContentsState;
    subscriptionList: SubscriptionListState;
}

export class ShortcutKeyContainer extends BaseContainer<ShortcutKeyContainerProps, {}> {
    combokeys: any;

    triggerKey(keys: string, action?: string): void {
        if (this.combokeys) {
            this.combokeys.trigger(keys, action);
        }
    }

    registerKey(key: string, handler: (event?: Event) => void): void {
        if (this.combokeys) {
            this.combokeys.bind(key, handler);
        }
    }

    /**
     * Default keyMap Object by
     */
    defaultActions = (() => {
        const loadNext = async (currentSubscriptionId?: SubscriptionIdentifier) => {
            if (!currentSubscriptionId) {
                const firstItem = this.props.subscriptionList.getFirstItem();
                if (!firstItem) {
                    return console.info("Not found first item");
                }
                await this.useCase(createShowSubscriptionContentsUseCase()).execute(firstItem.props.id);
                return;
            }
            const nextItem = this.props.subscriptionList.getNextItem(currentSubscriptionId);
            if (!nextItem) {
                return console.info("Not found next item");
            }
            this.useCase(createShowSubscriptionContentsUseCase())
                .execute(nextItem.props.id)
                .catch((error) => {
                    return this.useCase(createUpdateHeaderMessageUseCase())
                        .execute(`Can't load... Skip ${nextItem.title}.`)
                        .then(() => {
                            return loadNext(nextItem.props.id);
                        });
                });
        };
        let actionMap = {
            "move-next-subscription-feed": debounce(async (_event: Event) => {
                const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
                await loadNext(currentSubscriptionId);
            }, DEBOUNCE_TIME),
            "move-prev-subscription-feed": debounce(async (_event: Event) => {
                const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
                if (!currentSubscriptionId) {
                    return;
                }
                const nextItem = this.props.subscriptionList.getPrevItem(currentSubscriptionId);
                if (!nextItem) {
                    return console.info("Not found next item");
                }
                await this.useCase(createShowSubscriptionContentsUseCase()).execute(nextItem.props.id);
            }, DEBOUNCE_TIME),
            "move-next-content-item": (_event: Event) => {
                const body = document.querySelector(".SubscriptionContentsContainer");
                if (!body) {
                    return;
                }
                if (body.scrollTop === 0) {
                    const firstContent = this.props.subscriptionContents.getFirstContent();
                    if (firstContent) {
                        return this.useCase(new ScrollToNextContentUseCase()).execute(firstContent.id);
                    }
                }
                const currentContent = this.props.subscriptionContents.focusContentId;
                const nextContent = this.props.subscriptionContents.getNextContent();
                if (currentContent && !nextContent) {
                    // last item and next
                    return this.useCase(createUpdateHeaderMessageUseCase()).execute(
                        <span>
                            <MapSigns /> End of contents
                        </span>
                    );
                }
                if (!nextContent) {
                    return;
                }
                return this.useCase(new ScrollToNextContentUseCase()).execute(nextContent.id);
            },
            "move-prev-content-item": (_event: Event) => {
                const prevContent = this.props.subscriptionContents.getPrevContent();
                if (!prevContent) {
                    return;
                }
                this.useCase(new ScrollToPrevContentUseCase()).execute(prevContent.id);
            },
            "scroll-down-content": (event: Event) => {
                event.preventDefault();
                // TODO: make explicitly
                const contentContainer = document.querySelector(".SubscriptionContentsContainer") as HTMLElement;
                if (contentContainer) {
                    scrollByScrollSize(contentContainer, 0.3, "down");
                }
            },
            "scroll-up-content": (event: Event) => {
                event.preventDefault();
                // TODO: make explicitly
                const contentContainer = document.querySelector(".SubscriptionContentsContainer") as HTMLElement;
                if (contentContainer) {
                    scrollByScrollSize(contentContainer, 0.3, "up");
                }
            },
            "make-subscription-read": (event: Event) => {
                event.preventDefault();
                const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
                if (currentSubscriptionId) {
                    this.useCase(createMarkAsReadToServerUseCase()).execute(currentSubscriptionId);
                }
            },
            "open-current-content-url": (event: Event) => {
                event.preventDefault();
                const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
                const focusContentId = this.props.subscriptionContents.focusContentId;
                if (!currentSubscriptionId || !focusContentId) {
                    return;
                }
                this.useCase(createOpenSubscriptionContentInNewTabUseCase()).execute(
                    currentSubscriptionId,
                    focusContentId
                );
            },
            "toggle-content-filter": (_event: Event) => {
                if (this.props.subscriptionContents.enableContentFilter) {
                    this.useCase(new TurnOffContentsFilterUseCase()).execute();
                } else {
                    this.useCase(new TurnOnContentsFilterUseCase()).execute();
                }
            },
            "toggle-subscription-feed-list": (_event: Event) => {
                this.useCase(new ToggleAllListGroupUseCase()).execute();
            },
            "load-more-past-contents": async (_event: Event) => {
                const subscription = this.props.subscriptionContents.subscription;
                if (!subscription) {
                    return;
                }
                const beforeFocusContendId = this.props.subscriptionContents.focusContentId;
                // disable content filter
                this.useCase(new TurnOffContentsFilterUseCase()).execute();
                this.useCase(createUpdateHeaderMessageUseCase()).execute("Load more past contents");
                // fetch more contents
                await this.useCase(createFetchMoreSubscriptContentsUseCase()).execute(subscription.props.id);
                // move next content if the user was not moved
                if (
                    beforeFocusContendId &&
                    beforeFocusContendId.equals(this.props.subscriptionContents.focusContentId)
                ) {
                    actionMap["move-next-content-item"](_event);
                }
            },
            "skip-and-move-next-subscription-feed": async (_event: Event) => {
                const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
                if (!currentSubscriptionId) {
                    return;
                }
                await this.useCase(createUpdateHeaderMessageUseCase()).execute("Skip current subscription");
                await this.useCase(createReleaseFocusSubscriptionUseCase()).execute();
                await loadNext(currentSubscriptionId);
            }
        };
        return actionMap;
    })();

    componentDidMount() {
        this.combokeys = new Combokeys(document.documentElement || document.body);
        const actionMap = this.defaultActions;
        const keyMap: { [index: string]: keyof typeof actionMap } = {
            j: "move-next-content-item",
            "shift+j": "load-more-past-contents",
            t: "toggle-content-filter",
            k: "move-prev-content-item",
            a: "move-prev-subscription-feed",
            s: "move-next-subscription-feed",
            m: "make-subscription-read",
            v: "open-current-content-url",
            z: "toggle-subscription-feed-list",
            space: "scroll-down-content",
            "shift+space": "scroll-up-content",
            "shift+s": "skip-and-move-next-subscription-feed"
        };
        Object.keys(keyMap).forEach((key) => {
            this.combokeys.bind(key, (event: Event) => {
                if (isIgnoreNode(event)) {
                    return;
                }
                actionMap[keyMap[key]](event);
            });
        });
    }

    componentWillUnmount() {
        this.combokeys.detach();
    }

    render() {
        return null;
    }
}


text:
<?php

namespace Doctrine2l5;

use Auth;
use Config;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityManager;

use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Cache\Cache;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\Configuration;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\Mapping\ClassMetadataFactory;

use Doctrine2l5\EventListeners\TablePrefix;
use Doctrine2l5\Support\Repository as D2Repository;

class Doctrine2ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    /**
     * Have we been configured?
     */
    private $configured = true;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot( \Doctrine\Common\Cache\Cache $d2cache )
    {
        // handle publishing of config file:
        $this->handleConfigs();

        if( !$this->configured ) {
            if( isset( $_SERVER['argv'][1] ) && $_SERVER['argv'][1] != 'vendor:publish' )
                echo "You must pubish the configuration files first: artisan vendor:publish\n";
            return;
        }

        $d2em = $this->app->make( \Doctrine\ORM\EntityManagerInterface::class );
        $d2em->getConfiguration()->setMetadataCacheImpl( $d2cache );
        $d2em->getConfiguration()->setQueryCacheImpl( $d2cache );
        $d2em->getConnection()->getConfiguration()->setResultCacheImpl( $d2cache );

        if( Config::get( 'd2doctrine.sqllogger.enabled' ) )
            $this->attachLogger( $d2em );

        if( Config::get( 'd2doctrine.auth.enabled' ) )
            $this->setupAuth();
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        if( !Config::get( 'd2doctrine' ) ) {
            if( isset( $_SERVER['argv'][1] ) && $_SERVER['argv'][1] != 'vendor:publish' )
                echo "You must pubish the configuration files first: artisan vendor:publish\n";
            $this->configured = false;
            return;
        }

        $this->registerEntityManager();
        $this->registerClassMetadataFactory();
        $this->registerConsoleCommands();
        $this->registerRepositoryFacade();
        $this->registerFacades();
    }

    /**
     * The Entity Manager - why we're all here!
     */
    private function registerEntityManager()
    {
        $this->app->singleton( EntityManagerInterface::class, function( $app ) {

            $paths = [ Config::get('d2doctrine.paths.entities') ];
            $annotations_path = base_path().'/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php';

            AnnotationRegistry::registerFile($annotations_path);

            $dconfig        = new Configuration();
            $reader         = new AnnotationReader();
            $driverImpl     = new AnnotationDriver($reader, $paths);

            $dconfig->setMetadataDriverImpl($driverImpl);

            $dconfig->setProxyDir(                 Config::get( 'd2doctrine.paths.proxies'      ) );
            $dconfig->setProxyNamespace(           Config::get( 'd2doctrine.namespaces.proxies' ) );
            $dconfig->setAutoGenerateProxyClasses( Config::get( 'd2doctrine.autogen_proxies'    ) );

            $lconfig = $this->laravelToDoctrineConfigMapper();

            //load prefix listener
            if( isset($lconfig['prefix']) && $lconfig['prefix'] && $lconfig['prefix'] !== '' ) {
                $tablePrefix = new TablePrefix( $lconfig['prefix']);
                $eventManager->addEventListener(Events::loadClassMetadata, $tablePrefix);
            }

            $dconfig->addCustomNumericFunction('SIN', '\Doctrine2l5\Query\Extensions\Sin');
            $dconfig->addCustomNumericFunction('ASIN', '\Doctrine2l5\Query\Extensions\Asin');
            $dconfig->addCustomNumericFunction('COS', '\Doctrine2l5\Query\Extensions\Cos');
            $dconfig->addCustomNumericFunction('ACOS', '\Doctrine2l5\Query\Extensions\Acos');
            $dconfig->addCustomNumericFunction('RADIANS', '\Doctrine2l5\Query\Extensions\Radians');
            $dconfig->addCustomNumericFunction('PI', '\Doctrine2l5\Query\Extensions\Pi');
            $dconfig->addCustomNumericFunction('DEGREES', '\Doctrine2l5\Query\Extensions\Degrees');

            return EntityManager::create( $lconfig, $dconfig );
        });

        // $this->app->singleton( EntityManagerInterface::class, function( $app ) {
        //     $dconfig = new \Doctrine\ORM\Configuration;
        //     $driver = new \Doctrine\ORM\Mapping\Driver\YamlDriver(
        //         array( Config::get( 'd2doctrine.paths.yml' ) )
        //     );
        //     $dconfig->setMetadataDriverImpl( $driver );
        //     $dconfig->setProxyDir(                 Config::get( 'd2doctrine.paths.proxies'      ) );
        //     $dconfig->setProxyNamespace(           Config::get( 'd2doctrine.namespaces.proxies' ) );
        //     $dconfig->setAutoGenerateProxyClasses( Config::get( 'd2doctrine.autogen_proxies'    ) );
        //     $lconfig = $this->laravelToDoctrineConfigMapper();
        //     //load prefix listener
        //     if( isset($lconfig['prefix']) && $lconfig['prefix'] && $lconfig['prefix'] !== '' ) {
        //         $tablePrefix = new TablePrefix( $lconfig['prefix']);
        //         $eventManager->addEventListener(Events::loadClassMetadata, $tablePrefix);
        //     }
        //     return EntityManager::create( $lconfig, $dconfig );
        // });

    }

    /**
     * Register Facades to make developers' lives easier
     */
    private function registerFacades()
    {
        // Shortcut so developers don't need to add an Alias in app/config/app.php
        \App::booting( function() {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias( 'D2EM', 'Doctrine2l5\Support\Facades\Doctrine2' );
        });
    }

    /**
     * Register Laravel console commands
     */
    private function registerConsoleCommands()
    {
        $this->commands([
            "\Doctrine2l5\Console\Generators\All",
            "\Doctrine2l5\Console\Generators\Entities",
            "\Doctrine2l5\Console\Generators\Proxies",
            "\Doctrine2l5\Console\Generators\Repositories",
            "\Doctrine2l5\Console\Schema\Create",
            "\Doctrine2l5\Console\Schema\Drop",
            "\Doctrine2l5\Console\Schema\Update",
            "\Doctrine2l5\Console\Schema\Validate",
        ]);
    }

    /**
     * Metadata Factory - mainly used by schema console commands
     */
    private function registerClassMetadataFactory()
    {
        $this->app->singleton( ClassMetadataFactory::class, function( $app ) {
            return $app[EntityManagerInterface::class]->getMetadataFactory();
        });
    }

    private function registerRepositoryFacade()
    {
        $this->app->bind( D2Repository::class, function( $app ) {
            return new D2Repository;
        });

        \App::booting( function() {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias( 'D2R', 'Doctrine2l5\Support\Facades\Doctrine2Repository' );
        });

    }

    /**
     * Attach Laravel logging to Doctrine for debugging / profiling
     */
    private function attachLogger( $d2em )
    {
        $logger = new Logger\Laravel;
        if( Config::has( 'd2doctrine.sqllogger.level' ) )
            $logger->setLevel( Config::get( 'd2doctrine.sqllogger.level' ) );

        $d2em->getConnection()->getConfiguration()->setSQLLogger( $logger );
    }

    /**
     * Set up Laravel authentication via Doctrine2 provider
     */
    private function setupAuth()
    {
        Auth::extend( 'doctrine2l5', function() {
            return new \Illuminate\Auth\Guard(
                new \Doctrine2l5\Auth\Doctrine2UserProvider(
                    \D2EM::getRepository( Config::get( 'd2doctrine.auth.entity' ) ),
                    new \Illuminate\Hashing\BcryptHasher
                ),
                \App::make('session.store')
            );
        });
    }

    /**
     * Publish configuration file
     */
    private function handleConfigs() {
        $configPath = __DIR__ . '/../config/d2doctrine.php';
        $this->publishes( [ $configPath => config_path('d2doctrine.php') ] );
        $this->mergeConfigFrom( $configPath, 'd2doctrine' );
    }

    /**
     * Convert Laravel5's database configuration to something what Doctrine2's
     * DBAL providers can use.
     *
     * @return array
     */
    private function laravelToDoctrineConfigMapper()
    {
        switch( Config::get( 'database.default' ) ) {
            case 'mysql':
                return [
                    'driver'   => 'pdo_mysql',
                    'dbname'   => Config::get( 'database.connections.mysql.database' ),
                    'user'     => Config::get( 'database.connections.mysql.username' ),
                    'password' => Config::get( 'database.connections.mysql.password' ),
                    'host'     => Config::get( 'database.connections.mysql.host'     ),
                    'charset'  => Config::get( 'database.connections.mysql.charset'  ),
                    'prefix'   => Config::get( 'database.connections.mysql.prefix'   ),
                ];
                break;

            case 'pgsql':
                return [
                    'driver'   => 'pdo_pgsql',
                    'dbname'   => Config::get( 'database.connections.pgsql.database' ),
                    'user'     => Config::get( 'database.connections.pgsql.username' ),
                    'password' => Config::get( 'database.connections.pgsql.password' ),
                    'host'     => Config::get( 'database.connections.pgsql.host'     ),
                    'charset'  => Config::get( 'database.connections.pgsql.charset'  ),
                    'prefix'   => Config::get( 'database.connections.pgsql.prefix'   ),
                ];
                break;

            case 'sqlite':
                return [
                    'driver'   => 'pdo_sqlite',
                    'path'     => Config::get( 'database.connections.sqlite.database' ),
                    'user'     => Config::get( 'database.connections.sqlite.username' ),
                    'password' => Config::get( 'database.connections.sqlite.password' ),
                    'prefix'   => Config::get( 'database.connections.sqlite.prefix'   ),
                ];
                break;

                default:
                    throw new Doctrine2l5\Exception\ImplementationNotFound( Config::get( 'database.default' ) );
        }
    }
}