text:
package com.edmodo.cropper.util;

import android.graphics.PointF;
import android.support.annotation.NonNull;

import com.edmodo.cropper.cropwindow.handle.Handle;

/**
 * Utility class to perform basic operations with Handles.
 */
public class HandleUtil {

    // Public Methods //////////////////////////////////////////////////////////////////////////////

    /**
     * Determines which, if any, of the handles are pressed given the touch coordinates, the
     * bounding box, and the touch radius.
     *
     * @param x            the x-coordinate of the touch point
     * @param y            the y-coordinate of the touch point
     * @param left         the x-coordinate of the left bound
     * @param top          the y-coordinate of the top bound
     * @param right        the x-coordinate of the right bound
     * @param bottom       the y-coordinate of the bottom bound
     * @param targetRadius the target radius in pixels
     *
     * @return the Handle that was pressed; null if no Handle was pressed
     */
    public static Handle getPressedHandle(float x,
                                          float y,
                                          float left,
                                          float top,
                                          float right,
                                          float bottom,
                                          float targetRadius) {

        // Find the closest corner handle to the touch point.
        // If the touch point is in the target zone of this closest handle, then this is the pressed handle.
        // Else, check if any of the edges are in the target zone of the touch point.
        // Else, check if the touch point is within the crop window bounds; if so, then choose the center handle.

        Handle closestHandle = null;
        float closestDistance = Float.POSITIVE_INFINITY;

        final float distanceToTopLeft = MathUtil.calculateDistance(x, y, left, top);
        if (distanceToTopLeft < closestDistance) {
            closestDistance = distanceToTopLeft;
            closestHandle = Handle.TOP_LEFT;
        }

        final float distanceToTopRight = MathUtil.calculateDistance(x, y, right, top);
        if (distanceToTopRight < closestDistance) {
            closestDistance = distanceToTopRight;
            closestHandle = Handle.TOP_RIGHT;
        }

        final float distanceToBottomLeft = MathUtil.calculateDistance(x, y, left, bottom);
        if (distanceToBottomLeft < closestDistance) {
            closestDistance = distanceToBottomLeft;
            closestHandle = Handle.BOTTOM_LEFT;
        }

        final float distanceToBottomRight = MathUtil.calculateDistance(x, y, right, bottom);
        if (distanceToBottomRight < closestDistance) {
            closestDistance = distanceToBottomRight;
            closestHandle = Handle.BOTTOM_RIGHT;
        }

        if (closestDistance <= targetRadius) {
            return closestHandle;
        }

        // If we get to this point, none of the corner handles were in the touch target zone, so then we check the edges.
        if (HandleUtil.isInHorizontalTargetZone(x, y, left, right, top, targetRadius)) {
            return Handle.TOP;
        } else if (HandleUtil.isInHorizontalTargetZone(x, y, left, right, bottom, targetRadius)) {
            return Handle.BOTTOM;
        } else if (HandleUtil.isInVerticalTargetZone(x, y, left, top, bottom, targetRadius)) {
            return Handle.LEFT;
        } else if (HandleUtil.isInVerticalTargetZone(x, y, right, top, bottom, targetRadius)) {
            return Handle.RIGHT;
        }

        // If we get to this point, none of the corners or edges are in the touch target zone.
        // Check to see if the touch point is within the bounds of the crop window. If so, choose the center handle.
        if (isWithinBounds(x, y, left, top, right, bottom)) {
            return Handle.CENTER;
        }

        return null;
    }

    /**
     * Calculates the offset of the touch point from the precise location of the specified handle.
     * <p/>
     * The offset will be returned in the 'touchOffsetOutput' parameter; the x-offset will be the
     * first value and the y-offset will be the second value.
     */
    public static void getOffset(@NonNull Handle handle,
                                 float x,
                                 float y,
                                 float left,
                                 float top,
                                 float right,
                                 float bottom,
                                 @NonNull PointF touchOffsetOutput) {

        float touchOffsetX = 0;
        float touchOffsetY = 0;

        // Calculate the offset from the appropriate handle.
        switch (handle) {

            case TOP_LEFT:
                touchOffsetX = left - x;
                touchOffsetY = top - y;
                break;
            case TOP_RIGHT:
                touchOffsetX = right - x;
                touchOffsetY = top - y;
                break;
            case BOTTOM_LEFT:
                touchOffsetX = left - x;
                touchOffsetY = bottom - y;
                break;
            case BOTTOM_RIGHT:
                touchOffsetX = right - x;
                touchOffsetY = bottom - y;
                break;
            case LEFT:
                touchOffsetX = left - x;
                touchOffsetY = 0;
                break;
            case TOP:
                touchOffsetX = 0;
                touchOffsetY = top - y;
                break;
            case RIGHT:
                touchOffsetX = right - x;
                touchOffsetY = 0;
                break;
            case BOTTOM:
                touchOffsetX = 0;
                touchOffsetY = bottom - y;
                break;
            case CENTER:
                final float centerX = (right + left) / 2;
                final float centerY = (top + bottom) / 2;
                touchOffsetX = centerX - x;
                touchOffsetY = centerY - y;
                break;
        }

        touchOffsetOutput.x = touchOffsetX;
        touchOffsetOutput.y = touchOffsetY;
    }

    // Private Methods /////////////////////////////////////////////////////////////////////////////

    /**
     * Determines if the specified coordinate is in the target touch zone for a horizontal bar
     * handle.
     *
     * @param x            the x-coordinate of the touch point
     * @param y            the y-coordinate of the touch point
     * @param handleXStart the left x-coordinate of the horizontal bar handle
     * @param handleXEnd   the right x-coordinate of the horizontal bar handle
     * @param handleY      the y-coordinate of the horizontal bar handle
     * @param targetRadius the target radius in pixels
     *
     * @return true if the touch point is in the target touch zone; false otherwise
     */
    private static boolean isInHorizontalTargetZone(float x,
                                                    float y,
                                                    float handleXStart,
                                                    float handleXEnd,
                                                    float handleY,
                                                    float targetRadius) {

        return (x > handleXStart && x < handleXEnd && Math.abs(y - handleY) <= targetRadius);
    }

    /**
     * Determines if the specified coordinate is in the target touch zone for a vertical bar
     * handle.
     *
     * @param x            the x-coordinate of the touch point
     * @param y            the y-coordinate of the touch point
     * @param handleX      the x-coordinate of the vertical bar handle
     * @param handleYStart the top y-coordinate of the vertical bar handle
     * @param handleYEnd   the bottom y-coordinate of the vertical bar handle
     * @param targetRadius the target radius in pixels
     *
     * @return true if the touch point is in the target touch zone; false otherwise
     */
    private static boolean isInVerticalTargetZone(float x,
                                                  float y,
                                                  float handleX,
                                                  float handleYStart,
                                                  float handleYEnd,
                                                  float targetRadius) {

        return (Math.abs(x - handleX) <= targetRadius && y > handleYStart && y < handleYEnd);
    }

    private static boolean isWithinBounds(float x, float y, float left, float top, float right, float bottom) {
        return x >= left && x <= right && y >= top && y <= bottom;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/text_and_progressbar"
	android:orientation="horizontal"
	android:gravity="center"
	android:layout_width="fill_parent"
	android:layout_height="?attr/gdItemViewPreferredHeight"
	android:minHeight="?attr/gdItemViewPreferredHeight">

	<TextView android:id="@+id/text_and_progressbar_text"
		android:text="Progressbar text"
		android:onClick="onTextAndProgressBarClick"
		android:clickable="true"
		android:layout_width="wrap_content"
		android:layout_height="fill_parent"
		android:gravity="center"
		android:visibility="gone"/>

	<ProgressBar
           android:id="@+id/text_and_progressbar_progressbar"
           android:indeterminate="true"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_centerInParent="true"
           style="?android:attr/progressBarStyleSmall"
           />
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
package ru.otus.l71.creational.prototype;

/**
 * Created by tully.
 * <p>
 * Prototype
 */
public interface Prototype extends Cloneable {
    Prototype clone();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->

<phpdoc:classref xml:id="class.zmqsocket" xmlns:phpdoc="http://php.net/ns/phpdoc" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude">

 <title>The ZMQSocket class</title>
 <titleabbrev>ZMQSocket</titleabbrev>

 <partintro>

<!-- {{{ ZMQSocket intro -->
  <section xml:id="zmqsocket.intro">
   &reftitle.intro;
   <para>

   </para>
  </section>
<!-- }}} -->

  <section xml:id="zmqsocket.synopsis">
   &reftitle.classsynopsis;

<!-- {{{ Synopsis -->
   <classsynopsis>
    <ooclass><classname>ZMQSocket</classname></ooclass>

<!-- {{{ Class synopsis -->
    <classsynopsisinfo>
     <ooclass>
      <classname>ZMQSocket</classname>
     </ooclass>
    </classsynopsisinfo>
<!-- }}} -->

    <classsynopsisinfo role="comment">Methods</classsynopsisinfo>
    <xi:include xpointer="xmlns(db=http://docbook.org/ns/docbook) xpointer(id('class.zmqsocket')/db:refentry/db:refsect1[@role='description']/descendant::db:methodsynopsis[1])" />
   </classsynopsis>
<!-- }}} -->

  </section>

 </partintro>

 &reference.zmq.entities.zmqsocket;

</phpdoc:classref>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
using System;
using System.Collections.Generic;
using Milo.Core.Interfaces;

namespace Milo.Core
{
    /// <summary>
    /// Represents a Page
    /// </summary>
    [Serializable]
    public class PageData : IPageData
    {
        /// <summary>
        /// The languages for this page.
        /// </summary>
        private readonly List<string> _languages;

        /// <summary>
        /// Gets the parent page.
        /// </summary>
        /// <value>
        /// The parent page.
        /// </value>
        public PageData ParentPage
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Gets or sets the name of the page.
        /// </summary>
        /// <value>
        /// The name of the page.
        /// </value>
        public string PageName { get; set; }

        /// <summary>
        /// Gets or sets the name of the page type.
        /// </summary>
        /// <value>
        /// The name of the page type.
        /// </value>
        public string PageTypeName { get; set; }

        /// <summary>
        /// Get or sets the slug of the page.
        /// </summary>
        /// <value>
        /// The slug of the page.
        /// </value>
        public string PageSlug { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the page is in edit mode.
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is edit mode]; otherwise, <c>false</c>.
        /// </value>
        public bool IsEditMode { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="Milo.Core.PageData"/> class.
        /// </summary>
        public PageData()
        {
            _languages = new List<string>();
        }

        /// <summary>
        /// Gets the page languages.
        /// </summary>
        /// <value>
        /// The page languages.
        /// </value>
        public virtual List<string> PageLanguages
        {
            get
            {
                return _languages;
            }
        }

        /// <summary>
        /// Gets children pages.
        /// </summary>
        /// <returns>The children pages.</returns>
        public PageDataCollection GetChildren()
        {
            return new PageDataCollection();
        }

        /// <summary>
        /// Gets the property.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public IProperty GetProperty(string key)
        {
            return null;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>HBase 0.98.6-hadoop2 Reference Package org.apache.hadoop.hbase.types</title>
		<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="style" />

        	org.apache.hadoop.hbase.types

Classes

            	Pojo1

            	Pojo2

            	SampleUnion1

            	SpecializedPojo1Type1

            	SpecializedPojo2Type1

            	TestFixedLengthWrapper

            	TestOrderedBlob

            	TestOrderedBlobVar

            	TestOrderedString

            	TestPBCell

            	TestRawString

            	TestStruct

            	TestStructNullExtension

            	TestTerminatedWrapper

            	TestUnion2


text:
package org.jclouds.rest;

import org.jclouds.apis.ApiMetadata;

import com.google.common.annotations.Beta;

/**
 *
 * @since 1.6
 * @see ConfiguresHttpApi
 */
@Beta
public interface HttpApiMetadata<A> extends ApiMetadata {

   public interface Builder<A, T extends Builder<A, T>> extends ApiMetadata.Builder<T> {

      /**
       * @see ApiMetadata#getApi()
       */
      T api(Class<A> api);
   }

   /**
    *
    * @return the type of the java api which has http annotations on its methods.
    */
   Class<A> getApi();
}


text:
<?php

use Doctrine\ORM\Mapping\ClassMetadataInfo;

$metadata->setPrimaryTable(array(
   'name' => 'company_person',
));

$metadata->mapField(array (
    'id'        => true,
    'fieldName' => 'id',
    'type'      => 'integer',
));

$metadata->mapField(array (
    'fieldName' => 'zip',
    'length'    => 50,
));

$metadata->mapField(array (
    'fieldName' => 'city',
    'length'    => 50,
));

$metadata->mapOneToOne(array(
    'fieldName'     => 'user',
    'targetEntity'  => 'CmsUser',
    'joinColumns'   => array(array('referencedColumnName' => 'id'))
));

$metadata->addNamedNativeQuery(array (
    'name'              => 'find-all',
    'query'             => 'SELECT id, country, city FROM cms_addresses',
    'resultSetMapping'  => 'mapping-find-all',
));

$metadata->addNamedNativeQuery(array (
    'name'              => 'find-by-id',
    'query'             => 'SELECT * FROM cms_addresses WHERE id = ?',
    'resultClass'       => 'Doctrine\\Tests\\Models\\CMS\\CmsAddress',
));

$metadata->addNamedNativeQuery(array (
    'name'              => 'count',
    'query'             => 'SELECT COUNT(*) AS count FROM cms_addresses',
    'resultSetMapping'  => 'mapping-count',
));

$metadata->addSqlResultSetMapping(array (
    'name'      => 'mapping-find-all',
    'columns'   => array(),
    'entities'  => array ( array (
        'fields' => array (
          array (
            'name'      => 'id',
            'column'    => 'id',
          ),
          array (
            'name'      => 'city',
            'column'    => 'city',
          ),
          array (
            'name'      => 'country',
            'column'    => 'country',
          ),
        ),
        'entityClass' => 'Doctrine\Tests\Models\CMS\CmsAddress',
      ),
    ),
));

$metadata->addSqlResultSetMapping(array (
    'name'      => 'mapping-without-fields',
    'columns'   => array(),
    'entities'  => array(array (
        'entityClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsAddress',
        'fields' => array()
      )
    )
));

$metadata->addSqlResultSetMapping(array (
    'name' => 'mapping-count',
    'columns' =>array (
        array (
            'name' => 'count',
        ),
    )
));

$metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CmsAddressListener', 'postPersist');
$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CmsAddressListener', 'prePersist');

$metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CmsAddressListener', 'postUpdate');
$metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CmsAddressListener', 'preUpdate');

$metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CmsAddressListener', 'postRemove');
$metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CmsAddressListener', 'preRemove');

$metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CmsAddressListener', 'preFlush');
$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CmsAddressListener', 'postLoad');


text:
package com.google.apps.easyconnect.easyrp.client.basic.logic.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import com.google.apps.easyconnect.easyrp.client.basic.logic.GitNode;
import com.google.apps.easyconnect.easyrp.client.basic.logic.GitRule;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;

public class GitDecisionNode extends AbstractGitNode {
  private static final Logger log = Logger.getLogger(GitDecisionNode.class.getName());
  private static final String DEFAULT_CHILD_KEY = "DEFAULT";

  private Object evaluatorObject;
  private Method evaluator;
  private Map<String, GitNode> children = Maps.newHashMap();

  public GitDecisionNode(String id, Class<?> requestClass, Object evaluatorObject,
      String evaluatorMethod) {
    super(id, false, requestClass);
    Preconditions.checkNotNull(evaluatorObject);
    Preconditions.checkNotNull(evaluatorMethod);
    this.evaluator = ClassUtil.getMethod(evaluatorObject.getClass(), evaluatorMethod, requestClass);
    if (this.evaluator == null) {
      String msg = "Illegal Tree Statues: Failed to find [" + evaluatorMethod + "] on class ["
          + evaluatorObject.getClass().getSimpleName() + "].";
      log.severe(msg);
      throw new IllegalStateException(msg);
    }
    this.evaluatorObject = evaluatorObject;
  }

  public static String formatKey(String key) {
    Preconditions.checkNotNull(key);
    if (DEFAULT_CHILD_KEY.equalsIgnoreCase(key)) {
      return DEFAULT_CHILD_KEY;
    } else {
      return key.toLowerCase();
    }
  }

  public void addChild(String key, GitNode node) {
    Preconditions.checkNotNull(key);
    Preconditions.checkNotNull(node);
    children.put(formatKey(key), node);
  }

  public boolean hasChild(String key) {
    return key != null && children.containsKey(formatKey(key));
  }

  public void addDefaultChild(GitNode node) {
    children.put(DEFAULT_CHILD_KEY, node);
  }

  public boolean hasChildren() {
    return !this.children.isEmpty();
  }

  public Iterator<GitNode> children() {
    return children.values().iterator();
  }

  @VisibleForTesting
  GitNode findChild(Object request) {
    String key = null;
    GitNode child = null;
    try {
      key = (String) evaluator.invoke(evaluatorObject, request);
    } catch (IllegalArgumentException e) {
      log.severe("Failed to evaluate node: " + e.getMessage());
    } catch (IllegalAccessException e) {
      log.severe("Failed to evaluate node: " + e.getMessage());
    } catch (InvocationTargetException e) {
      log.severe("Failed to evaluate node: " + e.getMessage());
    }
    if (key != null) {
      child = this.children.get(formatKey(key));
      if (child == null) {
        child = this.children.get(DEFAULT_CHILD_KEY);
      }
    } else {
      child = this.children.get(DEFAULT_CHILD_KEY);
    }
    if (child == null) {
      String msg = "Illegal Tree Statues: GitNode [" + this.evaluator.getName()
          + "] return an unknown value [" + key + "].";
      log.severe(msg);
      throw new IllegalStateException(msg);
    }
    return child;
  }

  @Override
  public void execute(Object request) {
    Preconditions.checkNotNull(request);
    if (!this.getRequestClass().isInstance(request)) {
      String msg = "Illegal Tree Statues: GitNode [" + this.evaluator.getName()
          + "] expects parameter type [" + this.getRequestClass().getName()
          + "], but actually it get [" + request.getClass().getName() + "].";
      log.severe(msg);
      throw new IllegalStateException(msg);
    }
    findChild(request).execute(request);
  }

  @Override
  public void appendToRuleList(List<GitRule> rules, String parentId, String parentValue) {
    rules.add(new GitRule(getId(), parentId, parentValue, false, this.evaluator.getName(), null));
    Iterator<String> it = this.children.keySet().iterator();
    while (it.hasNext()) {
      String key = it.next();
      children.get(key).appendToRuleList(rules, getId(), key);
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="gone"
                tools:showIn="@layout/ucrop_activity_photobox"
                tools:visibility="visible">

    <TextView
        android:id="@+id/text_view_rotate"
        style="@style/ucrop_TextViewWidgetText"
        android:text="100°"/>

    <com.yalantis.ucrop.view.widget.HorizontalProgressWheelView
        android:id="@+id/rotate_scroll_wheel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/text_view_rotate"
        android:layout_toEndOf="@+id/wrapper_reset_rotate"
        android:layout_toLeftOf="@+id/wrapper_rotate_by_angle"
        android:layout_toRightOf="@+id/wrapper_reset_rotate"
        android:layout_toStartOf="@+id/wrapper_rotate_by_angle"/>

    <FrameLayout
        android:id="@+id/wrapper_reset_rotate"
        style="@style/ucrop_WrapperRotateButton"
        android:layout_centerVertical="true">

        <ImageView
            style="@style/ucrop_ImageViewWidgetIcon"
            android:src="@drawable/ucrop_ic_reset"/>

    </FrameLayout>

    <FrameLayout
        android:id="@+id/wrapper_rotate_by_angle"
        style="@style/ucrop_WrapperRotateButton"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true">

        <ImageView
            style="@style/ucrop_ImageViewWidgetIcon"
            android:src="@drawable/ucrop_ic_angle"/>

    </FrameLayout>

</RelativeLayout>


text:
$(document).ready(function(){
    var winW = $(window).innerWidth();
	// Cache the Window object
    if ( winW > 1024 ) {

	$window = $(window);

   $('#services').each(function(){
     var $bgobj = $(this); // assigning the object

      $(window).scroll(function() {

		// Scroll the background at var speed
		// the yPos is a negative value because we're scrolling it UP!
		var yPos = -($window.scrollTop() / $bgobj.data('speed'))-400;

		// Put together our final background position
		var coords = '50% '+ yPos + 'px';

		// Move the background
		$bgobj.css({ backgroundPosition: coords });

});

 });

    $('#team').each(function(){
     var $bgobj = $(this); // assigning the object

      $(window).scroll(function() {

		// Scroll the background at var speed
		// the yPos is a negative value because we're scrolling it UP!
		var yPos = -($window.scrollTop() / $bgobj.data('speed'))-900;

		// Put together our final background position
		var coords = '50% '+ yPos + 'px';

		// Move the background
		$bgobj.css({ backgroundPosition: coords });

});

 });

    };

});


text:
IIIT CAS Overlay Template
=========================

IIIT's CAS Overlay Template

# Versions
```xml
<cas.version>4.2.x</cas.version>
```

# Requirements
* JDK 1.7+

# Configuration

The `etc` directory contains the configuration files that need to be copied to `/etc/cas`.

Current files are:

* `cas.properties`
* `log4j2.xml`

# Build

```bash
mvnw clean package
```

or

```bash
mvnw.bat clean package
```

# Deployment

## Embedded Jetty

* Create a Java keystore at `/etc/cas/jetty/thekeystore` with the password `changeit`.
* Import your CAS server certificate inside this keystore.

```bash
mvnw jetty:run-forked
```

CAS will be available at:

* `http://cas.server.name:8080/cas`
* `https://cas.server.name:8443/cas`

## External
Deploy resultant `target/cas.war` to a Servlet container of choice.


text:
package org.apache.xmlbeans.impl.values;

import org.apache.xmlbeans.XmlBoolean;

public class XmlBooleanImpl extends JavaBooleanHolder implements XmlBoolean
{
}


text:
class Room < ActiveRecord::Base
  include Redis::Objects

  belongs_to :community
  belongs_to :owner, class_name: "User", foreign_key: :owner_id
  has_many :players
  has_many :users, through: :players
  has_many :backgrounds
  belongs_to :active_background, class_name: "Background", foreign_key: :active_background_id

  value :stored_dice

  validates :name, :about, :community, :owner, :system_id, presence: true

  attr_reader :dice, :system

  after_initialize :initialize_system
  after_create :initialize_dice
  after_update :change_system, if: Proc.new { |a| a.system_id_changed? }

  def initialize_system
    set_system
    initialize_dice unless self.id.nil?         # new直後は実行しない
  end

  def change_system
    set_system
    @dice = @system.dice
    store_dice
  end

  def initialize_dice
    if stored_dice.nil?
      @dice = @system.dice
      store_dice
    else
      @dice = Marshal.load(stored_dice)
    end
  end

  def store_dice
    stored_dice = Marshal.dump(@dice)
  end

  def owned?(user)
    self.user_id == user.id
  end

  def has_member?(user)
    self.players.where(user_id: user.id).length > 0
  end

  def character(user)
    if player = self.players.find_by(user_id: user.id)
      player.character
    end
  end

  def play_role(user)
    if player = self.players.find_by(user_id: user.id)
      player.player_role
    end
  end

  scope :downloadable, ->(user_id) { where{created_at >= Date.today - 50.days}
      .joins(community: :users).where{users.id.eq user_id} } # 50日以内のみログダウンロード可

  private
  def set_system
    @system_tytle = System::TITLES.key(system_id)
    klass = Module.const_get("System::#{@system_tytle.capitalize}System")
    @system = klass.new(self, system_id)
  end
end


text:
require 'csv'

module Uploadable
  class Processor
    attr_accessor :mandatory, :optional, :model
    def initialize options = {}
      self.model = options[:model]
      self.mandatory = options[:mandatory_fields]
      self.optional = options[:optional_fields]
    end

    def transform_csv csv_contents
      records = []
      headers = ::CSV.parse_line(csv_contents, {:headers => true, :header_converters => :symbol}).to_hash.keys
      validate_headers headers
      extra_headers = headers - self.mandatory - self.optional
      ::CSV.parse(csv_contents, {:headers => true, :header_converters => lambda { |d| humanized_attr_mapping(headers)[d] || d.gsub(/\s+/, "").underscore.to_sym }}) do |row|
        record = row.to_hash.reject { |key, v| extra_headers.include? key }
        row.to_hash.each { |k, v| record[k]=self.model.send("transform_#{k}_for_upload", v) if self.model.respond_to?("transform_#{k}_for_upload") }

        records << record
      end
      records
    end

    private
    def validate_headers headers
      absent_fields = (self.mandatory - headers)
      raise Exception.new("Mandatory header(s): #{absent_fields.join(",")} is missing") unless absent_fields.blank?
    end

    def humanized_attr_mapping(headers)
      self.model.attribute_names.inject({}) do |header_to_field, attr|
        header_to_field[self.model.human_attribute_name(attr)] = attr.gsub(/\s+/, "").underscore.to_sym
        header_to_field
      end
    end
  end
end


text:
ACE_RCSID(Bounded_Packet_Relay, BPR_Drivers, "$Id: BPR_Drivers.cpp 81978 2008-06-16 16:57:12Z sowayaa $")

// Constructor.

Input_Device_Wrapper_Base::Input_Device_Wrapper_Base (ACE_Thread_Manager *input_task_mgr)
  : ACE_Task_Base (input_task_mgr),
    send_input_msg_cmd_ (0),
    input_period_ (ACE_ONE_SECOND_IN_USECS),
    is_active_ (0),
    send_count_ (0)
{
}

// Destructor.

Input_Device_Wrapper_Base::~Input_Device_Wrapper_Base (void)
{
}

// Sets send input message command in the input device driver object.

int
Input_Device_Wrapper_Base::set_send_input_msg_cmd (ACE_Command_Base *send_input_msg_cmd)
{
  // Set the new command.  Input device is not responsible
  // for deleting the old command, if any.
  send_input_msg_cmd_ = send_input_msg_cmd;
  return 0;
}

// Sets period between when input messages are produced.

int
Input_Device_Wrapper_Base::set_input_period (u_long input_period)
{
  input_period_ = input_period;
  return 0;
}

// Sets count of messages to send.

int
Input_Device_Wrapper_Base::set_send_count (long count)
{
  send_count_ = count;
  return 0;
}

// Request that the input device stop sending messages
// and terminate its thread.  Should return 1 if it will do so, 0
// if it has already done so, or -1 if there is a problem doing so.

int
Input_Device_Wrapper_Base::request_stop (void)
{
  if (is_active_)
    {
      is_active_ = 0;
      return 1;
    }

  return 0;
}

// This method runs the input device loop in the new thread.

int
Input_Device_Wrapper_Base::svc (void)
{
  ACE_Time_Value timeout;
  ACE_Message_Block *message;

  // Set a flag to indicate we're active.
  is_active_ = 1;

  // Start with the total count of messages to send.
  for (current_count_ = send_count_;
       // While we're still marked active, and there are packets to send.
       (is_active_) && (current_count_ != 0);
       )
    {
      // Create an input message to send.
      message = create_input_message ();
      if (message == 0)
        {
          if (is_active_)
            {
              is_active_ = 0;
              ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                                 "Failed to create input message object"),
                                 -1);
            }

          break;
        }

      // Make sure there is a send command object.
      if (send_input_msg_cmd_ == 0)
        {
          delete message;
          if (is_active_)
            {
              is_active_ = 0;
              ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                                 "send message command object not instantiated"),
                                -1);
            }

          break;
        }

      // Send the input message.
      if (send_input_msg_cmd_->execute ((void *) message) < 0)
        {
          delete message;
          if (is_active_)
            {
              is_active_ = 0;
              ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                                 "Failed executing send message command object"),
                                -1);
            }

          break;
        }

      // If all went well, decrement count of messages to send, and
      // run the reactor event loop unti we get a timeout or something
      // happens in a registered upcall.
      if (current_count_ > 0)
        --current_count_;

      timeout = ACE_Time_Value (0, input_period_);
      reactor_.run_event_loop (timeout);
    }

  is_active_ = 0;

  return 0;
}

// Sends a newly created message block, carrying data read from the
// underlying input device, by passing a pointer to the message block
// to its command execution.

int
Input_Device_Wrapper_Base::send_input_message (ACE_Message_Block *amb)
{
  if (send_input_msg_cmd_)
    return send_input_msg_cmd_->execute ((void *) amb);
  else
    {
      if (is_active_)
        ACE_ERROR ((LM_ERROR, "%t %p\n",
                    "Input_Device_Wrapper_Base::send_input_message: "
                    "command object not instantiated"));

      return -1;
    }
}

Output_Device_Wrapper_Base::~Output_Device_Wrapper_Base (void)
{
}

// Constructor.

Bounded_Packet_Relay::Bounded_Packet_Relay (ACE_Thread_Manager *input_task_mgr,
                                            Input_Device_Wrapper_Base *input_wrapper,
                                            Output_Device_Wrapper_Base *output_wrapper)
  : is_active_ (0),
    input_task_mgr_ (input_task_mgr),
    input_wrapper_ (input_wrapper),
    output_wrapper_ (output_wrapper),
    queue_ (Bounded_Packet_Relay::DEFAULT_HWM,
            Bounded_Packet_Relay::DEFAULT_LWM),
    queue_hwm_ (Bounded_Packet_Relay::DEFAULT_HWM),
    queue_lwm_ (Bounded_Packet_Relay::DEFAULT_LWM),
    transmission_number_ (0),
    packets_sent_ (0),
    status_ (Bounded_Packet_Relay::UN_INITIALIZED),
    transmission_start_ (ACE_Time_Value::zero),
    transmission_end_ (ACE_Time_Value::zero)
{
  if (input_task_mgr_ == 0)
    input_task_mgr_ = ACE_Thread_Manager::instance ();
}

// Destructor.

Bounded_Packet_Relay::~Bounded_Packet_Relay (void)
{
  // Reactivate the queue, and then clear it.
  queue_.activate ();
  while (! queue_.is_empty ())
    {
      ACE_Message_Block *msg;
      queue_.dequeue_head (msg);
      delete msg;
    }

}

// Requests output be sent to output device.

int
Bounded_Packet_Relay::send_input (void)
{
  // Don't block, return immediately if queue is empty.
  ACE_Message_Block *item;

  // Using a separate (non-const) time value
  // is necessary on some platforms
  ACE_Time_Value immediate (ACE_Time_Value::zero);

  if (queue_.dequeue_head (item,
                           &immediate) < 0)
    return 1;

  // If a message block was dequeued, send it to the output device.

  if (output_wrapper_->write_output_message ((void *) item) < 0)
    {
      if (is_active_)
        ACE_ERROR ((LM_ERROR,
                    "%t %p\n",
                    "failed to write to output device object"));

      return -1;
    }

  // If all went OK, increase count of packets sent.
  ++packets_sent_;
  return 0;
}

// Requests a transmission be started.

int
Bounded_Packet_Relay::start_transmission (u_long packet_count,
                                          u_long arrival_period,
                                          int logging_level)
{
  // Serialize access to start and end transmission calls, statistics
  // reporting calls.
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->transmission_lock_, -1);

  // If a transmission is already in progress, just return.
  if (is_active_)
    return 1;

  // Set transmission in progress flag true.
  is_active_ = 1;

  // Update statistics for a new transmission.
  ++transmission_number_;
  packets_sent_ = 0;
  status_ = STARTED;
  transmission_start_ = ACE_OS::gettimeofday ();

  // Reactivate the queue, and then clear it.
  queue_.activate ();
  while (! queue_.is_empty ())
    {
      ACE_Message_Block *msg;
      queue_.dequeue_head (msg);
      delete msg;
    }

  // Initialize the output device.
  if (output_wrapper_->modify_device_settings ((void *) &logging_level) < 0)
    {
      status_ = ERROR_DETECTED;
      transmission_end_ = ACE_OS::gettimeofday ();
      is_active_ = 0;
      ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                         "failed to initialize output device object"),
                        -1);
    }
  // Initialize the input device.
  if (input_wrapper_->modify_device_settings ((void *) &logging_level) < 0)
    {
      status_ = ERROR_DETECTED;
      transmission_end_ = ACE_OS::gettimeofday ();
      is_active_ = 0;
      ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                         "failed to initialize output device object"),
                        -1);
    }
  else if (input_wrapper_->set_input_period (arrival_period) < 0)
    {
      status_ = ERROR_DETECTED;
      transmission_end_ = ACE_OS::gettimeofday ();
      is_active_ = 0;
      ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                         "failed to initialize input device object"),
                        -1);
    }
  else if (input_wrapper_->set_send_count (packet_count) < 0)
    {
      status_ = ERROR_DETECTED;
      transmission_end_ = ACE_OS::gettimeofday ();
      is_active_ = 0;
      ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                         "failed to initialize input device object"),
                        -1);
    }
  // Activate the input device.
  else if (input_wrapper_->activate () < 0)
    {
      status_ = ERROR_DETECTED;
      transmission_end_ = ACE_OS::gettimeofday ();
      is_active_ = 0;
      ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                         "failed to activate input device object"),
                        -1);
    }

  // If all went well, print a startup message and return success.
  ACE_DEBUG ((LM_DEBUG,
              "\n\nTransmission %u started\n\n",
              transmission_number_));
  return 0;
}

// Requests a transmission be ended.

int
Bounded_Packet_Relay::end_transmission (Transmission_Status status)
{
  // Serialize access to start and end transmission calls,
  // statistics reporting calls.
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->transmission_lock_, -1);

  // If a transmission is not already in progress, just return.
  if (! is_active_)
    return 1;

  // Set transmission in progress flag false.
  is_active_ = 0;

  // Ask the the input thread to stop.
  if (input_wrapper_->request_stop () < 0)
    {
      status_ = ERROR_DETECTED;
      transmission_end_ = ACE_OS::gettimeofday ();
      ACE_ERROR_RETURN ((LM_ERROR, "%t %p\n",
                         "failed asking input device thread to stop"),
                        -1);
    }

  // Deactivate the queue, allowing all waiting threads to continue.
  queue_.deactivate ();

  // Wait for input thread to stop.
  input_task_mgr_->wait_task (input_wrapper_);

  // Reactivate the queue, and then clear it.
  queue_.activate ();
  while (! queue_.is_empty ())
    {
      ACE_Message_Block *msg;
      queue_.dequeue_head (msg);
      delete msg;
    }

  // If all went well, set passed status, stamp end time, print a
  // termination message, and return success.
  status_ = status;
  transmission_end_ = ACE_OS::gettimeofday ();
  ACE_DEBUG ((LM_DEBUG,
              "\n\nTransmission %u ended with status: %s\n\n",
              transmission_number_, status_msg ()));
  return 0;
}

// Requests a report of statistics from the last transmission.

int
Bounded_Packet_Relay::report_statistics (void)
{
  // Serialize access to start and end transmission calls,
  // statistics reporting calls.
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX, ace_mon, this->transmission_lock_, -1);

  // If a transmission is already in progress, just return.
  if (is_active_)
    return 1;

  // Calculate duration of trasmission.
  ACE_Time_Value duration (transmission_end_);
  duration -= transmission_start_;

  // Report transmission statistics.
  ACE_DEBUG ((LM_DEBUG,
              "\n\nStatisics for transmission %u:\n\n"
              "Transmission status: %s\n"
              "Start time:          %d (sec) %d (usec)\n"
              "End time:            %d (sec) %d (usec)\n"
              "Duration:            %d (sec) %d (usec)\n"
              "Packets relayed:     %u\n\n",
              transmission_number_, status_msg (),
              transmission_start_.sec (),
              transmission_start_.usec (),
              transmission_end_.sec (),
              transmission_end_.usec (),
              duration.sec (),
              duration.usec (),
              packets_sent_));
  return 0;
}

// Public entry point to which to push input.

int
Bounded_Packet_Relay::receive_input (void * arg)
{
  if (! arg)
    {
      if (is_active_)
        ACE_ERROR ((LM_ERROR, "%t %p\n",
                    "Bounded_Packet_Relay::receive_input: "
                    "null argument"));

      return -1;
    }
  ACE_Message_Block *message = static_cast<ACE_Message_Block *> (arg);
  if (queue_.enqueue_tail (message) < 0)
    {
      if (is_active_)
        ACE_ERROR ((LM_ERROR, "%t %p\n",
                    "Bounded_Packet_Relay::receive_input failed"));

      return -1;
    }

  return 0;
}

// Get high water mark for relay queue.

ACE_UINT32
Bounded_Packet_Relay::queue_hwm (void)
{
  return queue_lwm_;
}

// Set high water mark for relay queue.

void
Bounded_Packet_Relay::queue_hwm (ACE_UINT32 hwm)
{
  queue_hwm_ = hwm;
}

// Get low water mark for relay queue.

ACE_UINT32
Bounded_Packet_Relay::queue_lwm (void)
{
  return queue_lwm_;
}

// Set low water mark for relay queue.

void
Bounded_Packet_Relay::queue_lwm (ACE_UINT32 lwm)
{
  queue_lwm_ = lwm;
}

// Returns string corresponding to current status.

const char *
Bounded_Packet_Relay::status_msg (void)
{
  const char *status_msg;
  switch (status_)
    {
      case UN_INITIALIZED:
        status_msg = "uninitialized";
        break;
      case STARTED:
        status_msg = "in progress";
        break;
      case COMPLETED:
        status_msg = "completed with all packets sent";
        break;
      case TIMED_OUT:
        status_msg = "terminated by transmission duration timer";
        break;
      case CANCELLED:
        status_msg = "cancelled by external control";
        break;
      case ERROR_DETECTED:
        status_msg = "error was detected";
        break;
      default:
        status_msg = "unknown transmission status";
        break;
    }

  return status_msg;
}


text:
package v1alpha1

// CASVolumeType represents a valid cas volume
type CASVolumeType string

const (
	// JivaVolume represents a volume based on jiva
	JivaVolume CASVolumeType = "jiva"

	// CstorVolume represents a volume based on cstor
	CstorVolume CASVolumeType = "cstor"
)

// CASKey represents the key used either in resource annotation or label
type CASKey string

const (
	// CreatePoolCASTemplateKey is the cas template annotation key whose value is
	// the name of cas template that will be used to provision a storagepool
	// If this field is present on SPC then CAS template pointed by this field is used to provision
	// the storage pool else default CAS template is used.
	CreatePoolCASTemplateKey CASKey = "cas.openebs.io/create-pool-template"

	// DeletePoolCASTemplateKey is the cas template annotation key whose value is
	// the name of cas template that will be used to delete a storagepool
	DeletePoolCASTemplateKey CASKey = "cas.openebs.io/delete-pool-template"

	// OpenEBSVersionKey is the label key which provides the installed version of
	// OpenEBS
	OpenEBSVersionKey CASKey = "openebs.io/version"

	// OpenEBSDisableReconcileKey is the label key decides to reconcile or not
	OpenEBSDisableReconcileKey CASKey = "reconcile.openebs.io/disable"

	// CASConfigKey is the key to fetch configurations w.r.t a CAS entity
	CASConfigKey CASKey = "cas.openebs.io/config"

	// NamespaceKey is the key to fetch cas entity's namespace
	NamespaceKey CASKey = "openebs.io/namespace"

	// PersistentVolumeClaimKey is the key to fetch name of PersistentVolumeClaim
	PersistentVolumeClaimKey CASKey = "openebs.io/persistentvolumeclaim"

	// CASKeyIsPatchJivaReplicaNodeAffinityHeader is the key to fetch value of IsPatchKey
	// its value is "enabled".
	CASKeyIsPatchJivaReplicaNodeAffinityHeader CASKey = "Is-Patch-Jiva-Replica-Node-Affinity"

	// NodeAffinityReplicaJivaIsPatchKey is the key to fetch value of IsPatchKey
	// its value is "enabled".
	NodeAffinityReplicaJivaIsPatchKey CASKey = "nodeAffinity.replica.jiva.openebs.io/is-patch"

	// CASKeyIsPatchJivaReplicaNodeAffinity is the key to fetch value of IsPatchKey
	// its value is "enabled".
	CASKeyIsPatchJivaReplicaNodeAffinity CASKey = "isPatchJivaReplicaNodeAffinity"

	// StorageClassKey is the key to fetch name of StorageClass
	StorageClassKey CASKey = "openebs.io/storageclass"

	// ConfigClassKey is the key to fetch name of CStorVolume ConfigClass
	ConfigClassKey CASKey = "openebs.io/config-class"

	// CASTypeKey is the key to fetch storage engine for the volume
	CASTypeKey CASKey = "openebs.io/cas-type"

	// StorageClassHeaderKey is the key to fetch name of StorageClass
	// This key is present only in get request headers
	StorageClassHeaderKey CASKey = "storageclass"
)

// CASPlainKey represents a openebs key used either in resource annotation
// or label
//
// NOTE:
//  PlainKey (i.e. without 'openebs.io/' ) helps to parse key via
// go templating
type CASPlainKey string

const (
	// OpenEBSVersionPlainKey is the label key which provides the installed
	// version of OpenEBS
	OpenEBSVersionPlainKey CASPlainKey = "version"

	// CASTNamePlainKey is the key to fetch name of CAS template
	CASTNamePlainKey CASPlainKey = "castName"
)

// KubePlainKey represents a kubernetes key used either in resource annotation
// or label
//
// NOTE:
//  PlainKey (i.e. without 'kubernetes.io/' ) helps to parse key via
// go templating
type KubePlainKey string

const (
	// KubeServerVersionPlainKey is the key to fetch Kubernetes server version
	KubeServerVersionPlainKey KubePlainKey = "kubeVersion"
)

// DeprecatedKey is a typed string to represent deprecated annotations' or
// labels' key
type DeprecatedKey string

const (
	// CapacityDeprecatedKey is a label key used to set volume capacity
	//
	// NOTE:
	//  Deprecated in favour of CASVolume.Spec.Capacity
	CapacityDeprecatedKey DeprecatedKey = "volumeprovisioner.mapi.openebs.io/storage-size"

	// NamespaceDeprecatedKey is the key to fetch volume's namespace
	//
	// NOTE:
	//  Deprecated in favour of NamespaceKey
	NamespaceDeprecatedKey DeprecatedKey = "k8s.io/namespace"

	// PersistentVolumeClaimDeprecatedKey is the key to fetch volume's PVC
	//
	// NOTE:
	//  Deprecated in favour of PersistentVolumeClaimKey
	PersistentVolumeClaimDeprecatedKey DeprecatedKey = "k8s.io/pvc"

	// StorageClassDeprecatedKey is the key to fetch name of StorageClass
	//
	// NOTE:
	//  Deprecated in favour of StorageClassKey
	StorageClassDeprecatedKey DeprecatedKey = "k8s.io/storage-class"
)


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

#include "ui/events/platform/x11/x11_hotplug_event_handler.h"

#include <X11/Xatom.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>

#include <algorithm>
#include <cmath>
#include <set>
#include <string>
#include <vector>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/process/launch.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/events/devices/device_hotplug_event_observer.h"
#include "ui/events/devices/device_util_linux.h"
#include "ui/events/devices/input_device.h"
#include "ui/events/devices/keyboard_device.h"
#include "ui/events/devices/touchscreen_device.h"
#include "ui/gfx/x/x11_types.h"

namespace ui {

namespace {

// Names of all known internal devices that should not be considered as
// keyboards.
// TODO(rsadam@): Identify these devices using udev rules. (Crbug.com/420728.)
const char* kKnownInvalidKeyboardDeviceNames[] = {"Power Button",
                                                  "Sleep Button",
                                                  "Video Bus"};

const char* kCachedAtomList[] = {
  "Abs MT Position X",
  "Abs MT Position Y",
  NULL,
};

typedef base::Callback<void(const std::vector<KeyboardDevice>&)>
    KeyboardDeviceCallback;

typedef base::Callback<void(const std::vector<TouchscreenDevice>&)>
    TouchscreenDeviceCallback;

// Used for updating the state on the UI thread once device information is
// parsed on helper threads.
struct UiCallbacks {
  KeyboardDeviceCallback keyboard_callback;
  TouchscreenDeviceCallback touchscreen_callback;
};

// Stores a copy of the XIValuatorClassInfo values so X11 device processing can
// happen on a worker thread. This is needed since X11 structs are not copyable.
struct ValuatorClassInfo {
  ValuatorClassInfo(const XIValuatorClassInfo& info)
      : label(info.label),
        max(info.max),
        min(info.min),
        mode(info.mode),
        number(info.number) {}

  Atom label;
  double max;
  double min;
  int mode;
  int number;
};

// Stores a copy of the XITouchClassInfo values so X11 device processing can
// happen on a worker thread. This is needed since X11 structs are not copyable.
struct TouchClassInfo {
  TouchClassInfo(const XITouchClassInfo& info)
      : mode(info.mode) {}

  int mode;
};

struct DeviceInfo {
  DeviceInfo(const XIDeviceInfo& device, const base::FilePath& path)
      : id(device.deviceid),
        name(device.name),
        use(device.use),
        enabled(device.enabled),
        path(path) {
    for (int i = 0; i < device.num_classes; ++i) {
      switch (device.classes[i]->type) {
        case XIValuatorClass:
          valuator_class_infos.push_back(ValuatorClassInfo(
              *reinterpret_cast<XIValuatorClassInfo*>(device.classes[i])));
          break;
        case XITouchClass:
          touch_class_infos.push_back(TouchClassInfo(
              *reinterpret_cast<XITouchClassInfo*>(device.classes[i])));
          break;
        default:
          break;
      }
    }
  }

  // Unique device identifier.
  int id;

  // Internal device name.
  std::string name;

  // Device type (ie: XIMasterPointer)
  int use;

  // Specifies if the device is enabled and can send events.
  bool enabled;

  // Path to the actual device (ie: /dev/input/eventXX)
  base::FilePath path;

  std::vector<ValuatorClassInfo> valuator_class_infos;

  std::vector<TouchClassInfo> touch_class_infos;
};

// X11 display cache used on worker threads. This is filled on the UI thread and
// passed in to the worker threads.
struct DisplayState {
  Atom mt_position_x;
  Atom mt_position_y;
};

// Returns true if |name| is the name of a known invalid keyboard device. Note,
// this may return false negatives.
bool IsKnownInvalidKeyboardDevice(const std::string& name) {
  for (const char* device_name : kKnownInvalidKeyboardDeviceNames) {
    if (name == device_name)
      return true;
  }
  return false;
}

// Returns true if |name| is the name of a known XTEST device. Note, this may
// return false negatives.
bool IsTestKeyboard(const std::string& name) {
  return name.find("XTEST") != std::string::npos;
}

base::FilePath GetDevicePath(XDisplay* dpy, const XIDeviceInfo& device) {
  // Skip the main pointer and keyboard since XOpenDevice() generates a
  // BadDevice error when passed these devices.
  if (device.use == XIMasterPointer || device.use == XIMasterKeyboard)
    return base::FilePath();

  // Input device has a property "Device Node" pointing to its dev input node,
  // e.g.   Device Node (250): "/dev/input/event8"
  Atom device_node = XInternAtom(dpy, "Device Node", False);
  if (device_node == None)
    return base::FilePath();

  Atom actual_type;
  int actual_format;
  unsigned long nitems, bytes_after;
  unsigned char* data;
  XDevice* dev = XOpenDevice(dpy, device.deviceid);
  if (!dev)
    return base::FilePath();

  if (XGetDeviceProperty(dpy,
                         dev,
                         device_node,
                         0,
                         1000,
                         False,
                         AnyPropertyType,
                         &actual_type,
                         &actual_format,
                         &nitems,
                         &bytes_after,
                         &data) != Success) {
    XCloseDevice(dpy, dev);
    return base::FilePath();
  }

  std::string path;
  // Make sure the returned value is a string.
  if (actual_type == XA_STRING && actual_format == 8)
    path = reinterpret_cast<char*>(data);

  XFree(data);
  XCloseDevice(dpy, dev);

  return base::FilePath(path);
}

// Helper used to parse keyboard information. When it is done it uses
// |reply_runner| and |callback| to update the state on the UI thread.
void HandleKeyboardDevicesInWorker(
    const std::vector<DeviceInfo>& device_infos,
    scoped_refptr<base::TaskRunner> reply_runner,
    const KeyboardDeviceCallback& callback) {
  std::vector<KeyboardDevice> devices;

  for (const DeviceInfo& device_info : device_infos) {
    if (!device_info.enabled || device_info.use != XISlaveKeyboard)
      continue;  // Assume all keyboards are keyboard slaves
    std::string device_name(device_info.name);
    base::TrimWhitespaceASCII(device_name, base::TRIM_TRAILING, &device_name);
    if (IsTestKeyboard(device_name))
      continue;  // Skip test devices.
    if (IsKnownInvalidKeyboardDevice(device_name))
      continue;  // Skip invalid devices.
    InputDeviceType type = GetInputDeviceTypeFromPath(device_info.path);
    devices.push_back(
        KeyboardDevice(device_info.id, type, device_name));
  }

  reply_runner->PostTask(FROM_HERE, base::Bind(callback, devices));
}

// Helper used to parse touchscreen information. When it is done it uses
// |reply_runner| and |callback| to update the state on the UI thread.
void HandleTouchscreenDevicesInWorker(
    const std::vector<DeviceInfo>& device_infos,
    const DisplayState& display_state,
    scoped_refptr<base::TaskRunner> reply_runner,
    const TouchscreenDeviceCallback& callback) {
  std::vector<TouchscreenDevice> devices;
  if (display_state.mt_position_x == None ||
      display_state.mt_position_y == None)
    return;

  std::set<int> no_match_touchscreen;
  for (const DeviceInfo& device_info : device_infos) {
    if (!device_info.enabled || device_info.use != XIFloatingSlave)
      continue;  // Assume all touchscreens are floating slaves

    double max_x = -1.0;
    double max_y = -1.0;
    bool is_direct_touch = false;

    for (const ValuatorClassInfo& valuator : device_info.valuator_class_infos) {
      if (display_state.mt_position_x == valuator.label) {
        // Ignore X axis valuator with unexpected properties
        if (valuator.number == 0 && valuator.mode == Absolute &&
            valuator.min == 0.0) {
          max_x = valuator.max;
        }
      } else if (display_state.mt_position_y == valuator.label) {
        // Ignore Y axis valuator with unexpected properties
        if (valuator.number == 1 && valuator.mode == Absolute &&
            valuator.min == 0.0) {
          max_y = valuator.max;
        }
      }
    }

    for (const TouchClassInfo& info : device_info.touch_class_infos) {
      is_direct_touch = info.mode == XIDirectTouch;
    }

    // Touchscreens should have absolute X and Y axes, and be direct touch
    // devices.
    if (max_x > 0.0 && max_y > 0.0 && is_direct_touch) {
      InputDeviceType type = GetInputDeviceTypeFromPath(device_info.path);
      // |max_x| and |max_y| are inclusive values, so we need to add 1 to get
      // the size.
      devices.push_back(TouchscreenDevice(
          device_info.id,
          type,
          device_info.name,
          gfx::Size(max_x + 1, max_y + 1)));
    }
  }

  reply_runner->PostTask(FROM_HERE, base::Bind(callback, devices));
}

// Called on a worker thread to parse the device information.
void HandleHotplugEventInWorker(
    const std::vector<DeviceInfo>& devices,
    const DisplayState& display_state,
    scoped_refptr<base::TaskRunner> reply_runner,
    const UiCallbacks& callbacks) {
  HandleTouchscreenDevicesInWorker(
      devices, display_state, reply_runner, callbacks.touchscreen_callback);
  HandleKeyboardDevicesInWorker(
      devices, reply_runner, callbacks.keyboard_callback);
}

DeviceHotplugEventObserver* GetHotplugEventObserver() {
  return DeviceDataManager::GetInstance();
}

void OnKeyboardDevices(const std::vector<KeyboardDevice>& devices) {
  GetHotplugEventObserver()->OnKeyboardDevicesUpdated(devices);
}

void OnTouchscreenDevices(const std::vector<TouchscreenDevice>& devices) {
  GetHotplugEventObserver()->OnTouchscreenDevicesUpdated(devices);
}

}  // namespace

X11HotplugEventHandler::X11HotplugEventHandler()
    : atom_cache_(gfx::GetXDisplay(), kCachedAtomList) {
}

X11HotplugEventHandler::~X11HotplugEventHandler() {
}

void X11HotplugEventHandler::OnHotplugEvent() {
  const XIDeviceList& device_list =
      DeviceListCacheX11::GetInstance()->GetXI2DeviceList(gfx::GetXDisplay());
  Display* display = gfx::GetXDisplay();

  std::vector<DeviceInfo> device_infos;
  for (int i = 0; i < device_list.count; ++i) {
    const XIDeviceInfo& device = device_list[i];
    device_infos.push_back(DeviceInfo(device, GetDevicePath(display, device)));
  }

  // X11 is not thread safe, so first get all the required state.
  DisplayState display_state;
  display_state.mt_position_x = atom_cache_.GetAtom("Abs MT Position X");
  display_state.mt_position_y = atom_cache_.GetAtom("Abs MT Position Y");

  UiCallbacks callbacks;
  callbacks.keyboard_callback = base::Bind(&OnKeyboardDevices);
  callbacks.touchscreen_callback = base::Bind(&OnTouchscreenDevices);
  // TODO(pkotwicz): Compute the lists of mice and touchpads and send the new
  // lists to DeviceHotplugEventObserver.

  // Parsing the device information may block, so delegate the operation to a
  // worker thread. Once the device information is extracted the parsed devices
  // will be returned via the callbacks.
  base::WorkerPool::PostTask(FROM_HERE,
                             base::Bind(&HandleHotplugEventInWorker,
                                        device_infos,
                                        display_state,
                                        base::ThreadTaskRunnerHandle::Get(),
                                        callbacks),
                             true /* task_is_slow */);
}

}  // namespace ui


text:
package org.elasticsearch.xpack.security.rest.action.oidc;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.license.LicenseUtils;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings;
import org.elasticsearch.xpack.security.authc.Realms;
import org.elasticsearch.xpack.security.rest.action.SecurityBaseRestHandler;

public abstract class OpenIdConnectBaseRestHandler extends SecurityBaseRestHandler {

    private static final String OIDC_REALM_TYPE = OpenIdConnectRealmSettings.TYPE;

    /**
     * @param settings     the node's settings
     * @param licenseState the license state that will be used to determine if security is licensed
     */
    protected OpenIdConnectBaseRestHandler(Settings settings, XPackLicenseState licenseState) {
        super(settings, licenseState);
    }

    @Override
    protected Exception checkFeatureAvailable(RestRequest request) {
        Exception failedFeature = super.checkFeatureAvailable(request);
        if (failedFeature != null) {
            return failedFeature;
        } else if (Realms.isRealmTypeAvailable(licenseState.allowedRealmType(), OIDC_REALM_TYPE)) {
            return null;
        } else {
            logger.info("The '{}' realm is not available under the current license", OIDC_REALM_TYPE);
            return LicenseUtils.newComplianceException(OIDC_REALM_TYPE);
        }
    }
}


text:
CREATE SEQUENCE users_id_seq;
CREATE TABLE users (
    id INT NOT NULL DEFAULT nextval('users_id_seq'),
    name varchar(255)
);

# --- !Downs

DROP TABLE users;
DROP SEQUENCE users_id_seq;


text:
class Application < ActiveRecord::Base

  has_many :message_types
  validates_uniqueness_of :key
  validates_presence_of :team_id
  has_many :messages
  belongs_to :team

  def user_entitled?(current_user)

    return false if current_user.nil?
    return current_user.teams.where(:id => self.team_id).exists?

  end

end


text:
'use strict';

var React = require('react');
var Navbar = require('react-bootstrap/Navbar');
var Nav = require('react-bootstrap/Nav');
var ZipcodeInput = require('./ZipcodeInput.js');

var Header = React.createClass({
    displayName: 'Header',
    render: function () {
        return (
            <div>
                <Navbar inverse>
                    <Nav>
                        <ZipcodeInput ackWhenValid={false} zipcode={this.props.zipcode} />
                    </Nav>
                </Navbar>
            </div>
        );
    }
});

module.exports = Header;


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

/*********************************************************************************

 * Description:  TODO: To be written.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/

require_once('modules/Emails/Email.php');

global $mod_strings;
global $app_list_strings;
global $app_strings;
global $current_user;

$json = getJSONobj();
$pass = '';
if(!empty($_REQUEST['mail_smtppass'])) {
    $pass = $_REQUEST['mail_smtppass'];
} elseif(isset($_REQUEST['mail_type'])) {
    $oe = new OutboundEmail();
    $oe = $oe->getMailerByName($current_user, $_REQUEST['mail_type']);
    if(!empty($oe)) {
        $pass = $oe->mail_smtppass;
    }
}
$out = Email::sendEmailTest($_REQUEST['mail_smtpserver'], $_REQUEST['mail_smtpport'], $_REQUEST['mail_smtpssl'],
        							($_REQUEST['mail_smtpauth_req'] == 'true' ? 1 : 0), $_REQUEST['mail_smtpuser'],
        							$pass, $_REQUEST['outboundtest_from_address'], $_REQUEST['outboundtest_to_address'], $_REQUEST['mail_sendtype'], $_REQUEST['mail_from_name']);

$out = $json->encode($out);
echo $out;
?>


text:
<?php

namespace App\Models\Rme;

use App\Models\Orm\Repository;

class StudentInvitesRepository extends Repository
{

}


text:
package crypto

import (
	"github.com/pquerna/distsync/common"

	"errors"
	"io"
	"strings"
)

type Encryptor interface {
	Encrypt(io.Reader, io.Writer) error
}

type Decryptor interface {
	Decrypt(io.Reader, io.Writer) error
}

type Cryptor interface {
	Encryptor
	Decryptor
}

func NewFromConf(c *common.Conf) (Cryptor, error) {
	// currently etm use a 32 byte secret.
	// TODO: better abstraction / interface.
	secret, err := decodeSecret(c.SharedSecret, 32)
	if err != nil {
		return nil, err
	}

	switch strings.ToUpper(c.Encrypt) {
	case "AEAD_AES_128_CBC_HMAC_SHA_256":
		return NewAES128SHA256(secret)
	case "AEAD_CHACHA20_POLY1305":
		return NewChacha20poly1305(secret)
	}

	return nil, errors.New("Unknown crypto backend: " + c.Encrypt)
}


text:
(function(root, factory) {
  'use strict';
  /* jshint unused: false */

  if (typeof define === 'function' && define.amd) {
    define(['es6-promise'], function(promise) {
      promise.polyfill();
      return factory(root);
    });
  } else if (typeof module !== 'undefined' && module.exports) {
    var Promise = require('es6-promise').polyfill();
    module.exports = factory.call(root);
  } else if (window !== undefined) {
    if (root.ES6Promise !== undefined && typeof root.ES6Promise.polyfill === 'function') {
      root.ES6Promise.polyfill();
    }
    root.corbel = factory(root);
  }

})(this, function(root) {
  'use strict';
  /* jshint unused: false */

  //  @include ../../bower_components/es6-promise/es6-promise.js

  /**
   * corbel namespace
   * @exports corbel
   * @namespace
   */
  var corbel = {};

  //-----------Utils and libraries (exports into corbel namespace)---------------------------

  //  @include ../corbel.js

  //  @include ../utils.js

  //  @include ../validate.js

  //  @include ../object.js

  //  @include ../cryptography.js

  //  @include ../jwt.js

  //  @include ../request.js

  //  @include ../services.js

  //----------corbel modules----------------

  //  @include ../config.js
  //  @include ../iam/iam.js
  //  @include ../iam/clientBuilder.js
  //  @include ../iam/domainBuilder.js
  //  @include ../iam/scopeBuilder.js
  //  @include ../iam/tokenBuilder.js
  //  @include ../iam/usernameBuilder.js
  //  @include ../iam/usersBuilder.js
  //  @include ../iam/groupsBuilder.js
  //  @include ../iam/emailBuilder.js
  //  @include ../assets/assets.js
  //  @include ../assets/assets-builder.js
  //  @include ../scheduler/scheduler.js
  //  @include ../scheduler/schedulerBuilder.js
  //  @include ../request-params/aggregation-builder.js
  //  @include ../request-params/query-builder.js
  //  @include ../request-params/page-builder.js
  //  @include ../request-params/sort-builder.js
  //  @include ../request-params/request-params-builder.js
  //  @include ../resources/resources.js
  //  @include ../resources/base-resource.js
  //  @include ../resources/relation.js
  //  @include ../resources/collection.js
  //  @include ../resources/resource.js
  //  @include ../oauth/oauth.js
  //  @include ../oauth/authorizationBuilder.js
  //  @include ../oauth/tokenBuilder.js
  //  @include ../oauth/userBuilder.js
  //  @include ../notifications/notifications.js
  //  @include ../notifications/base-notifications.js
  //  @include ../notifications/notificationsBuilder.js
  //  @include ../notifications/notificationsDomainBuilder.js
  //  @include ../notifications/notificationsTemplateBuilder.js
  //  @include ../ec/ec.js
  //  @include ../ec/orderBuilder.js
  //  @include ../ec/productBuilder.js
  //  @include ../evci/evci.js
  //  @include ../evci/eventBuilder.js
  //  @include ../borrow/borrow.js
  //  @include ../borrow/borrowBuilder.js
  //  @include ../borrow/userBuilder.js
  //  @include ../borrow/lenderBuilder.js
  //  @include ../composr/composr.js
  //  @include ../composr/phraseBuilder.js
  //  @include ../composr/requestBuilder.js
  //  @include ../webfs/webfs.js
  //  @include ../webfs/webfsBuilder.js
  //  @include ../domain/domain.js

  return corbel;
});


text:
package flate

import (
	"math"
	"math/bits"
	"sort"
)

// hcode is a huffman code with a bit code and bit length.
type hcode struct {
	code, len uint16
}

type huffmanEncoder struct {
	codes     []hcode
	freqcache []literalNode
	bitCount  [17]int32
	lns       byLiteral // stored to avoid repeated allocation in generate
	lfs       byFreq    // stored to avoid repeated allocation in generate
}

type literalNode struct {
	literal uint16
	freq    int32
}

// A levelInfo describes the state of the constructed tree for a given depth.
type levelInfo struct {
	// Our level.  for better printing
	level int32

	// The frequency of the last node at this level
	lastFreq int32

	// The frequency of the next character to add to this level
	nextCharFreq int32

	// The frequency of the next pair (from level below) to add to this level.
	// Only valid if the "needed" value of the next lower level is 0.
	nextPairFreq int32

	// The number of chains remaining to generate for this level before moving
	// up to the next level
	needed int32
}

// set sets the code and length of an hcode.
func (h *hcode) set(code uint16, length uint16) {
	h.len = length
	h.code = code
}

func maxNode() literalNode { return literalNode{math.MaxUint16, math.MaxInt32} }

func newHuffmanEncoder(size int) *huffmanEncoder {
	return &huffmanEncoder{codes: make([]hcode, size)}
}

// Generates a HuffmanCode corresponding to the fixed literal table
func generateFixedLiteralEncoding() *huffmanEncoder {
	h := newHuffmanEncoder(maxNumLit)
	codes := h.codes
	var ch uint16
	for ch = 0; ch < maxNumLit; ch++ {
		var bits uint16
		var size uint16
		switch {
		case ch < 144:
			// size 8, 000110000  .. 10111111
			bits = ch + 48
			size = 8
			break
		case ch < 256:
			// size 9, 110010000 .. 111111111
			bits = ch + 400 - 144
			size = 9
			break
		case ch < 280:
			// size 7, 0000000 .. 0010111
			bits = ch - 256
			size = 7
			break
		default:
			// size 8, 11000000 .. 11000111
			bits = ch + 192 - 280
			size = 8
		}
		codes[ch] = hcode{code: reverseBits(bits, byte(size)), len: size}
	}
	return h
}

func generateFixedOffsetEncoding() *huffmanEncoder {
	h := newHuffmanEncoder(30)
	codes := h.codes
	for ch := range codes {
		codes[ch] = hcode{code: reverseBits(uint16(ch), 5), len: 5}
	}
	return h
}

var fixedLiteralEncoding *huffmanEncoder = generateFixedLiteralEncoding()
var fixedOffsetEncoding *huffmanEncoder = generateFixedOffsetEncoding()

func (h *huffmanEncoder) bitLength(freq []int32) int {
	var total int
	for i, f := range freq {
		if f != 0 {
			total += int(f) * int(h.codes[i].len)
		}
	}
	return total
}

const maxBitsLimit = 16

// Return the number of literals assigned to each bit size in the Huffman encoding
//
// This method is only called when list.length >= 3
// The cases of 0, 1, and 2 literals are handled by special case code.
//
// list  An array of the literals with non-zero frequencies
//             and their associated frequencies. The array is in order of increasing
//             frequency, and has as its last element a special element with frequency
//             MaxInt32
// maxBits     The maximum number of bits that should be used to encode any literal.
//             Must be less than 16.
// return      An integer array in which array[i] indicates the number of literals
//             that should be encoded in i bits.
func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
	if maxBits >= maxBitsLimit {
		panic("flate: maxBits too large")
	}
	n := int32(len(list))
	list = list[0 : n+1]
	list[n] = maxNode()

	// The tree can't have greater depth than n - 1, no matter what. This
	// saves a little bit of work in some small cases
	if maxBits > n-1 {
		maxBits = n - 1
	}

	// Create information about each of the levels.
	// A bogus "Level 0" whose sole purpose is so that
	// level1.prev.needed==0.  This makes level1.nextPairFreq
	// be a legitimate value that never gets chosen.
	var levels [maxBitsLimit]levelInfo
	// leafCounts[i] counts the number of literals at the left
	// of ancestors of the rightmost node at level i.
	// leafCounts[i][j] is the number of literals at the left
	// of the level j ancestor.
	var leafCounts [maxBitsLimit][maxBitsLimit]int32

	for level := int32(1); level <= maxBits; level++ {
		// For every level, the first two items are the first two characters.
		// We initialize the levels as if we had already figured this out.
		levels[level] = levelInfo{
			level:        level,
			lastFreq:     list[1].freq,
			nextCharFreq: list[2].freq,
			nextPairFreq: list[0].freq + list[1].freq,
		}
		leafCounts[level][level] = 2
		if level == 1 {
			levels[level].nextPairFreq = math.MaxInt32
		}
	}

	// We need a total of 2*n - 2 items at top level and have already generated 2.
	levels[maxBits].needed = 2*n - 4

	level := maxBits
	for {
		l := &levels[level]
		if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 {
			// We've run out of both leafs and pairs.
			// End all calculations for this level.
			// To make sure we never come back to this level or any lower level,
			// set nextPairFreq impossibly large.
			l.needed = 0
			levels[level+1].nextPairFreq = math.MaxInt32
			level++
			continue
		}

		prevFreq := l.lastFreq
		if l.nextCharFreq < l.nextPairFreq {
			// The next item on this row is a leaf node.
			n := leafCounts[level][level] + 1
			l.lastFreq = l.nextCharFreq
			// Lower leafCounts are the same of the previous node.
			leafCounts[level][level] = n
			l.nextCharFreq = list[n].freq
		} else {
			// The next item on this row is a pair from the previous row.
			// nextPairFreq isn't valid until we generate two
			// more values in the level below
			l.lastFreq = l.nextPairFreq
			// Take leaf counts from the lower level, except counts[level] remains the same.
			copy(leafCounts[level][:level], leafCounts[level-1][:level])
			levels[l.level-1].needed = 2
		}

		if l.needed--; l.needed == 0 {
			// We've done everything we need to do for this level.
			// Continue calculating one level up. Fill in nextPairFreq
			// of that level with the sum of the two nodes we've just calculated on
			// this level.
			if l.level == maxBits {
				// All done!
				break
			}
			levels[l.level+1].nextPairFreq = prevFreq + l.lastFreq
			level++
		} else {
			// If we stole from below, move down temporarily to replenish it.
			for levels[level-1].needed > 0 {
				level--
			}
		}
	}

	// Somethings is wrong if at the end, the top level is null or hasn't used
	// all of the leaves.
	if leafCounts[maxBits][maxBits] != n {
		panic("leafCounts[maxBits][maxBits] != n")
	}

	bitCount := h.bitCount[:maxBits+1]
	bits := 1
	counts := &leafCounts[maxBits]
	for level := maxBits; level > 0; level-- {
		// chain.leafCount gives the number of literals requiring at least "bits"
		// bits to encode.
		bitCount[bits] = counts[level] - counts[level-1]
		bits++
	}
	return bitCount
}

// Look at the leaves and assign them a bit count and an encoding as specified
// in RFC 1951 3.2.2
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
	code := uint16(0)
	for n, bits := range bitCount {
		code <<= 1
		if n == 0 || bits == 0 {
			continue
		}
		// The literals list[len(list)-bits] .. list[len(list)-bits]
		// are encoded using "bits" bits, and get the values
		// code, code + 1, ....  The code values are
		// assigned in literal order (not frequency order).
		chunk := list[len(list)-int(bits):]

		h.lns.sort(chunk)
		for _, node := range chunk {
			h.codes[node.literal] = hcode{code: reverseBits(code, uint8(n)), len: uint16(n)}
			code++
		}
		list = list[0 : len(list)-int(bits)]
	}
}

// Update this Huffman Code object to be the minimum code for the specified frequency count.
//
// freq  An array of frequencies, in which frequency[i] gives the frequency of literal i.
// maxBits  The maximum number of bits to use for any literal.
func (h *huffmanEncoder) generate(freq []int32, maxBits int32) {
	if h.freqcache == nil {
		// Allocate a reusable buffer with the longest possible frequency table.
		// Possible lengths are codegenCodeCount, offsetCodeCount and maxNumLit.
		// The largest of these is maxNumLit, so we allocate for that case.
		h.freqcache = make([]literalNode, maxNumLit+1)
	}
	list := h.freqcache[:len(freq)+1]
	// Number of non-zero literals
	count := 0
	// Set list to be the set of all non-zero literals and their frequencies
	for i, f := range freq {
		if f != 0 {
			list[count] = literalNode{uint16(i), f}
			count++
		} else {
			list[count] = literalNode{}
			h.codes[i].len = 0
		}
	}
	list[len(freq)] = literalNode{}

	list = list[:count]
	if count <= 2 {
		// Handle the small cases here, because they are awkward for the general case code. With
		// two or fewer literals, everything has bit length 1.
		for i, node := range list {
			// "list" is in order of increasing literal value.
			h.codes[node.literal].set(uint16(i), 1)
		}
		return
	}
	h.lfs.sort(list)

	// Get the number of literals for each bit count
	bitCount := h.bitCounts(list, maxBits)
	// And do the assignment
	h.assignEncodingAndSize(bitCount, list)
}

type byLiteral []literalNode

func (s *byLiteral) sort(a []literalNode) {
	*s = byLiteral(a)
	sort.Sort(s)
}

func (s byLiteral) Len() int { return len(s) }

func (s byLiteral) Less(i, j int) bool {
	return s[i].literal < s[j].literal
}

func (s byLiteral) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

type byFreq []literalNode

func (s *byFreq) sort(a []literalNode) {
	*s = byFreq(a)
	sort.Sort(s)
}

func (s byFreq) Len() int { return len(s) }

func (s byFreq) Less(i, j int) bool {
	if s[i].freq == s[j].freq {
		return s[i].literal < s[j].literal
	}
	return s[i].freq < s[j].freq
}

func (s byFreq) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func reverseBits(number uint16, bitLength byte) uint16 {
	return bits.Reverse16(number << (16 - bitLength))
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>PluginCollection.CopyTo Method (IPlugin[], Int32)</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

PluginCollection.CopyTo Method (IPlugin[], Int32)

 Copies the entire PluginCollection to a one-dimensional IPlugin array, starting at the specified index of the target array.

        [Visual Basic]

Overridable Overloads Public Sub CopyTo( _
   ByVal array As IPlugin(), _
   ByVal start As Integer _
)

        [C#]

public virtual void CopyTo(
   IPlugin[] array,
   int start
);

Parameters

          array

The one-dimensional IPlugin array to copy to.

          start

The zero-based index in array at which copying begins.

See Also

        PluginCollection Class | log4net.Plugin Namespace | PluginCollection.CopyTo Overload List

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="CopyTo method">
        </param>
        <param name="Keyword" value="CopyTo method, PluginCollection class">
        </param>
        <param name="Keyword" value="PluginCollection.CopyTo method">
        </param>
      </object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text: doctoc . --github


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/button_recessed_pressed" android:state_focused="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/button_recessed_pressed" android:state_focused="false" android:state_pressed="true"/>
    <item android:drawable="@drawable/button_recessed_pressed" android:state_focused="true"/>
    <item android:drawable="@drawable/button_recessed_default" android:state_focused="false" android:state_pressed="false"/>

</selector>


text:
from unittest import TestCase
from mock import MagicMock, patch

import frontend.api.v1_1.controllers.results as api_results
from frontend.models.sqlobjects import FileWeb

class TestResultsFiles(TestCase):
    @patch("frontend.api.v1_1.controllers.results.FileWeb")
    @patch("frontend.api.v1_1.controllers.results.FileWebSchema_v1_1")
    @patch("frontend.api.v1_1.controllers.results.validate_id")
    def test001_get_ok(self, m_validate_id, m_fw_schema,
                       m_FileWeb):
        db_mock = MagicMock()
        expected = m_fw_schema().dumps().data
        resultid = "whatever"
        result = api_results.get(resultid, db_mock)
        m_validate_id.assert_called_once_with(resultid)
        m_FileWeb.load_from_ext_id.assert_called_once_with(resultid, db_mock)
        self.assertEqual(result, expected)
        self.assertEqual(api_results.response.content_type,
                         "application/json; charset=UTF-8")

    @patch("frontend.api.v1_1.controllers.results.request")
    @patch("frontend.api.v1_1.controllers.results.FileWeb")
    @patch("frontend.api.v1_1.controllers.results.validate_id")
    def test002_get_formatted_ok(self, m_validate_id, m_FileWeb,
                                 m_request):
        db_mock = MagicMock()
        resultid = "whatever"
        m_request.formatted = True
        m_FileWeb.load_from_ext_id.return_value = FileWeb(None, None,
                                                          None, None)
        api_results.get(resultid, db_mock)
        m_validate_id.assert_called_once_with(resultid)
        m_FileWeb.load_from_ext_id.assert_called_once_with(resultid, db_mock)
        self.assertEqual(api_results.response.content_type,
                         "application/json; charset=UTF-8")

    @patch("frontend.api.v1_1.controllers.results.process_error")
    @patch("frontend.api.v1_1.controllers.results.validate_id")
    def test003_get_error(self, m_validate_id, m_process_error):
        db_mock = MagicMock()
        exception = Exception("test")
        m_validate_id.side_effect = exception
        resultid = "whatever"
        api_results.get(resultid, db_mock)
        m_process_error.assert_called_once_with(exception)


text:
const ArchivePlugin = require('webpack-archive-plugin')

module.exports = {
  outputDir: 'dist/static/',
  assetsDir: 'assets',
  filenameHashing: false,
  css: {
    extract: true
  },
  configureWebpack: {}
}

if (process.env.NODE_ENV === 'production') {
  module.exports.configureWebpack.plugins = [
    new ArchivePlugin()
  ]
}


text:
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# the lib use python logging can get it if the following is set in your
# Ansible config.

__metaclass__ = type

ANSIBLE_METADATA = {'status': ['preview'],
                    'supported_by': 'community',
                    'metadata_version': '1.1'}

DOCUMENTATION = '''
---
module: fortios_firewall_auth_portal
short_description: Configure firewall authentication portals in Fortinet's FortiOS and FortiGate.
description:
    - This module is able to configure a FortiGate or FortiOS by
      allowing the user to configure firewall feature and auth_portal category.
      Examples includes all options and need to be adjusted to datasources before usage.
      Tested with FOS v6.0.2
version_added: "2.8"
author:
    - Miguel Angel Munoz (@mamunozgonzalez)
    - Nicolas Thomas (@thomnico)
notes:
    - Requires fortiosapi library developed by Fortinet
    - Run as a local_action in your playbook
requirements:
    - fortiosapi>=0.9.8
options:
    host:
       description:
            - FortiOS or FortiGate ip address.
       required: true
    username:
        description:
            - FortiOS or FortiGate username.
        required: true
    password:
        description:
            - FortiOS or FortiGate password.
        default: ""
    vdom:
        description:
            - Virtual domain, among those defined previously. A vdom is a
              virtual instance of the FortiGate that can be configured and
              used as a different unit.
        default: root
    https:
        description:
            - Indicates if the requests towards FortiGate must use HTTPS
              protocol
        type: bool
        default: false
    firewall_auth_portal:
        description:
            - Configure firewall authentication portals.
        default: null
        suboptions:
            groups:
                description:
                    - Firewall user groups permitted to authenticate through this portal. Separate group names with spaces.
                suboptions:
                    name:
                        description:
                            - Group name. Source user.group.name.
                        required: true
            identity-based-route:
                description:
                    - Name of the identity-based route that applies to this portal. Source firewall.identity-based-route.name.
            portal-addr:
                description:
                    - Address (or FQDN) of the authentication portal.
            portal-addr6:
                description:
                    - IPv6 address (or FQDN) of authentication portal.
'''

EXAMPLES = '''
- hosts: localhost
  vars:
   host: "192.168.122.40"
   username: "admin"
   password: ""
   vdom: "root"
  tasks:
  - name: Configure firewall authentication portals.
    fortios_firewall_auth_portal:
      host:  "{{ host }}"
      username: "{{ username }}"
      password: "{{ password }}"
      vdom:  "{{ vdom }}"
      firewall_auth_portal:
        groups:
         -
            name: "default_name_4 (source user.group.name)"
        identity-based-route: "<your_own_value> (source firewall.identity-based-route.name)"
        portal-addr: "<your_own_value>"
        portal-addr6: "<your_own_value>"
'''

RETURN = '''
build:
  description: Build number of the fortigate image
  returned: always
  type: str
  sample: '1547'
http_method:
  description: Last method used to provision the content into FortiGate
  returned: always
  type: str
  sample: 'PUT'
http_status:
  description: Last result given by FortiGate on last operation applied
  returned: always
  type: str
  sample: "200"
mkey:
  description: Master key (id) used in the last call to FortiGate
  returned: success
  type: str
  sample: "id"
name:
  description: Name of the table used to fulfill the request
  returned: always
  type: str
  sample: "urlfilter"
path:
  description: Path of the table used to fulfill the request
  returned: always
  type: str
  sample: "webfilter"
revision:
  description: Internal revision number
  returned: always
  type: str
  sample: "17.0.2.10658"
serial:
  description: Serial number of the unit
  returned: always
  type: str
  sample: "FGVMEVYYQT3AB5352"
status:
  description: Indication of the operation's result
  returned: always
  type: str
  sample: "success"
vdom:
  description: Virtual domain used
  returned: always
  type: str
  sample: "root"
version:
  description: Version of the FortiGate
  returned: always
  type: str
  sample: "v5.6.3"

'''

from ansible.module_utils.basic import AnsibleModule

fos = None

def login(data):
    host = data['host']
    username = data['username']
    password = data['password']

    fos.debug('on')
    if 'https' in data and not data['https']:
        fos.https('off')
    else:
        fos.https('on')

    fos.login(host, username, password)

def filter_firewall_auth_portal_data(json):
    option_list = ['groups', 'identity-based-route', 'portal-addr',
                   'portal-addr6']
    dictionary = {}

    for attribute in option_list:
        if attribute in json and json[attribute] is not None:
            dictionary[attribute] = json[attribute]

    return dictionary

def firewall_auth_portal(data, fos):
    vdom = data['vdom']
    firewall_auth_portal_data = data['firewall_auth_portal']
    filtered_data = filter_firewall_auth_portal_data(firewall_auth_portal_data)
    return fos.set('firewall',
                   'auth-portal',
                   data=filtered_data,
                   vdom=vdom)

def fortios_firewall(data, fos):
    login(data)

    methodlist = ['firewall_auth_portal']
    for method in methodlist:
        if data[method]:
            resp = eval(method)(data, fos)
            break

    fos.logout()
    return not resp['status'] == "success", resp['status'] == "success", resp

def main():
    fields = {
        "host": {"required": True, "type": "str"},
        "username": {"required": True, "type": "str"},
        "password": {"required": False, "type": "str", "no_log": True},
        "vdom": {"required": False, "type": "str", "default": "root"},
        "https": {"required": False, "type": "bool", "default": "False"},
        "firewall_auth_portal": {
            "required": False, "type": "dict",
            "options": {
                "groups": {"required": False, "type": "list",
                           "options": {
                               "name": {"required": True, "type": "str"}
                           }},
                "identity-based-route": {"required": False, "type": "str"},
                "portal-addr": {"required": False, "type": "str"},
                "portal-addr6": {"required": False, "type": "str"}

            }
        }
    }

    module = AnsibleModule(argument_spec=fields,
                           supports_check_mode=False)
    try:
        from fortiosapi import FortiOSAPI
    except ImportError:
        module.fail_json(msg="fortiosapi module is required")

    global fos
    fos = FortiOSAPI()

    is_error, has_changed, result = fortios_firewall(module.params, fos)

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)

if __name__ == '__main__':
    main()


text:
package cc.aicode.e2e.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 功能说明: 标记实体为Excel实体
 * 参数说明:
 *
 * @author 管宜尧
 *         2013-11-28 下午4:40:00
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelEntity {
}


text:
Mif.TreeGrid.prototype.Node = Mif.TreeGrid.Node = new Class({

	Extends: Mif.Tree.Node

});


text:
class StratificationFactorsController < ApplicationController
  before_action :authenticate_user!
  before_action :find_editable_project_or_redirect
  before_action :redirect_blinded_users
  before_action :find_randomization_scheme_or_redirect
  before_action :find_stratification_factor_or_redirect, only: [:show, :edit, :update, :destroy]
  before_action :redirect_with_published_scheme, only: [:new, :create, :edit, :update, :destroy]

  layout "layouts/full_page_sidebar_dark"

  # GET /stratification_factors
  def index
    @stratification_factors = @randomization_scheme.stratification_factors.order(:name).page(params[:page]).per(40)
  end

  # # GET /stratification_factors/1
  # def show
  # end

  # GET /stratification_factors/new
  def new
    @stratification_factor = @randomization_scheme.stratification_factors
                                                  .where(project_id: @project.id, user_id: current_user.id).new
  end

  # # GET /stratification_factors/1/edit
  # def edit
  # end

  # POST /stratification_factors
  def create
    @stratification_factor = @randomization_scheme.stratification_factors
                                                  .where(project_id: @project.id, user_id: current_user.id)
                                                  .new(stratification_factor_params)
    if @stratification_factor.save
      redirect_to(
        [@project, @randomization_scheme, @stratification_factor],
        notice: "Stratification factor was successfully created."
      )
    else
      render :new
    end
  end

  # PATCH /stratification_factors/1
  def update
    if @stratification_factor.update(stratification_factor_params)
      redirect_to(
        [@project, @randomization_scheme, @stratification_factor],
        notice: "Stratification factor was successfully updated."
      )
    else
      render :edit
    end
  end

  # DELETE /stratification_factors/1
  def destroy
    @stratification_factor.destroy
    redirect_to(
      project_randomization_scheme_stratification_factors_path(@project, @randomization_scheme),
      notice: "Stratification factor was successfully deleted."
    )
  end

  private

  def find_randomization_scheme_or_redirect
    @randomization_scheme = @project.randomization_schemes.find_by(id: params[:randomization_scheme_id])
    redirect_without_randomization_scheme
  end

  def redirect_without_randomization_scheme
    return if @randomization_scheme
    empty_response_or_root_path(project_randomization_schemes_path(@project))
  end

  def find_stratification_factor_or_redirect
    @stratification_factor = @randomization_scheme.stratification_factors.find_by(id: params[:id])
    redirect_without_stratification_factor
  end

  def redirect_without_stratification_factor
    return if @stratification_factor
    empty_response_or_root_path(
      project_randomization_scheme_stratification_factors_path(@project, @randomization_scheme)
    )
  end

  def redirect_with_published_scheme
    return unless @randomization_scheme.published?
    flash[:alert] = "Stratification factors can't be created or edited on published randomization scheme."
    url = if @stratification_factor
            [@project, @randomization_scheme, @stratification_factor]
          else
            project_randomization_scheme_stratification_factors_path(@project, @randomization_scheme)
          end
    empty_response_or_root_path(url)
  end

  def stratification_factor_params
    params[:stratification_factor] ||= { blank: "1" }
    clean_calculation
    params.require(:stratification_factor).permit(:name, :stratifies_by_site, :calculation)
  end

  def clean_calculation
    return unless params[:stratification_factor].key?(:calculation)
    params[:stratification_factor][:calculation] = params[:stratification_factor][:calculation].to_s.strip
  end
end