text:
class Passenger < Formula
  desc "Server for Ruby, Python, and Node.js apps via Apache/NGINX"
  homepage "https://www.phusionpassenger.com/"
  url "https://github.com/phusion/passenger/releases/download/release-6.0.6/passenger-6.0.6.tar.gz"
  sha256 "fbf89ebfacc079bdf6466567eabc9eb741a5abd8f230133311f7a40fff763842"
  license "MIT"
  revision 2
  head "https://github.com/phusion/passenger.git", branch: "stable-6.0"

  bottle do
    cellar :any
    sha256 "d2276b41d2d3fbcbf98627083a47ea507ec87902f10caf08b5992297ba8b0e41" => :catalina
    sha256 "3051d187b0aa3d6099819447899d25fe0cbe55997d453823be7102b9a9df90c5" => :mojave
    sha256 "c5e5ec2ca304fde4469c076c3959435680fd40b9ca4a0e2b6ca6c27851ceef19" => :high_sierra
  end

  # to build nginx module
  depends_on "nginx" => [:build, :test]
  depends_on "openssl@1.1"
  depends_on "pcre"

  def install
    if MacOS.version >= :mojave && MacOS::CLT.installed?
      ENV["SDKROOT"] = MacOS::CLT.sdk_path(MacOS.version)
    else
      ENV.delete("SDKROOT")
    end

    inreplace "src/ruby_supportlib/phusion_passenger/platform_info/openssl.rb" do |s|
      s.gsub! "-I/usr/local/opt/openssl/include", "-I#{Formula["openssl@1.1"].opt_include}"
      s.gsub! "-L/usr/local/opt/openssl/lib", "-L#{Formula["openssl@1.1"].opt_lib}"
    end

    system "rake", "apache2"
    system "rake", "nginx"
    nginx_addon_dir = `./bin/passenger-config about nginx-addon-dir`.strip

    mkdir "nginx" do
      system "tar", "-xf", "#{Formula["nginx"].opt_pkgshare}/src/src.tar.xz", "--strip-components", "1"
      args = (Formula["nginx"].opt_pkgshare/"src/configure_args.txt").read.split("\n")
      args << "--add-dynamic-module=#{nginx_addon_dir}"

      system "./configure", *args
      system "make"
      (libexec/"modules").install "objs/ngx_http_passenger_module.so"
    end

    (libexec/"download_cache").mkpath

    # Fixes https://github.com/phusion/passenger/issues/1288
    rm_rf "buildout/libev"
    rm_rf "buildout/libuv"
    rm_rf "buildout/cache"

    necessary_files = %w[configure Rakefile README.md CONTRIBUTORS
                         CONTRIBUTING.md LICENSE CHANGELOG package.json
                         passenger.gemspec build bin doc images dev src
                         resources buildout]

    cp_r necessary_files, libexec, preserve: true

    # Allow Homebrew to create symlinks for the Phusion Passenger commands.
    bin.install_symlink Dir["#{libexec}/bin/*"]

    # Ensure that the Phusion Passenger commands can always find their library
    # files.

    locations_ini = `./bin/passenger-config --make-locations-ini --for-native-packaging-method=homebrew`
    locations_ini.gsub!(/=#{Regexp.escape Dir.pwd}/, "=#{libexec}")
    (libexec/"src/ruby_supportlib/phusion_passenger/locations.ini").write(locations_ini)

    ruby_libdir = `./bin/passenger-config about ruby-libdir`.strip
    ruby_libdir.gsub!(/^#{Regexp.escape Dir.pwd}/, libexec)
    system "./dev/install_scripts_bootstrap_code.rb",
      "--ruby", ruby_libdir, *Dir[libexec/"bin/*"]

    system "./bin/passenger-config", "compile-nginx-engine"
    cp Dir["buildout/support-binaries/nginx*"], libexec/"buildout/support-binaries", preserve: true

    nginx_addon_dir.gsub!(/^#{Regexp.escape Dir.pwd}/, libexec)
    system "./dev/install_scripts_bootstrap_code.rb",
      "--nginx-module-config", libexec/"bin", "#{nginx_addon_dir}/config"

    man1.install Dir["man/*.1"]
    man8.install Dir["man/*.8"]
  end

  def caveats
    <<~EOS
      To activate Phusion Passenger for Nginx, run:
        brew install nginx
      And add the following to #{etc}/nginx/nginx.conf at the top scope (outside http{}):
        load_module #{opt_libexec}/modules/ngx_http_passenger_module.so;
      And add the following to #{etc}/nginx/nginx.conf in the http scope:
        passenger_root #{opt_libexec}/src/ruby_supportlib/phusion_passenger/locations.ini;
        passenger_ruby /usr/bin/ruby;

      To activate Phusion Passenger for Apache, create /etc/apache2/other/passenger.conf:
        LoadModule passenger_module #{opt_libexec}/buildout/apache2/mod_passenger.so
        PassengerRoot #{opt_libexec}/src/ruby_supportlib/phusion_passenger/locations.ini
        PassengerDefaultRuby /usr/bin/ruby
    EOS
  end

  test do
    ruby_libdir = `#{HOMEBREW_PREFIX}/bin/passenger-config --ruby-libdir`.strip
    assert_equal "#{libexec}/src/ruby_supportlib", ruby_libdir

    (testpath/"nginx.conf").write <<~EOS
      load_module #{opt_libexec}/modules/ngx_http_passenger_module.so;
      worker_processes 4;
      error_log #{testpath}/error.log;
      pid #{testpath}/nginx.pid;

      events {
        worker_connections 1024;
      }

      http {
        passenger_root #{opt_libexec}/src/ruby_supportlib/phusion_passenger/locations.ini;
        passenger_ruby /usr/bin/ruby;
        client_body_temp_path #{testpath}/client_body_temp;
        fastcgi_temp_path #{testpath}/fastcgi_temp;
        proxy_temp_path #{testpath}/proxy_temp;
        scgi_temp_path #{testpath}/scgi_temp;
        uwsgi_temp_path #{testpath}/uwsgi_temp;
        passenger_temp_path #{testpath}/passenger_temp;

        server {
          passenger_enabled on;
          listen 8080;
          root #{testpath};
          access_log #{testpath}/access.log;
          error_log #{testpath}/error.log;
        }
      }
    EOS
    system "#{Formula["nginx"].opt_bin}/nginx", "-t", "-c", testpath/"nginx.conf"
  end
end


text:
package dagger.android.processor;

import static com.google.auto.common.AnnotationMirrors.getAnnotatedAnnotations;
import static com.google.common.collect.Iterables.getOnlyElement;
import static dagger.android.processor.AndroidMapKeys.injectedTypeFromMapKey;

import com.google.auto.common.BasicAnnotationProcessor.Step;
import com.google.auto.common.MoreElements;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.squareup.javapoet.ClassName;
import dagger.MapKey;
import javax.annotation.processing.Messager;
import javax.inject.Qualifier;
import javax.inject.Scope;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic.Kind;

/** Validates the correctness of {@link dagger.MapKey}s used with {@code dagger.android}. */
final class AndroidMapKeyValidator implements Step {
  private static final ImmutableMap<String, ClassName> SUPPORTED_ANNOTATIONS =
      ImmutableMap.of(
          TypeNames.ANDROID_INJECTION_KEY.toString(), TypeNames.ANDROID_INJECTION_KEY,
          TypeNames.CLASS_KEY.toString(), TypeNames.CLASS_KEY);

  private final Elements elements;
  private final Types types;
  private final Messager messager;

  AndroidMapKeyValidator(Elements elements, Types types, Messager messager) {
    this.elements = elements;
    this.types = types;
    this.messager = messager;
  }

  @Override
  public ImmutableSet<String> annotations() {
    return SUPPORTED_ANNOTATIONS.keySet();
  }

  @Override
  public ImmutableSet<Element> process(ImmutableSetMultimap<String, Element> elementsByAnnotation) {
    ImmutableSet.Builder<Element> deferredElements = ImmutableSet.builder();
    elementsByAnnotation
        .entries()
        .forEach(
            entry -> {
              try {
                validateMethod(entry.getKey(), MoreElements.asExecutable(entry.getValue()));
              } catch (TypeNotPresentException e) {
                deferredElements.add(entry.getValue());
              }
            });
    return deferredElements.build();
  }

  private void validateMethod(String annotation, ExecutableElement method) {
    if (!getAnnotatedAnnotations(method, Qualifier.class).isEmpty()) {
      return;
    }

    TypeMirror returnType = method.getReturnType();
    if (!types.isAssignable(types.erasure(returnType), factoryElement().asType())) {
      // if returnType is not related to AndroidInjector.Factory, ignore the method
      return;
    }

    if (!getAnnotatedAnnotations(method, Scope.class).isEmpty()) {
      SuppressWarnings suppressedWarnings = method.getAnnotation(SuppressWarnings.class);
      if (suppressedWarnings == null
          || !ImmutableSet.copyOf(suppressedWarnings.value())
              .contains("dagger.android.ScopedInjectorFactory")) {
        AnnotationMirror mapKeyAnnotation =
            getOnlyElement(getAnnotatedAnnotations(method, MapKey.class));
        TypeElement mapKeyValueElement =
            elements.getTypeElement(injectedTypeFromMapKey(mapKeyAnnotation).get());
        messager.printMessage(
            Kind.ERROR,
            String.format(
                "%s bindings should not be scoped. Scoping this method may leak instances of %s.",
                TypeNames.ANDROID_INJECTOR_FACTORY.canonicalName(),
                mapKeyValueElement.getQualifiedName()),
            method);
      }
    }

    validateReturnType(method);

    // @Binds methods should only have one parameter, but we can't guarantee the order of Processors
    // in javac, so do a basic check for valid form
    if (MoreDaggerElements.isAnnotationPresent(method, TypeNames.BINDS)
        && method.getParameters().size() == 1) {
      validateMapKeyMatchesBindsParameter(annotation, method);
    }
  }

  /** Report an error if the method's return type is not {@code AndroidInjector.Factory<?>}. */
  private void validateReturnType(ExecutableElement method) {
    TypeMirror returnType = method.getReturnType();
    DeclaredType requiredReturnType = injectorFactoryOf(types.getWildcardType(null, null));

    if (!types.isSameType(returnType, requiredReturnType)) {
      messager.printMessage(
          Kind.ERROR,
          String.format(
              "%s should bind %s, not %s. See https://dagger.dev/android",
              method, requiredReturnType, returnType),
          method);
    }
  }

  /**
   * A valid @Binds method could bind an {@code AndroidInjector.Factory} for one type, while giving
   * it a map key of a different type. The return type and parameter type would pass typical @Binds
   * validation, but the map lookup in {@code DispatchingAndroidInjector} would retrieve the wrong
   * injector factory.
   *
   * <pre>{@code
   * {@literal @Binds}
   * {@literal @IntoMap}
   * {@literal @ClassKey(GreenActivity.class)}
   * abstract AndroidInjector.Factory<?> bindBlueActivity(
   *     BlueActivityComponent.Builder builder);
   * }</pre>
   */
  private void validateMapKeyMatchesBindsParameter(String annotation, ExecutableElement method) {
    TypeMirror parameterType = getOnlyElement(method.getParameters()).asType();
    AnnotationMirror annotationMirror =
        MoreDaggerElements.getAnnotationMirror(method, SUPPORTED_ANNOTATIONS.get(annotation)).get();
    TypeMirror mapKeyType =
        elements.getTypeElement(injectedTypeFromMapKey(annotationMirror).get()).asType();
    if (!types.isAssignable(parameterType, injectorFactoryOf(mapKeyType))) {
      messager.printMessage(
          Kind.ERROR,
          String.format("%s does not implement AndroidInjector<%s>", parameterType, mapKeyType),
          method,
          annotationMirror);
    }
  }

  /** Returns a {@link DeclaredType} for {@code AndroidInjector.Factory<implementationType>}. */
  private DeclaredType injectorFactoryOf(TypeMirror implementationType) {
    return types.getDeclaredType(factoryElement(), implementationType);
  }

  private TypeElement factoryElement() {
    return elements.getTypeElement(TypeNames.ANDROID_INJECTOR_FACTORY.canonicalName());
  }
}

redpajama_set_name: RedPajamaGithub


text:
factory = modelingSession.getModel()
partition = selectedElements.get(0)
action = factory.createOpaqueAction()
note= factory.createNote('.*', 'description', action, 'relDl=(worst=0, best=0, value=0, prob=1.0)')
note.setMimeType('text/plain')
action.setName('chunk')
partition.getContainedNode().add(action)


text:
package org.biobank.platedecoder.ui;

import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.StackPane;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Code borrowed from:
 *   https://community.oracle.com/thread/2541811
 */
public class ZoomingPane extends ScrollPane {

    @SuppressWarnings("unused")
    private static final Logger LOG = LoggerFactory.getLogger(ZoomingPane.class);

    private static final double ZOOM_IN = 1.1;

    private static final double ZOOM_OUT = 1.0 / ZOOM_IN;

    private DoubleProperty zoomScaleProperty;

    public ZoomingPane(Node content) {
        final StackPane zoomPane = new StackPane();
        this.zoomScaleProperty = new SimpleDoubleProperty(1.0);
        zoomPane.getChildren().add(content);

        final Group scrollContent = new Group(zoomPane);
        setContent(scrollContent);

        viewportBoundsProperty().addListener((observable, oldValue, newValue) -> {
                zoomPane.setMinSize(newValue.getWidth(), newValue.getHeight());
            });

        zoomPane.addEventFilter(ScrollEvent.ANY, (ScrollEvent event) -> {
                double scaleFactor = (event.getDeltaY() > 0) ? ZOOM_IN : ZOOM_OUT;

                // amount of scrolling in each direction in scrollContent coordinate units
                Point2D scrollOffset = figureScrollOffset(scrollContent);

                double scale = content.getScaleX() * scaleFactor;
                zoomScaleProperty.setValue(scale);
                content.setScaleX(scale);
                content.setScaleY(scale);

                // move viewport so that old center remains in the center after the scaling
                repositionScroller(scrollContent, scaleFactor, scrollOffset);

                event.consume();
            });

        // Panning via drag....
        final ObjectProperty<Point2D> lastMouseCoordinates = new SimpleObjectProperty<Point2D>();
        scrollContent.setOnMousePressed(event -> {
                lastMouseCoordinates.set(new Point2D(event.getX(), event.getY()));
            });

        scrollContent.setOnMouseDragged(event -> {
                final Point2D mouseCoords = lastMouseCoordinates.get();
                final Bounds bounds = getViewportBounds();
                final Bounds scrollContentBounds = scrollContent.getLayoutBounds();
                double hValue, vValue;

                double deltaX = event.getX() - mouseCoords.getX();
                double extraWidth = scrollContentBounds.getWidth() - bounds.getWidth();
                if (extraWidth > 0.0) {
                    double deltaH = deltaX * (getHmax() - getHmin()) / extraWidth;
                    double desiredH = getHvalue() - deltaH;
                    hValue = Math.max(0, Math.min(getHmax(), desiredH));
                } else {
                    hValue = 0.0;
                }
                setHvalue(hValue);

                double deltaY = event.getY() - mouseCoords.getY();
                double extraHeight = scrollContentBounds.getHeight() - bounds.getHeight();
                if (extraHeight > 0.0) {
                    double deltaV = deltaY * (getHmax() - getHmin()) / extraHeight;
                    double desiredV = getVvalue() - deltaV;
                    vValue = Math.max(0, Math.min(getVmax(), desiredV));
                } else {
                    vValue = 0.0;
                }
                setVvalue(vValue);
            });
    }

    private Point2D figureScrollOffset(Node scrollContent) {
        final Bounds bounds = getViewportBounds();
        final Bounds scrollContentBounds = scrollContent.getLayoutBounds();

        double extraWidth = scrollContentBounds.getWidth() - bounds.getWidth();
        double hScrollProportion = (getHvalue() - getHmin()) / (getHmax() - getHmin());
        double scrollXOffset = hScrollProportion * Math.max(0, extraWidth);
        double extraHeight = scrollContentBounds.getHeight() - bounds.getHeight();
        double vScrollProportion = (getVvalue() - getVmin()) / (getVmax() - getVmin());
        double scrollYOffset = vScrollProportion * Math.max(0, extraHeight);
        return new Point2D(scrollXOffset, scrollYOffset);
    }

    private void repositionScroller(Node scrollContent,
                                    double scaleFactor,
                                    Point2D scrollOffset) {
        final Bounds bounds = getViewportBounds();
        final Bounds scrollContentBounds = scrollContent.getLayoutBounds();

        double scrollXOffset = scrollOffset.getX();
        double scrollYOffset = scrollOffset.getY();
        double extraWidth = scrollContentBounds.getWidth() - bounds.getWidth();
        double hValue, vValue;

        if (extraWidth > 0) {
            double halfWidth = bounds.getWidth() / 2 ;
            double newScrollXOffset = (scaleFactor - 1) *  halfWidth + scaleFactor * scrollXOffset;
            hValue = getHmin() + newScrollXOffset * (getHmax() - getHmin()) / extraWidth;
        } else {
            hValue = getHmin();
        }
        setHvalue(hValue);

        double extraHeight = scrollContentBounds.getHeight() - bounds.getHeight();
        if (extraHeight > 0) {
            double halfHeight = bounds.getHeight() / 2 ;
            double newScrollYOffset = (scaleFactor - 1) * halfHeight + scaleFactor * scrollYOffset;
            vValue = getVmin() + newScrollYOffset * (getVmax() - getVmin()) / extraHeight;
        } else {
            vValue = getVmin();
        }
        setVvalue(vValue);
    }

    /**
     * Returns the scaling factor used to display the image.
     *
     * The user can zoom into and out of the image. The scale factor represents the amount of zoom.
     *
     * @return the zoomScaleProperty
     */
    public DoubleProperty getZoomScaleProperty() {
        return zoomScaleProperty;
    }

}


text:
/********************************************************************************/
/*										*/
/*			     				*/
/*			     Written by Ken Goldman				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*            $Id: PP.c 809 2016-11-16 18:31:54Z kgoldman $			*/
/*										*/
/*  Licenses and Notices							*/
/*										*/
/*  1. Copyright Licenses:							*/
/*										*/
/*  - Trusted Computing Group (TCG) grants to the user of the source code in	*/
/*    this specification (the "Source Code") a worldwide, irrevocable, 		*/
/*    nonexclusive, royalty free, copyright license to reproduce, create 	*/
/*    derivative works, distribute, display and perform the Source Code and	*/
/*    derivative works thereof, and to grant others the rights granted herein.	*/
/*										*/
/*  - The TCG grants to the user of the other parts of the specification 	*/
/*    (other than the Source Code) the rights to reproduce, distribute, 	*/
/*    display, and perform the specification solely for the purpose of 		*/
/*    developing products based on such documents.				*/
/*										*/
/*  2. Source Code Distribution Conditions:					*/
/*										*/
/*  - Redistributions of Source Code must retain the above copyright licenses, 	*/
/*    this list of conditions and the following disclaimers.			*/
/*										*/
/*  - Redistributions in binary form must reproduce the above copyright 	*/
/*    licenses, this list of conditions	and the following disclaimers in the 	*/
/*    documentation and/or other materials provided with the distribution.	*/
/*										*/
/*  3. Disclaimers:								*/
/*										*/
/*  - THE COPYRIGHT LICENSES SET FORTH ABOVE DO NOT REPRESENT ANY FORM OF	*/
/*  LICENSE OR WAIVER, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, WITH	*/
/*  RESPECT TO PATENT RIGHTS HELD BY TCG MEMBERS (OR OTHER THIRD PARTIES)	*/
/*  THAT MAY BE NECESSARY TO IMPLEMENT THIS SPECIFICATION OR OTHERWISE.		*/
/*  Contact TCG Administration (admin@trustedcomputinggroup.org) for 		*/
/*  information on specification licensing rights available through TCG 	*/
/*  membership agreements.							*/
/*										*/
/*  - THIS SPECIFICATION IS PROVIDED "AS IS" WITH NO EXPRESS OR IMPLIED 	*/
/*    WARRANTIES WHATSOEVER, INCLUDING ANY WARRANTY OF MERCHANTABILITY OR 	*/
/*    FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, COMPLETENESS, OR 		*/
/*    NONINFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS, OR ANY WARRANTY 		*/
/*    OTHERWISE ARISING OUT OF ANY PROPOSAL, SPECIFICATION OR SAMPLE.		*/
/*										*/
/*  - Without limitation, TCG and its members and licensors disclaim all 	*/
/*    liability, including liability for infringement of any proprietary 	*/
/*    rights, relating to use of information in this specification and to the	*/
/*    implementation of this specification, and TCG disclaims all liability for	*/
/*    cost of procurement of substitute goods or services, lost profits, loss 	*/
/*    of use, loss of data or any incidental, consequential, direct, indirect, 	*/
/*    or special damages, whether under contract, tort, warranty or otherwise, 	*/
/*    arising in any way out of use or reliance upon this specification or any 	*/
/*    information herein.							*/
/*										*/
/*  (c) Copyright IBM Corp. and others, 2016					*/
/*										*/
/********************************************************************************/

/* 8.8 PP.c */
/* 8.8.1 Introduction */
/* This file contains the functions that support the physical presence operations of the TPM. */
/* 8.8.2 Includes */
#include "Tpm.h"
/* 8.8.3 Functions */
/* 8.8.3.1 PhysicalPresencePreInstall_Init() */
/* This function is used to initialize the array of commands that always require confirmation with
   physical presence. The array is an array of bits that has a correspondence with the command
   code. */
/* This command should only ever be executable in a manufacturing setting or in a simulation. */
/* When set, these cannot be cleared. */
void
PhysicalPresencePreInstall_Init(
				void
				)
{
    COMMAND_INDEX        commandIndex;
    // Clear all the PP commands
    MemorySet(&gp.ppList, 0, sizeof(gp.ppList));
    // Any command that is PP_REQUIRED should be SET
    for(commandIndex = 0; commandIndex < COMMAND_COUNT; commandIndex++)
	{
	    if(s_commandAttributes[commandIndex] & IS_IMPLEMENTED
	       &&  s_commandAttributes[commandIndex] & PP_REQUIRED)
		SET_BIT(commandIndex, gp.ppList);
	}
    // Write PP list to NV
    NV_SYNC_PERSISTENT(ppList);
    return;
}
/* 8.8.3.2 PhysicalPresenceCommandSet() */
/* This function is used to set the indicator that a command requires PP confirmation. */
void
PhysicalPresenceCommandSet(
			   TPM_CC           commandCode    // IN: command code
			   )
{
    COMMAND_INDEX       commandIndex = CommandCodeToCommandIndex(commandCode);
    // if the command isn't implemented, the do nothing
    if(commandIndex == UNIMPLEMENTED_COMMAND_INDEX)
	return;
    // only set the bit if this is a command for which PP is allowed
    if(s_commandAttributes[commandIndex] & PP_COMMAND)
	SET_BIT(commandIndex, gp.ppList);
    return;
}
/* 8.8.3.3 PhysicalPresenceCommandClear() */
/* This function is used to clear the indicator that a command requires PP confirmation. */
void
PhysicalPresenceCommandClear(
			     TPM_CC           commandCode    // IN: command code
			     )
{
    COMMAND_INDEX       commandIndex = CommandCodeToCommandIndex(commandCode);
    // If the command isn't implemented, then don't do anything
    if(commandIndex == UNIMPLEMENTED_COMMAND_INDEX)
	return;
    // Only clear the bit if the command does not require PP
    if((s_commandAttributes[commandIndex] & PP_REQUIRED) == 0)
	CLEAR_BIT(commandIndex, gp.ppList);
    return;
}
/* 8.8.3.4 PhysicalPresenceIsRequired() */
/* This function indicates if PP confirmation is required for a command. */
/* Return Values Meaning */
/* TRUE if physical presence is required */
/* FALSE if physical presence is not required */
BOOL
PhysicalPresenceIsRequired(
			   COMMAND_INDEX    commandIndex   // IN: command index
			   )
{
    // Check the bit map.  If the bit is SET, PP authorization is required
    return (TEST_BIT(commandIndex, gp.ppList));
}
/* 8.8.3.5 PhysicalPresenceCapGetCCList() */
/* This function returns a list of commands that require PP confirmation. The list starts from the
   first implemented command that has a command code that the same or greater than commandCode. */
/* Return Values Meaning */
/* YES if there are more command codes available */
/* NO all the available command codes have been returned */
TPMI_YES_NO
PhysicalPresenceCapGetCCList(
			     TPM_CC           commandCode,   // IN: start command code
			     UINT32           count,         // IN: count of returned TPM_CC
			     TPML_CC         *commandList    // OUT: list of TPM_CC
			     )
{
    TPMI_YES_NO     more = NO;
    COMMAND_INDEX   commandIndex;
    // Initialize output handle list
    commandList->count = 0;
    // The maximum count of command we may return is MAX_CAP_CC
    if(count > MAX_CAP_CC) count = MAX_CAP_CC;
    // Collect PP commands
    for(commandIndex = GetClosestCommandIndex(commandCode);
	commandIndex != UNIMPLEMENTED_COMMAND_INDEX;
	commandIndex = GetNextCommandIndex(commandIndex))
	{
	    if(PhysicalPresenceIsRequired(commandIndex))
		{
		    if(commandList->count < count)
			{
			    // If we have not filled up the return list, add this command
			    // code to it
			    commandList->commandCodes[commandList->count]
				= GetCommandCode(commandIndex);
			    commandList->count++;
			}
		    else
			{
			    // If the return list is full but we still have PP command
			    // available, report this and stop iterating
			    more = YES;
			    break;
			}
		}
	}
    return more;
}


text:
try:
    from django.conf.urls import *
except ImportError: # Django < 1.4
    from django.conf.urls.defaults import *
from tastypie.api import Api
from complex.api.resources import PostResource, ProfileResource, CommentResource, UserResource, GroupResource

api = Api(api_name='v1')
api.register(PostResource(), canonical=True)
api.register(ProfileResource(), canonical=True)
api.register(CommentResource(), canonical=True)
api.register(UserResource(), canonical=True)
api.register(GroupResource(), canonical=True)

urlpatterns = api.urls


text:
title: Reactペーパーコンポーネント
components: Paper
githubLabel: 'component: Paper'
---

# Paper

<p class="description">マテリアルデザインでは、紙の物理的特性が画面に変換されます。 </p>

アプリケーションの背景に紙のような質感を与えます。 ペーパーコンポーネントは、サイズを変更したり、シャッフルしたり、複数の紙を表示するように扱うことができます。

{{"component": "modules/components/ComponentLinkHeader.js"}}

## 基本のペーパーコンポーネント

{{"demo": "pages/components/paper/SimplePaper.js", "bg": true}}

## バリアント

If you need an outlined surface, use the `variant` prop.

{{"demo": "pages/components/paper/Variants.js", "bg": "inline"}}

## Elevation

The elevation can be used to establish a hierachy between other content. In practical terms, the elevation controls the size of the shadow applied to the surface. In dark mode, raising the elevation also makes the surface lighter.

{{"demo": "pages/components/paper/Elevation.js", "bg": "inline"}}


text:
import { Injectable } from '@angular/core';
import { INGREDIENTS_TYPE } from './mock-ingredientType';

@Injectable()
export class IngredientTypeService {
  getIngredientTypeList() {
    return Promise.resolve(INGREDIENTS_TYPE).then(
        ingredientType => ingredientType
    );
  }
  getIngredientType(id: number) {
    return Promise.resolve(INGREDIENTS_TYPE).then(
      ingredientType => ingredientType.filter(ingredientType => ingredientType.id === id)[0]

    );
  }

}


text:
/**
 * @constructor
 * @extends {WebInspector.VBox}
 * @implements {WebInspector.Searchable}
 * @implements {WebInspector.TargetManager.Observer}
 * @implements {WebInspector.ViewportControl.Provider}
 */
WebInspector.ConsoleView = function()
{
    WebInspector.VBox.call(this);
    this.registerRequiredCSS("filter.css");

    this._searchableView = new WebInspector.SearchableView(this);
    this._searchableView.setMinimalSearchQuerySize(0);
    this._searchableView.show(this.element);

    this._contentsElement = this._searchableView.element;
    this._contentsElement.classList.add("console-view");
    this._visibleViewMessages = [];
    this._urlToMessageCount = {};
    this._hiddenByFilterCount = 0;

    this._clearConsoleButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear console log."), "clear-status-bar-item");
    this._clearConsoleButton.addEventListener("click", this._requestClearMessages, this);

    this._executionContextSelector = new WebInspector.StatusBarComboBox(this._executionContextChanged.bind(this), "console-context");

    /**
     * @type {!Map.<!WebInspector.ExecutionContext, !Element>}
     */
    this._optionByExecutionContext = new Map();

    this._filter = new WebInspector.ConsoleViewFilter(this);
    this._filter.addEventListener(WebInspector.ConsoleViewFilter.Events.FilterChanged, this._updateMessageList.bind(this));

    this._filterBar = new WebInspector.FilterBar();

    this._preserveLogCheckbox = new WebInspector.StatusBarCheckbox(WebInspector.UIString("Preserve log"));
    WebInspector.SettingsUI.bindCheckbox(this._preserveLogCheckbox.inputElement, WebInspector.settings.preserveConsoleLog);
    this._preserveLogCheckbox.element.title = WebInspector.UIString("Do not clear log on page reload / navigation.");

    var statusBarElement = this._contentsElement.createChild("div", "console-status-bar");
    statusBarElement.appendChildren(this._clearConsoleButton.element, this._filterBar.filterButton().element, this._executionContextSelector.element, this._preserveLogCheckbox.element);

    this._filtersContainer = this._contentsElement.createChild("div", "console-filters-header hidden");
    this._filtersContainer.appendChild(this._filterBar.filtersElement());
    this._filterBar.addEventListener(WebInspector.FilterBar.Events.FiltersToggled, this._onFiltersToggled, this);
    this._filterBar.setName("consoleView");
    this._filter.addFilters(this._filterBar);

    this._viewport = new WebInspector.ViewportControl(this);
    this._viewport.setStickToBottom(true);
    this._viewport.contentElement().classList.add("console-group", "console-group-messages");
    this._contentsElement.appendChild(this._viewport.element);
    this._messagesElement = this._viewport.element;
    this._messagesElement.id = "console-messages";
    this._messagesElement.classList.add("monospace");
    this._messagesElement.addEventListener("click", this._messagesClicked.bind(this), true);

    this._viewportThrottler = new WebInspector.Throttler(50);

    this._filterStatusMessageElement = document.createElementWithClass("div", "console-message");
    this._messagesElement.insertBefore(this._filterStatusMessageElement, this._messagesElement.firstChild);
    this._filterStatusTextElement = this._filterStatusMessageElement.createChild("span", "console-info");
    this._filterStatusMessageElement.createTextChild(" ");
    var resetFiltersLink = this._filterStatusMessageElement.createChild("span", "console-info node-link");
    resetFiltersLink.textContent = WebInspector.UIString("Show all messages.");
    resetFiltersLink.addEventListener("click", this._filter.reset.bind(this._filter), true);

    this._topGroup = WebInspector.ConsoleGroup.createTopGroup();
    this._currentGroup = this._topGroup;

    this._promptElement = this._messagesElement.createChild("div", "source-code");
    this._promptElement.id = "console-prompt";
    this._promptElement.spellcheck = false;

    // FIXME: This is a workaround for the selection machinery bug. See crbug.com/410899
    var selectAllFixer = this._messagesElement.createChild("div", "console-view-fix-select-all");
    selectAllFixer.textContent = ".";

    this._showAllMessagesCheckbox = new WebInspector.StatusBarCheckbox(WebInspector.UIString("Show all messages"));
    this._showAllMessagesCheckbox.inputElement.checked = true;
    this._showAllMessagesCheckbox.inputElement.addEventListener("change", this._updateMessageList.bind(this), false);

    this._showAllMessagesCheckbox.element.classList.add("hidden");

    statusBarElement.appendChild(this._showAllMessagesCheckbox.element);

    this._registerShortcuts();

    this._messagesElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), false);
    WebInspector.settings.monitoringXHREnabled.addChangeListener(this._monitoringXHREnabledSettingChanged, this);

    this._linkifier = new WebInspector.Linkifier();

    /** @type {!Array.<!WebInspector.ConsoleViewMessage>} */
    this._consoleMessages = [];

    this._prompt = new WebInspector.TextPromptWithHistory(WebInspector.ExecutionContextSelector.completionsForTextPromptInCurrentContext);
    this._prompt.setSuggestBoxEnabled(true);
    this._prompt.renderAsBlock();
    this._prompt.attach(this._promptElement);
    this._prompt.proxyElement.addEventListener("keydown", this._promptKeyDown.bind(this), false);
    this._prompt.setHistoryData(WebInspector.settings.consoleHistory.get());
    var historyData = WebInspector.settings.consoleHistory.get();
    this._prompt.setHistoryData(historyData);

    this._updateFilterStatus();
    WebInspector.settings.consoleTimestampsEnabled.addChangeListener(this._consoleTimestampsSettingChanged, this);

    this._registerWithMessageSink();
    WebInspector.targetManager.observeTargets(this);
    WebInspector.targetManager.addModelListener(WebInspector.RuntimeModel, WebInspector.RuntimeModel.Events.ExecutionContextCreated, this._onExecutionContextCreated, this);
    WebInspector.targetManager.addModelListener(WebInspector.RuntimeModel, WebInspector.RuntimeModel.Events.ExecutionContextDestroyed, this._onExecutionContextDestroyed, this);
    this._initConsoleMessages();

    WebInspector.context.addFlavorChangeListener(WebInspector.ExecutionContext, this._executionContextChangedExternally, this);
}

WebInspector.ConsoleView.prototype = {
    _initConsoleMessages: function()
    {
        var mainTarget = WebInspector.targetManager.mainTarget();
        if (!WebInspector.isWorkerFrontend() && (!mainTarget || !mainTarget.resourceTreeModel.cachedResourcesLoaded())) {
            WebInspector.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, this._onResourceTreeModelLoaded, this);
            return;
        }
        this._fetchMultitargetMessages();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onResourceTreeModelLoaded: function(event)
    {
        var resourceTreeModel = event.target;
        if (resourceTreeModel.target() !== WebInspector.targetManager.mainTarget())
            return;
        WebInspector.targetManager.removeModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, this._onResourceTreeModelLoaded, this);
        this._fetchMultitargetMessages();
    },

    _fetchMultitargetMessages: function()
    {
        WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this);
        WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._onConsoleMessageAdded, this);
        WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.CommandEvaluated, this._commandEvaluated, this);
        WebInspector.multitargetConsoleModel.messages().forEach(this._addConsoleMessage, this);
    },

    /**
     * @return {number}
     */
    itemCount: function()
    {
        return this._visibleViewMessages.length;
    },

    /**
     * @param {number} index
     * @return {?WebInspector.ViewportElement}
     */
    itemElement: function(index)
    {
        return this._visibleViewMessages[index];
    },

    /**
     * @param {number} index
     * @return {number}
     */
    fastHeight: function(index)
    {
        return this._visibleViewMessages[index].fastHeight();
    },

    /**
     * @return {number}
     */
    minimumRowHeight: function()
    {
        return 16;
    },

    /**
     * @param {!WebInspector.Target} target
     */
    targetAdded: function(target)
    {
        this._viewport.invalidate();
        target.runtimeModel.executionContexts().forEach(this._executionContextCreated, this);
        if (WebInspector.targetManager.targets().length > 1)
            this._showAllMessagesCheckbox.element.classList.toggle("hidden", false);
    },

    /**
     * @param {!WebInspector.Target} target
     */
    targetRemoved: function(target)
    {
        this._clearExecutionContextsForTarget(target);
    },

    _registerWithMessageSink: function()
    {
        WebInspector.console.messages().forEach(this._addSinkMessage, this);
        WebInspector.console.addEventListener(WebInspector.Console.Events.MessageAdded, messageAdded, this);

        /**
         * @param {!WebInspector.Event} event
         * @this {WebInspector.ConsoleView}
         */
        function messageAdded(event)
        {
            this._addSinkMessage(/** @type {!WebInspector.Console.Message} */ (event.data));
        }
    },

    /**
     * @param {!WebInspector.Console.Message} message
     */
    _addSinkMessage: function(message)
    {
        var level = WebInspector.ConsoleMessage.MessageLevel.Debug;
        switch (message.level) {
        case WebInspector.Console.MessageLevel.Error:
            level = WebInspector.ConsoleMessage.MessageLevel.Error;
            break;
        case WebInspector.Console.MessageLevel.Warning:
            level = WebInspector.ConsoleMessage.MessageLevel.Warning;
            break;
        }

        var consoleMessage = new WebInspector.ConsoleMessage(null, WebInspector.ConsoleMessage.MessageSource.Other, level, message.text,
                undefined, undefined, undefined, undefined, undefined, undefined, undefined, message.timestamp);
        this._addConsoleMessage(consoleMessage);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _consoleTimestampsSettingChanged: function(event)
    {
        var enabled = /** @type {boolean} */ (event.data);
        this._updateMessageList();
        this._consoleMessages.forEach(function(viewMessage) {
            viewMessage.updateTimestamp(enabled);
        });
    },

    /**
     * @return {!Element}
     */
    defaultFocusedElement: function()
    {
        return this._promptElement
    },

    _onFiltersToggled: function(event)
    {
        var toggled = /** @type {boolean} */ (event.data);
        this._filtersContainer.classList.toggle("hidden", !toggled);
    },

    /**
     * @param {!WebInspector.ExecutionContext} executionContext
     * @return {string}
     */
    _titleFor: function(executionContext)
    {
        var result;
        if (executionContext.isMainWorldContext) {
            if (executionContext.frameId) {
                var frame = executionContext.target().resourceTreeModel.frameForId(executionContext.frameId);
                result =  frame ? frame.displayName() : (executionContext.origin || executionContext.name);
            } else {
                result = WebInspector.displayNameForURL(executionContext.origin) || executionContext.name;
            }
        } else
            result = "\u00a0\u00a0\u00a0\u00a0" + (executionContext.name || executionContext.origin);

        var maxLength = 50;
        return result.trimMiddle(maxLength);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onExecutionContextCreated: function(event)
    {
        var executionContext = /** @type {!WebInspector.ExecutionContext} */ (event.data);
        this._executionContextCreated(executionContext);
    },

    /**
     * @param {!WebInspector.ExecutionContext} executionContext
     */
    _executionContextCreated: function(executionContext)
    {
        var newOption = document.createElement("option");
        newOption.__executionContext = executionContext;
        newOption.text = this._titleFor(executionContext);
        this._optionByExecutionContext.set(executionContext, newOption);
        var sameGroupExists = false;
        var options = this._executionContextSelector.selectElement().options;
        var insertBeforeOption = null;
        for (var i = 0; i < options.length; ++i) {
            var optionContext = options[i].__executionContext;
            var isSameGroup = executionContext.target() === optionContext.target() && executionContext.frameId === optionContext.frameId;
            sameGroupExists |= isSameGroup;
            if ((isSameGroup && WebInspector.ExecutionContext.comparator(optionContext, executionContext) > 0) || (sameGroupExists && !isSameGroup)) {
                insertBeforeOption = options[i];
                break;
            }
        }
        this._executionContextSelector.selectElement().insertBefore(newOption, insertBeforeOption);
        if (executionContext === WebInspector.context.flavor(WebInspector.ExecutionContext))
            this._executionContextSelector.select(newOption);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onExecutionContextDestroyed: function(event)
    {
        var executionContext = /** @type {!WebInspector.ExecutionContext} */ (event.data);
        this._executionContextDestroyed(executionContext);
    },

    /**
     * @param {!WebInspector.ExecutionContext} executionContext
     */
    _executionContextDestroyed: function(executionContext)
    {
        var option = this._optionByExecutionContext.remove(executionContext);
        option.remove();
    },

    /**
     * @param {!WebInspector.Target} target
     */
    _clearExecutionContextsForTarget: function(target)
    {
        var executionContexts = this._optionByExecutionContext.keys();
        for (var i = 0; i < executionContexts.length; ++i) {
            if (executionContexts[i].target() === target)
                this._executionContextDestroyed(executionContexts[i]);
        }
    },

    _executionContextChanged: function()
    {
        var newContext = this._currentExecutionContext();
        WebInspector.context.setFlavor(WebInspector.ExecutionContext, newContext);
        this._prompt.clearAutoComplete(true);
        if (!this._showAllMessagesCheckbox.checked())
            this._updateMessageList();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _executionContextChangedExternally: function(event)
    {
        var executionContext =  /** @type {?WebInspector.ExecutionContext} */ (event.data);
        if (!executionContext)
            return;

        var options = this._executionContextSelector.selectElement().options;
        for (var i = 0; i < options.length; ++i) {
            if (options[i].__executionContext === executionContext)
                this._executionContextSelector.select(options[i]);
        }
    },

    /**
     * @return {?WebInspector.ExecutionContext}
     */
    _currentExecutionContext: function()
    {
        var option = this._executionContextSelector.selectedOption();
        return option ? option.__executionContext : null;
    },

    willHide: function()
    {
        this._prompt.hideSuggestBox();
        this._prompt.clearAutoComplete(true);
    },

    wasShown: function()
    {
        this._viewport.refresh();
        if (!this._prompt.isCaretInsidePrompt())
            this._prompt.moveCaretToEndOfPrompt();
    },

    focus: function()
    {
        if (this._promptElement === WebInspector.currentFocusElement())
            return;
        WebInspector.setCurrentFocusElement(this._promptElement);
        this._prompt.moveCaretToEndOfPrompt();
    },

    restoreScrollPositions: function()
    {
        if (this._viewport.scrolledToBottom())
            this._immediatelyScrollToBottom();
        else
            WebInspector.View.prototype.restoreScrollPositions.call(this);
    },

    onResize: function()
    {
        this._scheduleViewportRefresh();
        this._prompt.hideSuggestBox();
        if (this._viewport.scrolledToBottom())
            this._immediatelyScrollToBottom();
    },

    _scheduleViewportRefresh: function()
    {
        /**
         * @param {!WebInspector.Throttler.FinishCallback} finishCallback
         * @this {WebInspector.ConsoleView}
         */
        function invalidateViewport(finishCallback)
        {
            this._viewport.invalidate();
            finishCallback();
        }
        this._viewportThrottler.schedule(invalidateViewport.bind(this));
    },

    _immediatelyScrollToBottom: function()
    {
        // This will scroll viewport and trigger its refresh.
        this._promptElement.scrollIntoView(true);
    },

    _updateFilterStatus: function()
    {
        this._filterStatusTextElement.textContent = WebInspector.UIString(this._hiddenByFilterCount === 1 ? "%d message is hidden by filters." : "%d messages are hidden by filters.", this._hiddenByFilterCount);
        this._filterStatusMessageElement.style.display = this._hiddenByFilterCount ? "" : "none";
    },

    /**
     * @param {!WebInspector.ConsoleViewMessage} viewMessage
     */
    _consoleMessageAdded: function(viewMessage)
    {
        /**
         * @param {!WebInspector.ConsoleViewMessage} viewMessage1
         * @param {!WebInspector.ConsoleViewMessage} viewMessage2
         * @return {number}
         */
        function compareTimestamps(viewMessage1, viewMessage2)
        {
            return WebInspector.ConsoleMessage.timestampComparator(viewMessage1.consoleMessage(), viewMessage2.consoleMessage());
        }
        var insertAt = insertionIndexForObjectInListSortedByFunction(viewMessage, this._consoleMessages, compareTimestamps, true);
        this._consoleMessages.splice(insertAt, 0, viewMessage);

        var message = viewMessage.consoleMessage();
        if (this._urlToMessageCount[message.url])
            this._urlToMessageCount[message.url]++;
        else
            this._urlToMessageCount[message.url] = 1;

        if (this._tryToCollapseMessages(viewMessage, this._visibleViewMessages.peekLast()))
            return;

        if (this._filter.shouldBeVisible(viewMessage))
            this._showConsoleMessage(viewMessage)
        else {
            this._hiddenByFilterCount++;
            this._updateFilterStatus();
        }
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onConsoleMessageAdded: function(event)
    {
        var message = /** @type {!WebInspector.ConsoleMessage} */ (event.data);
        this._addConsoleMessage(message);
    },

    /**
     * @param {!WebInspector.ConsoleMessage} message
     */
    _addConsoleMessage: function(message)
    {
        var viewMessage = this._createViewMessage(message);
        this._consoleMessageAdded(viewMessage);
        this._scheduleViewportRefresh();
    },

    /**
     * @param {!WebInspector.ConsoleViewMessage} viewMessage
     */
    _showConsoleMessage: function(viewMessage)
    {
        var lastMessage = this._visibleViewMessages.peekLast();
        if (viewMessage.consoleMessage().type === WebInspector.ConsoleMessage.MessageType.EndGroup) {
            if (lastMessage && !this._currentGroup.messagesHidden())
                lastMessage.incrementCloseGroupDecorationCount();
            this._currentGroup = this._currentGroup.parentGroup();
            return;
        }
        if (!this._currentGroup.messagesHidden()) {
            var originatingMessage = viewMessage.consoleMessage().originatingMessage();
            if (lastMessage && originatingMessage && lastMessage.consoleMessage() === originatingMessage)
                lastMessage.toMessageElement().classList.add("console-adjacent-user-command-result");

            this._visibleViewMessages.push(viewMessage);

            if (this._searchRegex && viewMessage.matchesRegex(this._searchRegex)) {
                this._searchResults.push(viewMessage);
                this._searchableView.updateSearchMatchesCount(this._searchResults.length);
            }
        }

        if (viewMessage.consoleMessage().isGroupStartMessage())
            this._currentGroup = new WebInspector.ConsoleGroup(this._currentGroup, viewMessage);
    },

    /**
     * @param {!WebInspector.ConsoleMessage} message
     * @return {!WebInspector.ConsoleViewMessage}
     */
    _createViewMessage: function(message)
    {
        var nestingLevel = this._currentGroup.nestingLevel();
        switch (message.type) {
        case WebInspector.ConsoleMessage.MessageType.Command:
            return new WebInspector.ConsoleCommand(message, nestingLevel);
        case WebInspector.ConsoleMessage.MessageType.Result:
            return new WebInspector.ConsoleCommandResult(message, this._linkifier, nestingLevel);
        case WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed:
        case WebInspector.ConsoleMessage.MessageType.StartGroup:
            return new WebInspector.ConsoleGroupViewMessage(message, this._linkifier, nestingLevel);
        default:
            return new WebInspector.ConsoleViewMessage(message, this._linkifier, nestingLevel);
        }
    },

    _consoleCleared: function()
    {
        this._clearCurrentSearchResultHighlight();
        this._consoleMessages = [];
        this._updateMessageList();

        if (this._searchRegex)
            this._searchableView.updateSearchMatchesCount(0);

        this._linkifier.reset();
    },

    _handleContextMenuEvent: function(event)
    {
        if (event.target.enclosingNodeOrSelfWithNodeName("a"))
            return;

        var contextMenu = new WebInspector.ContextMenu(event);

        function monitoringXHRItemAction()
        {
            WebInspector.settings.monitoringXHREnabled.set(!WebInspector.settings.monitoringXHREnabled.get());
        }
        contextMenu.appendCheckboxItem(WebInspector.UIString("Log XMLHttpRequests"), monitoringXHRItemAction, WebInspector.settings.monitoringXHREnabled.get());

        var sourceElement = event.target.enclosingNodeOrSelfWithClass("console-message-wrapper");
        var consoleMessage = sourceElement ? sourceElement.message.consoleMessage() : null;

        var filterSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString("Filter"));

        if (consoleMessage && consoleMessage.url) {
            var menuTitle = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Hide messages from %s" : "Hide Messages from %s", new WebInspector.ParsedURL(consoleMessage.url).displayName);
            filterSubMenu.appendItem(menuTitle, this._filter.addMessageURLFilter.bind(this._filter, consoleMessage.url));
        }

        filterSubMenu.appendSeparator();
        var unhideAll = filterSubMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Unhide all" : "Unhide All"), this._filter.removeMessageURLFilter.bind(this._filter));
        filterSubMenu.appendSeparator();

        var hasFilters = false;

        for (var url in this._filter.messageURLFilters) {
            filterSubMenu.appendCheckboxItem(String.sprintf("%s (%d)", new WebInspector.ParsedURL(url).displayName, this._urlToMessageCount[url]), this._filter.removeMessageURLFilter.bind(this._filter, url), true);
            hasFilters = true;
        }

        filterSubMenu.setEnabled(hasFilters || (consoleMessage && consoleMessage.url));
        unhideAll.setEnabled(hasFilters);

        contextMenu.appendSeparator();
        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear console" : "Clear Console"), this._requestClearMessages.bind(this));

        var request = consoleMessage ? consoleMessage.request : null;
        if (request && request.type === WebInspector.resourceTypes.XHR) {
            contextMenu.appendSeparator();
            contextMenu.appendItem(WebInspector.UIString("Replay XHR"), NetworkAgent.replayXHR.bind(null, request.requestId));
        }

        contextMenu.show();
    },

    /**
     * @param {!WebInspector.ConsoleViewMessage} lastMessage
     * @param {?WebInspector.ConsoleViewMessage} viewMessage
     * @return {boolean}
     */
    _tryToCollapseMessages: function(lastMessage, viewMessage)
    {
        if (!WebInspector.settings.consoleTimestampsEnabled.get() && viewMessage && !lastMessage.consoleMessage().isGroupMessage() && lastMessage.consoleMessage().isEqual(viewMessage.consoleMessage())) {
            viewMessage.incrementRepeatCount();
            return true;
        }

        return false;
    },

    _updateMessageList: function()
    {
        this._topGroup = WebInspector.ConsoleGroup.createTopGroup();
        this._currentGroup = this._topGroup;
        this._searchResults = [];
        this._hiddenByFilterCount = 0;
        for (var i = 0; i < this._visibleViewMessages.length; ++i) {
            this._visibleViewMessages[i].resetCloseGroupDecorationCount();
            this._visibleViewMessages[i].resetIncrementRepeatCount();
        }
        this._visibleViewMessages = [];
        for (var i = 0; i < this._consoleMessages.length; ++i) {
            var viewMessage = this._consoleMessages[i];
            if (this._tryToCollapseMessages(viewMessage, this._visibleViewMessages.peekLast()))
                continue;
            if (this._filter.shouldBeVisible(viewMessage))
                this._showConsoleMessage(viewMessage);
            else
                this._hiddenByFilterCount++;
        }
        this._updateFilterStatus();
        this._viewport.invalidate();
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _monitoringXHREnabledSettingChanged: function(event)
    {
        var enabled = /** @type {boolean} */ (event.data);
        WebInspector.targetManager.targets().forEach(function(target) {target.consoleAgent().setMonitoringXHREnabled(enabled);});
    },

    /**
     * @param {!Event} event
     */
    _messagesClicked: function(event)
    {
        if (!this._prompt.isCaretInsidePrompt() && window.getSelection().isCollapsed)
            this._prompt.moveCaretToEndOfPrompt();
        var groupMessage = event.target.enclosingNodeOrSelfWithClass("console-group-title");
        if (!groupMessage)
            return;
        var consoleGroupViewMessage = groupMessage.parentElement.message;
        consoleGroupViewMessage.setCollapsed(!consoleGroupViewMessage.collapsed());
        this._updateMessageList();
    },

    _registerShortcuts: function()
    {
        this._shortcuts = {};

        var shortcut = WebInspector.KeyboardShortcut;
        var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Console"));

        var shortcutL = shortcut.makeDescriptor("l", WebInspector.KeyboardShortcut.Modifiers.Ctrl);
        this._shortcuts[shortcutL.key] = this._requestClearMessages.bind(this);
        var keys = [shortcutL];
        if (WebInspector.isMac()) {
            var shortcutK = shortcut.makeDescriptor("k", WebInspector.KeyboardShortcut.Modifiers.Meta);
            this._shortcuts[shortcutK.key] = this._requestClearMessages.bind(this);
            keys.unshift(shortcutK);
        }
        section.addAlternateKeys(keys, WebInspector.UIString("Clear console"));

        section.addKey(shortcut.makeDescriptor(shortcut.Keys.Tab), WebInspector.UIString("Autocomplete common prefix"));
        section.addKey(shortcut.makeDescriptor(shortcut.Keys.Right), WebInspector.UIString("Accept suggestion"));

        var shortcutU = shortcut.makeDescriptor("u", WebInspector.KeyboardShortcut.Modifiers.Ctrl);
        this._shortcuts[shortcutU.key] = this._clearPromptBackwards.bind(this);
        section.addAlternateKeys([shortcutU], WebInspector.UIString("Clear console prompt"));

        keys = [
            shortcut.makeDescriptor(shortcut.Keys.Down),
            shortcut.makeDescriptor(shortcut.Keys.Up)
        ];
        section.addRelatedKeys(keys, WebInspector.UIString("Next/previous line"));

        if (WebInspector.isMac()) {
            keys = [
                shortcut.makeDescriptor("N", shortcut.Modifiers.Alt),
                shortcut.makeDescriptor("P", shortcut.Modifiers.Alt)
            ];
            section.addRelatedKeys(keys, WebInspector.UIString("Next/previous command"));
        }

        section.addKey(shortcut.makeDescriptor(shortcut.Keys.Enter), WebInspector.UIString("Execute command"));
    },

    _clearPromptBackwards: function()
    {
        this._prompt.text = "";
    },

    _requestClearMessages: function()
    {
        var targets = WebInspector.targetManager.targets();
        for (var i = 0; i < targets.length; ++i)
            targets[i].consoleModel.requestClearMessages();
    },

    _promptKeyDown: function(event)
    {
        if (isEnterKey(event)) {
            this._enterKeyPressed(event);
            return;
        }

        var shortcut = WebInspector.KeyboardShortcut.makeKeyFromEvent(event);
        var handler = this._shortcuts[shortcut];
        if (handler) {
            handler();
            event.preventDefault();
        }
    },

    _enterKeyPressed: function(event)
    {
        if (event.altKey || event.ctrlKey || event.shiftKey)
            return;

        event.consume(true);

        this._prompt.clearAutoComplete(true);

        var str = this._prompt.text;
        if (!str.length)
            return;
        this._appendCommand(str, true);
    },

    /**
     * @param {?WebInspector.RemoteObject} result
     * @param {boolean} wasThrown
     * @param {!WebInspector.ConsoleMessage} originatingConsoleMessage
     * @param {?DebuggerAgent.ExceptionDetails=} exceptionDetails
     */
    _printResult: function(result, wasThrown, originatingConsoleMessage, exceptionDetails)
    {
        if (!result)
            return;

        var target = result.target();
        /**
         * @param {string=} url
         * @param {number=} lineNumber
         * @param {number=} columnNumber
         */
        function addMessage(url, lineNumber, columnNumber)
        {
            var level = wasThrown ? WebInspector.ConsoleMessage.MessageLevel.Error : WebInspector.ConsoleMessage.MessageLevel.Log;
            var message;
            if (!wasThrown)
                message = new WebInspector.ConsoleMessage(target, WebInspector.ConsoleMessage.MessageSource.JS, level, "", WebInspector.ConsoleMessage.MessageType.Result, url, lineNumber, columnNumber, undefined, [result]);
            else
                message = new WebInspector.ConsoleMessage(target, WebInspector.ConsoleMessage.MessageSource.JS, level, exceptionDetails.text, WebInspector.ConsoleMessage.MessageType.Result, exceptionDetails.url, exceptionDetails.line, exceptionDetails.column, undefined, [WebInspector.UIString("Uncaught"), result], exceptionDetails.stackTrace);
            message.setOriginatingMessage(originatingConsoleMessage);
            target.consoleModel.addMessage(message);
        }

        if (result.type !== "function") {
            addMessage();
            return;
        }

        result.functionDetails(didGetDetails);

        /**
         * @param {?WebInspector.DebuggerModel.FunctionDetails} response
         */
        function didGetDetails(response)
        {
            if (!response || !response.location) {
                addMessage();
                return;
            }
            var url;
            var lineNumber;
            var columnNumber;
            var script = target.debuggerModel.scriptForId(response.location.scriptId);
            if (script && script.sourceURL) {
                url = script.sourceURL;
                // FIXME(WK62725): Debugger line/column are 0-based, while console ones are 1-based.
                lineNumber = response.location.lineNumber + 1;
                columnNumber = response.location.columnNumber + 1;
            }
            // FIXME: this should be using live location.
            addMessage(url, lineNumber, columnNumber);
        }
    },

    /**
     * @param {string} text
     * @param {boolean} useCommandLineAPI
     */
    _appendCommand: function(text, useCommandLineAPI)
    {

        this._prompt.text = "";
        var currentExecutionContext = WebInspector.context.flavor(WebInspector.ExecutionContext);
        if (currentExecutionContext)
            WebInspector.ConsoleModel.evaluateCommandInConsole(currentExecutionContext, text, useCommandLineAPI);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _commandEvaluated: function(event)
    {
        var data = /**{{result: ?WebInspector.RemoteObject, wasThrown: boolean, text: string, commandMessage: !WebInspector.ConsoleMessage}} */ (event.data);
        this._prompt.pushHistoryItem(data.text);
        WebInspector.settings.consoleHistory.set(this._prompt.historyData.slice(-30));
        this._printResult(data.result, data.wasThrown, data.commandMessage, data.exceptionDetails);
    },

    /**
     * @return {!Array.<!Element>}
     */
    elementsToRestoreScrollPositionsFor: function()
    {
        return [this._messagesElement];
    },

    searchCanceled: function()
    {
        this._clearCurrentSearchResultHighlight();
        delete this._searchResults;
        delete this._searchRegex;
        this._viewport.refresh();
    },

    /**
     * @param {string} query
     * @param {boolean} shouldJump
     * @param {boolean=} jumpBackwards
     */
    performSearch: function(query, shouldJump, jumpBackwards)
    {
        this.searchCanceled();
        this._searchableView.updateSearchMatchesCount(0);
        this._searchRegex = createPlainTextSearchRegex(query, "gi");

        /** @type {!Array.<number>} */
        this._searchResults = [];
        for (var i = 0; i < this._visibleViewMessages.length; i++) {
            if (this._visibleViewMessages[i].matchesRegex(this._searchRegex))
                this._searchResults.push(i);
        }
        this._searchableView.updateSearchMatchesCount(this._searchResults.length);
        this._currentSearchResultIndex = -1;
        if (shouldJump && this._searchResults.length)
            this._jumpToSearchResult(jumpBackwards ? -1 : 0);
        this._viewport.refresh();
    },

    jumpToNextSearchResult: function()
    {
        if (!this._searchResults || !this._searchResults.length)
            return;
        this._jumpToSearchResult(this._currentSearchResultIndex + 1);
    },

    jumpToPreviousSearchResult: function()
    {
        if (!this._searchResults || !this._searchResults.length)
            return;
        this._jumpToSearchResult(this._currentSearchResultIndex - 1);
    },

    _clearCurrentSearchResultHighlight: function()
    {
        if (!this._searchResults)
            return;

        var highlightedViewMessage = this._visibleViewMessages[this._searchResults[this._currentSearchResultIndex]];
        if (highlightedViewMessage)
            highlightedViewMessage.clearHighlight();
        this._currentSearchResultIndex = -1;
    },

    _jumpToSearchResult: function(index)
    {
        index = mod(index, this._searchResults.length);
        this._clearCurrentSearchResultHighlight();
        this._currentSearchResultIndex = index;
        this._searchableView.updateCurrentMatchIndex(this._currentSearchResultIndex);
        var currentViewMessageIndex = this._searchResults[index];
        this._viewport.scrollItemIntoView(currentViewMessageIndex);
        this._visibleViewMessages[currentViewMessageIndex].highlightSearchResults(this._searchRegex);
    },

    __proto__: WebInspector.VBox.prototype
}

/**
 * @constructor
 * @extends {WebInspector.Object}
 * @param {!WebInspector.ConsoleView} view
 */
WebInspector.ConsoleViewFilter = function(view)
{
    this._view = view;
    this._messageURLFilters = WebInspector.settings.messageURLFilters.get();
    this._filterChanged = this.dispatchEventToListeners.bind(this, WebInspector.ConsoleViewFilter.Events.FilterChanged);
};

WebInspector.ConsoleViewFilter.Events = {
    FilterChanged: "FilterChanged"
};

WebInspector.ConsoleViewFilter.prototype = {
    addFilters: function(filterBar)
    {
        this._textFilterUI = new WebInspector.TextFilterUI(true);
        this._textFilterUI.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._textFilterChanged, this);
        filterBar.addFilter(this._textFilterUI);

        var levels = [
            {name: "error", label: WebInspector.UIString("Errors")},
            {name: "warning", label: WebInspector.UIString("Warnings")},
            {name: "info", label: WebInspector.UIString("Info")},
            {name: "log", label: WebInspector.UIString("Logs")},
            {name: "debug", label: WebInspector.UIString("Debug")}
        ];
        this._levelFilterUI = new WebInspector.NamedBitSetFilterUI(levels, WebInspector.settings.messageLevelFilters);
        this._levelFilterUI.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._filterChanged, this);
        filterBar.addFilter(this._levelFilterUI);
    },

    _textFilterChanged: function(event)
    {
        this._filterRegex = this._textFilterUI.regex();

        this._filterChanged();
    },

    /**
     * @param {string} url
     */
    addMessageURLFilter: function(url)
    {
        this._messageURLFilters[url] = true;
        WebInspector.settings.messageURLFilters.set(this._messageURLFilters);
        this._filterChanged();
    },

    /**
     * @param {string} url
     */
    removeMessageURLFilter: function(url)
    {
        if (!url)
            this._messageURLFilters = {};
        else
            delete this._messageURLFilters[url];

        WebInspector.settings.messageURLFilters.set(this._messageURLFilters);
        this._filterChanged();
    },

    /**
     * @returns {!Object}
     */
    get messageURLFilters()
    {
        return this._messageURLFilters;
    },

    /**
     * @param {!WebInspector.ConsoleViewMessage} viewMessage
     * @return {boolean}
     */
    shouldBeVisible: function(viewMessage)
    {
        var message = viewMessage.consoleMessage();
        var executionContext = WebInspector.context.flavor(WebInspector.ExecutionContext);
        if (!message.target())
            return true;

        if (!this._view._showAllMessagesCheckbox.checked() && executionContext) {
            if (message.target() !== executionContext.target())
                return false;
            if (message.executionContextId  && message.executionContextId !== executionContext.id) {
                return false;
            }
        }

        if (viewMessage.consoleMessage().isGroupMessage())
            return true;

        if (message.type === WebInspector.ConsoleMessage.MessageType.Result || message.type === WebInspector.ConsoleMessage.MessageType.Command)
            return true;

        if (message.url && this._messageURLFilters[message.url])
            return false;

        if (message.level && !this._levelFilterUI.accept(message.level))
            return false;

        if (this._filterRegex) {
            this._filterRegex.lastIndex = 0;
            if (!viewMessage.matchesRegex(this._filterRegex))
                return false;
        }

        return true;
    },

    reset: function()
    {
        this._messageURLFilters = {};
        WebInspector.settings.messageURLFilters.set(this._messageURLFilters);
        WebInspector.settings.messageLevelFilters.set({});
        this._view._showAllMessagesCheckbox.inputElement.checked = true;
        this._textFilterUI.setValue("");
        this._filterChanged();
    },

    __proto__: WebInspector.Object.prototype
};

/**
 * @constructor
 * @extends {WebInspector.ConsoleViewMessage}
 * @param {!WebInspector.ConsoleMessage} message
 * @param {number} nestingLevel
 */
WebInspector.ConsoleCommand = function(message, nestingLevel)
{
    WebInspector.ConsoleViewMessage.call(this, message, null, nestingLevel);
}

WebInspector.ConsoleCommand.prototype = {
    clearHighlight: function()
    {
        var highlightedMessage = this._formattedCommand;
        delete this._formattedCommand;
        this._formatCommand();
        this._element.replaceChild(this._formattedCommand, highlightedMessage);
    },

    /**
     * @param {!RegExp} regexObject
     */
    highlightSearchResults: function(regexObject)
    {
        regexObject.lastIndex = 0;
        var match = regexObject.exec(this.text);
        var matchRanges = [];
        while (match) {
            matchRanges.push(new WebInspector.SourceRange(match.index, match[0].length));
            match = regexObject.exec(this.text);
        }
        WebInspector.highlightSearchResults(this._formattedCommand, matchRanges);
        this._element.scrollIntoViewIfNeeded();
    },

    /**
     * @param {!RegExp} regexObject
     * @return {boolean}
     */
    matchesRegex: function(regexObject)
    {
        regexObject.lastIndex = 0;
        return regexObject.test(this.text);
    },

    /**
     * @return {!Element}
     */
    contentElement: function()
    {
        if (!this._element) {
            this._element = document.createElementWithClass("div", "console-user-command");
            this._element.message = this;

            this._formatCommand();
            this._element.appendChild(this._formattedCommand);
        }
        return this._element;
    },

    _formatCommand: function()
    {
        this._formattedCommand = document.createElementWithClass("span", "console-message-text source-code");
        this._formattedCommand.textContent = this.text;
    },

    __proto__: WebInspector.ConsoleViewMessage.prototype
}

/**
 * @constructor
 * @extends {WebInspector.ConsoleViewMessage}
 * @param {!WebInspector.ConsoleMessage} message
 * @param {!WebInspector.Linkifier} linkifier
 * @param {number} nestingLevel
 */
WebInspector.ConsoleCommandResult = function(message, linkifier, nestingLevel)
{
    WebInspector.ConsoleViewMessage.call(this, message, linkifier, nestingLevel);
}

WebInspector.ConsoleCommandResult.prototype = {
    /**
     * @override
     * @param {!WebInspector.RemoteObject} array
     * @return {boolean}
     */
    useArrayPreviewInFormatter: function(array)
    {
        return false;
    },

    /**
     * @return {!Element}
     */
    contentElement: function()
    {
        var element = WebInspector.ConsoleViewMessage.prototype.contentElement.call(this);
        element.classList.add("console-user-command-result");
        return element;
    },

    __proto__: WebInspector.ConsoleViewMessage.prototype
}

/**
 * @constructor
 * @param {?WebInspector.ConsoleGroup} parentGroup
 * @param {?WebInspector.ConsoleViewMessage} groupMessage
 */
WebInspector.ConsoleGroup = function(parentGroup, groupMessage)
{
    this._parentGroup = parentGroup;
    this._nestingLevel = parentGroup ? parentGroup.nestingLevel() + 1 : 0;
    this._messagesHidden = groupMessage && groupMessage.collapsed() || this._parentGroup && this._parentGroup.messagesHidden();
}

/**
 * @return {!WebInspector.ConsoleGroup}
 */
WebInspector.ConsoleGroup.createTopGroup = function()
{
    return new WebInspector.ConsoleGroup(null, null);
}

WebInspector.ConsoleGroup.prototype = {
    /**
     * @return {boolean}
     */
    messagesHidden: function()
    {
        return this._messagesHidden;
    },

    /**
     * @return {number}
     */
    nestingLevel: function()
    {
        return this._nestingLevel;
    },

    /**
     * @return {?WebInspector.ConsoleGroup}
     */
    parentGroup: function()
    {
        return this._parentGroup || this;
    },
}

/**
 * @constructor
 * @implements {WebInspector.ActionDelegate}
 */
WebInspector.ConsoleView.ShowConsoleActionDelegate = function()
{
}

WebInspector.ConsoleView.ShowConsoleActionDelegate.prototype = {
    /**
     * @return {boolean}
     */
    handleAction: function()
    {
        WebInspector.console.show();
        return true;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Waffle.Windows.AuthProvider
{
    /// <summary>
    /// A Windows auth identity.
    /// </summary>
    public struct WindowsAuthIdentity
    {
        /// <summary>
        /// A string that contains the user name.
        /// </summary>
        public string Username;
        /// <summary>
        /// A string that contains the domain name or the workgroup name.
        /// </summary>
        public string Domain;
        /// <summary>
        /// A string that contains the password of the user in the domain or workgroup.
        /// </summary>
        public string Password;
    }
}


text:
/**
 * Provides abstract classes for common code
 */
package oshi.software.common;


text:
package com.gizrak.ebook;

import com.gizrak.ebook.constant.Extras;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

/**
 * Creates shortcut for each activity.

 *
 *

 *
CLASS_NAME: Activity for shortcut executed.

 *
ID: _id from Database.

 *
TITLE: Shortcut Name.

 *
COVER_IMG: Shortcut Image.

 *

 *
 * @author gizrak
 */
public class ShortcutActivity extends Activity {

	private static final String ACTION_SHORTCUT = "android.intent.action.CREATE_SHORTCUT";
	private static final String EXTRA_KEY = "com.gizrak.ebook.ShortcutActivity";

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

		final Intent i = getIntent();
		String className = i.getStringExtra(Extras.CLASS_NAME);
		long id = i.getLongExtra(Extras.ID, 1);
		String type = i.getStringExtra(Extras.TYPE);
		String title = i.getStringExtra(Extras.TITLE);
		String author = i.getStringExtra(Extras.AUTHOR);
		String path = i.getStringExtra(Extras.PATH);
		Bitmap img = (Bitmap) i.getParcelableExtra(Extras.IMAGE);

		// First, set up the shortcut intent.
		// For this example, we simply create an intent that
		// will bring us directly back to this activity.
		// A more typical implementation would use a
		// data Uri in order to display a more specific result, or a custom
		// action in order to
		// launch a specific operation.
		Intent shortcutIntent = new Intent(ACTION_SHORTCUT);
		shortcutIntent.setClassName("com.gizrak.ebook", className);
		shortcutIntent.putExtra(EXTRA_KEY, "gizrak provides this shortcut");
		shortcutIntent.putExtra(Extras.ID, id);
		shortcutIntent.putExtra(Extras.TYPE, type);
		shortcutIntent.putExtra(Extras.TITLE, title);
		shortcutIntent.putExtra(Extras.AUTHOR, author);
		shortcutIntent.putExtra(Extras.PATH, path);

		// Then, set up the container intent (the response to the caller)
		Intent intent = new Intent();
		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, img);

		// Now, return the result to the launcher
		intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		sendBroadcast(intent);

		finish();
	}
}


text:
{% extends 'missionlogger/base.html' %}

{% block title %}{{ mission.title }} details {% endblock %}

{% block body %}

Mission: {{ mission.title }}

Vessel: {{ mission.vessel }}

Status: {{ mission.get_status_display }}

<textarea disabled class="materialize-textarea black-text">{{ mission.details }}</textarea>

                  Back

{% endblock %}


text:
package org.hisp.dhis.analytics.event.data;

import com.google.common.collect.Sets;
import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.analytics.AggregationType;
import org.hisp.dhis.analytics.AnalyticsAggregationType;
import org.hisp.dhis.analytics.event.EventDataQueryService;
import org.hisp.dhis.analytics.event.EventQueryParams;
import org.hisp.dhis.common.AnalyticsType;
import org.hisp.dhis.common.DimensionType;
import org.hisp.dhis.common.DimensionalItemObject;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.DimensionalObjectUtils;
import org.hisp.dhis.common.EventDataQueryRequest;
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.common.GridHeader;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.eventchart.EventChart;
import org.hisp.dhis.legend.Legend;
import org.hisp.dhis.legend.LegendSet;
import org.hisp.dhis.legend.LegendSetService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStageService;
import org.hisp.dhis.system.grid.ListGrid;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.trackedentity.TrackedEntityAttributeDimension;
import org.hisp.dhis.trackedentity.TrackedEntityAttributeService;
import org.hisp.dhis.trackedentity.TrackedEntityDataElementDimension;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

/**
 * @author Lars Helge Overland
 */
public class EventDataQueryServiceTest
    extends DhisSpringTest
{
    private Program prA;
    private ProgramStage psA;

    private Period peA;
    private Period peB;

    private OrganisationUnit ouA;
    private OrganisationUnit ouB;

    private DataElement deA;
    private DataElement deB;
    private DataElement deC;

    private TrackedEntityAttribute atA;
    private TrackedEntityAttribute atB;

    private LegendSet legendSetA;

    private Legend legendA;
    private Legend legendB;

    @Autowired
    private EventDataQueryService dataQueryService;

    @Autowired
    private ProgramService programService;

    @Autowired
    private ProgramStageService programStageService;

    @Autowired
    private DataElementService dataElementService;

    @Autowired
    private OrganisationUnitService organisationUnitService;

    @Autowired
    private TrackedEntityAttributeService attributeService;

    @Autowired
    private LegendSetService legendSetService;

    @Override
    public void setUpTest()
    {
        peA = PeriodType.getPeriodFromIsoString( "201401" );
        peB = PeriodType.getPeriodFromIsoString( "201402" );

        ouA = createOrganisationUnit( 'A' );
        ouB = createOrganisationUnit( 'B' );

        organisationUnitService.addOrganisationUnit( ouA );
        organisationUnitService.addOrganisationUnit( ouB );

        deA = createDataElement( 'A' );
        deB = createDataElement( 'B' );
        deC = createDataElement( 'C' );
        deC.setValueType( ValueType.COORDINATE );

        dataElementService.addDataElement( deA );
        dataElementService.addDataElement( deB );
        dataElementService.addDataElement( deC );

        atA = createTrackedEntityAttribute( 'A' );
        atB = createTrackedEntityAttribute( 'B' );

        attributeService.addTrackedEntityAttribute( atA );
        attributeService.addTrackedEntityAttribute( atB );

        prA = createProgram( 'A', null, Sets.newHashSet( atA, atB ), Sets.newHashSet( ouA, ouB ), null );
        programService.addProgram( prA );

        psA = createProgramStage( 'A', 0 );
        psA.addDataElement( deA, 0 );
        psA.addDataElement( deB, 1 );
        prA.getProgramStages().add( psA );

        programStageService.saveProgramStage( psA );

        legendA = createLegend( 'A', 0d, 10d );
        legendB = createLegend( 'B', 10d, 20d );

        legendSetA = createLegendSet( 'A' );

        legendSetA.getLegends().add( legendA );
        legendSetA.getLegends().add( legendB );

        legendSetService.addLegendSet( legendSetA );
    }

    @Test
    public void testGetFromUrlA()
    {
        Set<String> dimensionParams = new HashSet<>();
        dimensionParams.add( "ou:" + ouA.getUid() + ";" + ouB.getId() );
        dimensionParams.add( atA.getUid() + ":LE:5" );

        Set<String> filterParams = new HashSet<>();
        filterParams.add( "pe:201401;201402" );

        EventDataQueryRequest request = EventDataQueryRequest.newBuilder().program( prA.getUid() )
            .dimension( dimensionParams ).filter( filterParams ).build();

        EventQueryParams params = dataQueryService.getFromRequest( request );

        assertEquals( prA, params.getProgram() );
        assertEquals( 1, params.getOrganisationUnits().size() );
        assertEquals( 1, params.getItems().size() );
        assertEquals( 2, params.getFilterPeriods().size() );
    }

    @Test
    public void testGetFromUrlB()
    {
        Set<String> dimensionParams = new HashSet<>();
        dimensionParams.add( "ou:" + ouA.getUid() + ";" + ouB.getId() );
        dimensionParams.add( atA.getUid() + ":LE:5" );

        Set<String> filterParams = new HashSet<>();
        filterParams.add( "pe:201401" );

        EventDataQueryRequest request = EventDataQueryRequest.newBuilder().program( prA.getUid() )
            .dimension( dimensionParams ).filter( filterParams ).value(  deA.getUid() ).aggregationType( AggregationType.AVERAGE ).build();

        EventQueryParams params = dataQueryService.getFromRequest( request );

        assertEquals( prA, params.getProgram() );
        assertEquals( 1, params.getOrganisationUnits().size() );
        assertEquals( 1, params.getItems().size() );
        assertEquals( 1, params.getFilterPeriods().size() );
        assertEquals( deA, params.getValue() );
        assertEquals( AnalyticsAggregationType.AVERAGE, params.getAggregationType() );
    }

    @Test
    public void testGetFromAnalyticalObjectA()
    {
        EventChart eventChart = new EventChart();
        eventChart.setAutoFields();
        eventChart.setProgram( prA );

        eventChart.getColumnDimensions().add( atA.getUid() );
        eventChart.getRowDimensions().add( DimensionalObject.ORGUNIT_DIM_ID );
        eventChart.getFilterDimensions().add( DimensionalObject.PERIOD_DIM_ID );

        eventChart.getAttributeDimensions().add( new TrackedEntityAttributeDimension( atA, null, "LE:5" ) );
        eventChart.getPeriods().add( peA );
        eventChart.getPeriods().add( peB );
        eventChart.getOrganisationUnits().add( ouA );
        eventChart.getOrganisationUnits().add( ouB );

        EventQueryParams params = dataQueryService.getFromAnalyticalObject( eventChart );

        assertNotNull( params );
        assertEquals( 1, params.getItems().size() );
        assertEquals( 2, params.getOrganisationUnits().size() );
        assertEquals( 2, params.getFilterPeriods().size() );
    }

    @Test
    public void testGetFromAnalyticalObjectB()
    {
        EventChart eventChart = new EventChart();
        eventChart.setAutoFields();
        eventChart.setProgram( prA );

        eventChart.getColumnDimensions().add( atA.getUid() );
        eventChart.getColumnDimensions().add( deA.getUid() );
        eventChart.getRowDimensions().add( DimensionalObject.PERIOD_DIM_ID );
        eventChart.getFilterDimensions().add( DimensionalObject.ORGUNIT_DIM_ID );

        eventChart.getAttributeDimensions().add( new TrackedEntityAttributeDimension( atA, null, "LE:5" ) );
        eventChart.getDataElementDimensions().add( new TrackedEntityDataElementDimension( deA, null, "GE:100" ) );
        eventChart.getPeriods().add( peA );
        eventChart.getPeriods().add( peB );
        eventChart.getOrganisationUnits().add( ouA );
        eventChart.getOrganisationUnits().add( ouB );

        EventQueryParams params = dataQueryService.getFromAnalyticalObject( eventChart );

        assertNotNull( params );
        assertEquals( 2, params.getItems().size() );
        assertEquals( 2, params.getPeriods().size() );
        assertEquals( 2, params.getFilterOrganisationUnits().size() );
    }

    @Test
    public void testGetFromAnalyticalObjectC()
    {
        EventChart eventChart = new EventChart();
        eventChart.setAutoFields();
        eventChart.setProgram( prA );

        eventChart.getColumnDimensions().add( deA.getUid() );
        eventChart.getColumnDimensions().add( atA.getUid() );
        eventChart.getRowDimensions().add( DimensionalObject.ORGUNIT_DIM_ID );
        eventChart.getFilterDimensions().add( DimensionalObject.PERIOD_DIM_ID );

        eventChart.getDataElementDimensions().add( new TrackedEntityDataElementDimension( deA, null, "GT:2000" ) );
        eventChart.getAttributeDimensions().add( new TrackedEntityAttributeDimension( atA, null, "LE:5" ) );
        eventChart.getPeriods().add( peA );
        eventChart.getPeriods().add( peB );
        eventChart.getOrganisationUnits().add( ouA );

        EventQueryParams params = dataQueryService.getFromAnalyticalObject( eventChart );

        assertNotNull( params );
        assertEquals( 2, params.getItems().size() );
        assertEquals( 1, params.getOrganisationUnits().size() );
        assertEquals( 2, params.getFilterPeriods().size() );
    }

    @Test
    public void testSetItemsForDimensionFilters()
    {
        TrackedEntityAttribute tea = new TrackedEntityAttribute();
        tea.setAutoFields();

        TrackedEntityAttributeDimension tead = new TrackedEntityAttributeDimension( tea, null, "EQ:2" );

        EventChart eventChart = new EventChart();
        eventChart.setAutoFields();
        eventChart.getColumnDimensions().add( tea.getUid() );
        eventChart.getAttributeDimensions().add( tead );

        Grid grid = new ListGrid();
        grid.addHeader( new GridHeader( tea.getUid(), tea.getName() ) );
        grid.addRow().addValue( "1" );
        grid.addRow().addValue( "2" );
        grid.addRow().addValue( "3" );
        grid.addRow().addValue( null );

        eventChart.populateAnalyticalProperties();

        DimensionalObject dim = eventChart.getColumns().get( 0 );

        DimensionalObjectUtils.setDimensionItemsForFilters( dim, grid, true );

        assertNotNull( dim );
        assertEquals( DimensionType.PROGRAM_ATTRIBUTE, dim.getDimensionType() );
        assertEquals( AnalyticsType.EVENT, dim.getAnalyticsType() );
        assertEquals( tead.getFilter(), dim.getFilter() );

        List<DimensionalItemObject> items = dim.getItems();
        assertEquals( 4, items.size() );
        assertNotNull( items.get( 0 ).getUid() );
        assertNotNull( items.get( 0 ).getName() );
        assertNotNull( items.get( 0 ).getCode() );
        assertNotNull( items.get( 0 ).getShortName() );
    }

    @Test
    public void testGetFromUrlLegendSet()
    {
        Set<String> dimensionParams = new HashSet<>();
        dimensionParams.add( deA.getUid() + "-" + legendSetA.getUid() + ":IN:" + legendA.getUid() + ";" + legendB.getUid() );

        Set<String> filterParams = new HashSet<>();
        filterParams.add( "pe:201401;201402" );
        filterParams.add( atA.getUid() + ":LE:5" );

        EventDataQueryRequest request = EventDataQueryRequest.newBuilder().program( prA.getUid() )
            .dimension( dimensionParams ).filter( filterParams ).build();

        EventQueryParams params = dataQueryService.getFromRequest( request );

        assertEquals( prA, params.getProgram() );
        assertEquals( 1, params.getItems().size() );
        assertEquals( legendSetA, params.getItems().get( 0 ).getLegendSet() );
        assertEquals( 1, params.getItemFilters().size() );
        assertEquals( 2, params.getFilterPeriods().size() );
    }

    @Test
    public void testGetCoordinateField()
    {
        assertEquals( "geom", dataQueryService.getCoordinateField( EventQueryParams.EVENT_COORDINATE_FIELD ) );
        assertEquals( "geom", dataQueryService.getCoordinateField( null ) );
        assertEquals( deC.getUid(), dataQueryService.getCoordinateField( deC.getUid() ) );
    }

    @Test( expected = IllegalQueryException.class )
    public void testGetInvalidCoordinateFieldException()
    {
        dataQueryService.getCoordinateField( "someField" );
    }

    @Test( expected = IllegalQueryException.class )
    public void testGetNonCoordinateValueTypeCoordinateFieldException()
    {
        dataQueryService.getCoordinateField( deA.getUid() );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="exo_controls_previous_description">मागील ट्रॅक</string>
  <string name="exo_controls_next_description">पुढील ट्रॅक</string>
  <string name="exo_controls_pause_description">विराम</string>
  <string name="exo_controls_play_description">प्‍ले करा</string>
  <string name="exo_controls_stop_description">थांबा</string>
  <string name="exo_controls_rewind_description">रीवाइंड करा</string>
  <string name="exo_controls_fastforward_description">फास्ट फॉरवर्ड करा</string>
  <string name="exo_controls_repeat_off_description">रीपीट करू नका</string>
  <string name="exo_controls_repeat_one_description">एक रीपीट करा</string>
  <string name="exo_controls_repeat_all_description">सर्व रीपीट करा</string>
  <string name="exo_controls_shuffle_description">शफल करा</string>
  <string name="exo_controls_fullscreen_description">फुल स्क्रीन मोड</string>
  <string name="exo_controls_vr_description">VR मोड</string>
  <string name="exo_download_description">डाउनलोड करा</string>
  <string name="exo_download_notification_channel_name">डाउनलोड</string>
  <string name="exo_download_downloading">डाउनलोड होत आहे</string>
  <string name="exo_download_completed">डाउनलोड पूर्ण झाले</string>
  <string name="exo_download_failed">डाउनलोड अयशस्वी झाले</string>
  <string name="exo_download_removing">डाउनलोड काढून टाकत आहे</string>
  <string name="exo_track_selection_title_video">व्हिडिओ</string>
  <string name="exo_track_selection_title_audio">ऑडिओ</string>
  <string name="exo_track_selection_title_text">मजकूर</string>
  <string name="exo_track_selection_none">काहीही नाही</string>
  <string name="exo_track_selection_auto">आपोआप</string>
  <string name="exo_track_unknown">अज्ञात</string>
  <string name="exo_track_resolution">%1$d × %2$d</string>
  <string name="exo_track_mono">मोनो</string>
  <string name="exo_track_stereo">स्टिरिओ</string>
  <string name="exo_track_surround">सराउंड साउंड</string>
  <string name="exo_track_surround_5_point_1">५.१ सराउंड साउंड</string>
  <string name="exo_track_surround_7_point_1">७.१ सराउंड साउंड</string>
  <string name="exo_track_role_alternate">पर्यायी</string>
  <string name="exo_track_role_supplementary">साहाय्यक</string>
  <string name="exo_track_role_commentary">समालोचन</string>
  <string name="exo_track_role_closed_captions">सबटायटल</string>
  <string name="exo_track_bitrate">%1$.2f Mbps</string>
  <string name="exo_item_list">%1$s, %2$s</string>
</resources>