text:
layout: docs
title: API
description: Video.JS API Docs - API settings based on the HTML5 video API
body_id: api
body_class: docs subpage
---

API
===
The Video.js API allows you to interact with the video through Javascript, whether the browser is playing the video through HTML5 video, Flash, or any other supported playback technologies.

Referencing the Player
----------------------
To use the API functions, you need access to the player object. Luckily this is easy to get. You just need to make sure your video tag has an ID. The example embed code has an ID of "example\_video_1". If you have multiple videos on one page, make sure every video tag has a unique ID.

    var myPlayer = _V_("example_video_1");

(If the player hasn't been initialized yet via the data-setup attribute or another method, this will also initialize the player.)

Wait Until the Player is Ready
------------------------------
The time it takes Video.js to set up the video and API will vary depending on the playback technology being used (HTML5 will often be much faster to load than Flash). For that reason we want to use the player's 'ready' function to trigger any code that requires the player's API.

    _V_("example_video_1").ready(function(){

      var myPlayer = this;

      // EXAMPLE: Start playing the video.
      myPlayer.play();

    });

API Methods
-----------
Now that you have access to a ready player, you can control the video, get values, or respond to video events using the following functions. The Video.js API function names follow the [HTML5 media API](http://www.w3.org/TR/html5/video.html). The main difference is that attributes which you would get or set on a video element using the equals sign ( `myVideoElement.currentTime = "120";` ), you would use a function argument syntax for Video.js ( `myPlayer.currentTime(120);` )

### play() ###
Start video playback. Returns the player object.

    myPlayer.play();

### pause() ###
Pause the video playback. Returns the player object

    myPlayer.pause();

### paused() ###
Returns false if the video is currently playing, or true otherwise. ()

    var isPaused = myPlayer.paused();
    var isPlaying = !myPlayer.paused();

### src(newSource) ###
The source function updates the video source. There are three types of variables you can pass as the argument.

**URL String**: A URL to the the video file. Use this method if you're sure the current playback technology (HTML5/Flash) can support the source you provide. Currently only MP4 files can be used in both HTML5 and Flash.

    myPlayer.src("http://www.example.com/path/to/video.mp4");

**Source Object (or element):** A javascript object containing information about the source file. Use this method if you want the player to determine if it can support the file using the type information.

    myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" });

**Array of Source Objects:** To provide multiple versions of the source so that it can be played using HTML5 across browsers you can use an array of source objects. Video.js will detect which version is supported and load that file.

    myPlayer.src([
      { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" },
      { type: "video/webm", src: "http://www.example.com/path/to/video.webm" },
      { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" }
    ]);

Returns the player object.

### currentTime() ###
Returns the current time of the video in seconds.

    var whereYouAt = myPlayer.currentTime();

### currentTime(seconds) // Type: Integer or Float ###
Seek to the supplied time (seconds). Returns the player object.

    myPlayer.currentTime(120); // 2 minutes into the video

### duration() ###
Returns the length in time of the video in seconds. NOTE: The video must have started loading before the duration can be known, and in the case of Flash, may not be known until the video starts playing.

    var howLongIsThis = myPlayer.duration();

### buffered() ###
Returns a [TimeRange](http://videojs.com/docs/glossary.html#timerange) object with sections of the video that have been downloaded. If you just want the percent of the video that's been downloaded, use bufferedPercent.

    var bufferedTimeRange = myPlayer.buffered(),

    // Number of different ranges of time have been buffered. Usually 1.
    numberOfRanges = bufferedTimeRange.length,

    // Time in seconds when the first range starts. Usually 0.
    firstRangeStart = bufferedTimeRange.start(0),

    // Time in seconds when the first range ends
    firstRangeEnd = bufferedTimeRange.end(0),

    // Length in seconds of the first time range
    firstRangeLength = firstRangeEnd - firstRangeStart;

### bufferedPercent() ###
Returns the percent (as a decimal) of the video that's been downloaded. 0 means none, 1 means all.

    var howMuchIsDownloaded = myPlayer.bufferedPercent();

### volume() ###
Returns the current volume of the video as a percent in decimal form. 0 is off (muted), 1.0 is all the way up, 0.5 is half way.

    var howLoudIsIt = myPlayer.volume();

### volume(percentAsDecimal) ###
Set the volume to the supplied percent (as a decimal between 0 and 1).

    myPlayer.volume(0.5); // Set volume to half

### width() ###
Returns the current width of the video in pixels.

    var howWideIsIt = myPlayer.width();

### width(pixels) ###
Change the width of the video to the supplied width in pixels. Returns the player object

    myPlayer.width(640);

### height() ###
Returns the current height of the video in pixels.

    var howTallIsIt = myPlayer.height();

### height(pixels) ###
Change the height of the video to the supplied height in pixels. Returns the player object

    myPlayer.height(480);

### size(width, height) ###
Changes the width and height of the video to the supplied width and height. This is more efficient if you're changing both width and height (only triggers the player's resize event once). Returns the player object.

    myPlayer.size(640,480);

### requestFullScreen() ###
Increase the size of the video to full screen. In some browsers, full screen is not supported natively, so it enters full window mode, where the video fills the browser window. In browsers and devices that support native full screen, sometimes the browser's default controls will be shown, and not the Video.js custom skin. This includes most mobile devices (iOS, Android) and older versions of Safari. Returns the player object.

    myPlayer.requestFullScreen();

### cancelFullScreen() ###
Return the video to its normal size after having been in full screen mode. Returns the player object.

    myPlayer.cancelFullScreen();

Events
------
You can attach event listeners to the player similarly to how you would for a video element.

    var myFunc = function(){
      var myPlayer = this;
      // Do something when the event is fired
    };
    myPlayer.addEvent("eventName", myFunc);

You can also remove the listeners later.

    myPlayer.removeEvent("eventName", myFunc);

### Event Types
List of player events you can add listeners for.

Name	Description

loadstart	Fired when the user agent begins looking for media data.

loadedmetadata	Fired when the player has initial duration and dimension information.

loadeddata	Fired when the player has downloaded data at the current playback position.

loadedalldata	Fired when the player has finished downloading the source data.

play	Fired whenever the media begins or resumes playback.

pause	Fired whenever the media has been paused.

timeupdate	Fired when the current playback position has changed. During playback this is fired every 15-250 milliseconds, depnding on the playback technology in use.

ended	Fired when the end of the media resource is reached. currentTime == duration

durationchange	Fired when the duration of the media resource is changed, or known for the first time.

progress	Fired while the user agent is downloading media data.

resize	Fired when the width and/or height of the video window changes.

volumechange	Fired when the volume changes.

error	Fired when there is an error in playback.

fullscreenchange	Fired when the player switches in or out of fullscreen mode.


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* This is a model class.
* This is the class which retrieves the data relating to the cart functions from the database
* and insert/ edit and delete data related to the cart table of the database
*/
class Cart_model extends CI_Model
{
	/**
	* This function returns cart item details from the database
	*
	* @param $user_id : This is the user id which the cart items should be retrieved for
	* @return cart item details  as an associative array
	*
	*/
    public function retrieve_cart_items($user_id) {
      $this->db->select("*");
	  $this->db->from('Cart');
	  $this->db->where('Cart.Reg_ID',$user_id);
	  $this->db->join('Items', 'Cart.Item_ID = Items.Item_ID');
	  $this->db->join('ItemImage', 'ItemImage.ItemID = Items.Item_ID');
	  $this->db->group_by('Cart.Cart_ID');
	  $this->db->order_by("Cart.AddedTime", "desc");
	  $query = $this->db->get();
	  return $query->result();
    }

    /**
	* This function returns cart total for a given user
	*
	* @param $user_id : This is the user id which the cart total should be retrieved for
	* @return cart total for the given user
	*
	*/
     public function retrieve_cart_total($user_id) {
      $this->db->select("SUM(Total) as subTot");
	  $this->db->from('Cart');
	  $this->db->where('Cart.Reg_ID',$user_id);
	  $this->db->group_by('Cart.Reg_ID');
	  $query = $this->db->get();
	  return $query->row('subTot');
    }

    /**
	* This function adds cart item details to the database
	*
	* @param $user_id : This is the user id which the cart items should be added for
	* @param $item_id : This is the item id which the cart items should be added for
	* @param $unit_price : This is the unit price of the item to be added
	* @return cart item details  as an associative array
	*
	*/
    public function add_cart_items($user_id, $item_id,$unit_price,$qty) {
     $data = array(
		   'Item_ID' => $item_id ,
		   'Reg_ID' => $user_id ,
		   'Quantity' => $qty ,
		   'UnitPrice' => $unit_price ,
		   'Total' => $unit_price*$qty
		);

		return $this->db->insert('Cart', $data);
    }

    /**
	* This function returns number of items available for a give itemID from the database
	*
	* @param $item_id : This is the item id which the item details should be retrieved for
	* @return item details  as an associative array
	*
	*/
    public function retrieve_available_qty($item_id) {
      $this->db->select("Medium_Quantity");
	  $this->db->from('Items');
	  $this->db->where('Items.Item_ID',$item_id);
	  $query = $this->db->get();
	  return $query->row('Medium_Quantity');
    }

    /**
	* This function updates the item table for a given itemID
	*
	* @param $item_id : This is the item id which the item details should be retrieved for
	* @param $qty : This is the quantity of the item which is going to be removed/added from/to the items table.
	* @param $avail_qty : This is the quantity of the item which is available currently.
	* @return id : number of rows affected
	*
	*/
    public function update_items($item_id,$avail_qty,$qty) {
     $data = array(
		   'Medium_Quantity' => $avail_qty-$qty
		);

     $this->db->where('Item_ID',$item_id);
	 $id = $this->db->update('Items', $data);

		return $id;
    }

    /**
    * This function removes items from the cart
    * @param $cartID : This is the cartID of the entry which is needed to be removed from the cart table
    * @return Nothing
    */
    public function remove_cart_items($cartID) {
    	$this->db->where('Cart_ID', $cartID);
		$this->db->delete('Cart');
    }

    /**
    * This function retrieves items count from the cart for a given user
    * @param $user_ID : This is the user_ID of the user which the cart items count should be retrieved for
    * @return Nothing
    */
    public function retrieve_cart_items_count($user_id) {
	  $this->db->where('Cart.Reg_ID',$user_id);
	  $this->db->from('Cart');
	  return $this->db->count_all_results();
    }

    /**
	* This function returns cart items in the carts of all users for admin purposes
	*
	* No paramters are accepted by this method
	* @return cart item details  as an associative array
	*
	*/
    public function retrieve_cart_items_admin() {
      $this->db->select("Cart.Cart_ID,Registered_Users.Name as uName,Items.Name as iName,Cart.UnitPrice,Cart.Quantity,Cart.Total,Cart.AddedTime,Items.Item_ID");
	  $this->db->from('Cart');
	  $this->db->join('Items', 'Cart.Item_ID = Items.Item_ID');
	  $this->db->join('Registered_Users', 'Registered_Users.Reg_ID = Cart.Reg_ID');
	  $this->db->group_by('Cart.Cart_ID');
	  $query = $this->db->get();
	  return $query->result();
    }

    public function get_id_by_name($name)
	{
		$this->db->select("Reg_ID");
	  	$this->db->from('Registered_Users');
	  	$this->db->where('Username',$name);
	  	$query = $this->db->get();

	 	return $query->result()[0]->Reg_ID;
	}

	public function getTotal($items)
    {
    	$total=0;
    	foreach ($items as $itm) {
    		$total = $total + $itm->Total;
    	}
    	return $total;
    }

    public function get_cart_items_only($user_id)
    {
    	$this->db->select("*");
	  	$this->db->from('Cart');
	  	$this->db->where('Reg_ID',$user_id);
	  	$query = $this->db->get();
	  	return $query->result();
    }

    public function insert_perchase($itm)
    {
    	$data = array(
		   'Item_ID' => $itm->Item_ID ,
		   'Reg_ID' => $itm->Reg_ID ,
		   'PurchasedTime' => $itm->AddedTime ,
		   'Total' => $itm->Total,
		   'Quantity' => $itm->Quantity,
		   'UnitPrice' => $itm->UnitPrice
		);
    	//var_dump($data);
		return $this->db->insert('Purchases', $data);

    }
}

redpajama_set_name: RedPajamaGithub


text:
import {Injector} from '../di/injector';
import {INJECTOR} from '../di/injector_compatibility';
import {InjectFlags} from '../di/interface/injector';
import {StaticProvider} from '../di/interface/provider';
import {R3Injector, createInjector} from '../di/r3_injector';
import {Type} from '../interface/type';
import {ComponentFactoryResolver as viewEngine_ComponentFactoryResolver} from '../linker/component_factory_resolver';
import {InternalNgModuleRef, NgModuleFactory as viewEngine_NgModuleFactory, NgModuleRef as viewEngine_NgModuleRef} from '../linker/ng_module_factory';
import {registerNgModuleType} from '../linker/ng_module_factory_registration';
import {NgModuleDef} from '../metadata/ng_module';
import {assertDefined} from '../util/assert';
import {stringify} from '../util/stringify';

import {ComponentFactoryResolver} from './component_ref';
import {getNgModuleDef} from './definition';
import {maybeUnwrapFn} from './util/misc_utils';

export interface NgModuleType<T = any> extends Type<T> { ngModuleDef: NgModuleDef<T>; }

const COMPONENT_FACTORY_RESOLVER: StaticProvider = {
  provide: viewEngine_ComponentFactoryResolver,
  useClass: ComponentFactoryResolver,
  deps: [viewEngine_NgModuleRef],
};

export class NgModuleRef<T> extends viewEngine_NgModuleRef<T> implements InternalNgModuleRef<T> {
  // tslint:disable-next-line:require-internal-with-underscore
  _bootstrapComponents: Type<any>[] = [];
  // tslint:disable-next-line:require-internal-with-underscore
  _r3Injector: R3Injector;
  injector: Injector = this;
  instance: T;
  destroyCbs: (() => void)[]|null = [];

  constructor(ngModuleType: Type<T>, public _parent: Injector|null) {
    super();
    const ngModuleDef = getNgModuleDef(ngModuleType);
    ngDevMode && assertDefined(
                     ngModuleDef,
                     `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`);

    this._bootstrapComponents = maybeUnwrapFn(ngModuleDef !.bootstrap);
    const additionalProviders: StaticProvider[] = [
      {
        provide: viewEngine_NgModuleRef,
        useValue: this,
      },
      COMPONENT_FACTORY_RESOLVER
    ];
    this._r3Injector = createInjector(
        ngModuleType, _parent, additionalProviders, stringify(ngModuleType)) as R3Injector;
    this.instance = this.get(ngModuleType);
  }

  get(token: any, notFoundValue: any = Injector.THROW_IF_NOT_FOUND,
      injectFlags: InjectFlags = InjectFlags.Default): any {
    if (token === Injector || token === viewEngine_NgModuleRef || token === INJECTOR) {
      return this;
    }
    return this._r3Injector.get(token, notFoundValue, injectFlags);
  }

  get componentFactoryResolver(): viewEngine_ComponentFactoryResolver {
    return this.get(viewEngine_ComponentFactoryResolver);
  }

  destroy(): void {
    ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
    const injector = this._r3Injector;
    !injector.destroyed && injector.destroy();
    this.destroyCbs !.forEach(fn => fn());
    this.destroyCbs = null;
  }
  onDestroy(callback: () => void): void {
    ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
    this.destroyCbs !.push(callback);
  }
}

export class NgModuleFactory<T> extends viewEngine_NgModuleFactory<T> {
  constructor(public moduleType: Type<T>) { super(); }

  create(parentInjector: Injector|null): viewEngine_NgModuleRef<T> {
    const moduleType = this.moduleType;
    const moduleRef = new NgModuleRef(moduleType, parentInjector);
    const ngModuleDef = getNgModuleDef(moduleType);
    ngModuleDef && ngModuleDef.id &&
        registerNgModuleType(ngModuleDef.id, moduleType as NgModuleType);
    return moduleRef;
  }
}


text:
{% extends 'base.html' %}
{% load compress %}

{% block title %}Forbidden - {{ block.super }}{% endblock %}

{% block css %}{% compress css %}{{ block.super }}{% endcompress %}{% endblock %}
{% block js %}{% compress js %}{{ block.super }}{% endcompress %}{% endblock %}

{% block usermenu %}{% endblock %}

{% block messages %}{% endblock %}

{% block content %}

Forbidden (HTTP 403)

The authenticity of your request couldn't be verified.

        {% if no_referer %}

This application requires a 'Referer' header to be sent by your browser and no such header was received. The header is necessary to ensure that your browser is not being hijacked by third parties. If you have configured your browser not to send 'Referer' headers, you will need to re-enable them before your request can be fulfilled.

        {% endif %}
        {% if DEBUG and reason %}

Reason given for failure:

{{ reason }}

        {% endif %}

{% endblock %}


text:
First of all, thanks for taking interest into contributing to this repository, below is what you need to know about the project.

### Getting Started

Clone the repo

`git clone https://github.com/logaretm/vee-validate.git`

Install npm dev dependencies

`npm install` or for better results use `yarn`

Check the `scripts` section of `package.json` for any npm scripts that might find useful.

### Folder Structure

As you can see we have:
- `src` contains the working code for the repository:
    - `exceptions`: contains any validator-specific exceptions.
    - `messages`: contains default English messages.
    - `plugins`: contains any sort of add-on behavior and rules, that may or not may be available at all times.
    - `rules`: contains validation rules that are available to the validator instances.
    - `utils`: contains small utility functions.
- `dist` contains the unminified and the minified build of the repository.
- `__tests__` contains the test files for the project, it uses [jest](https://facebook.github.io/jest/) for testing. it contains a similar folder structure as the `src` folder.

If you want to contribute to the docs you can find it [here](https://github.com/logaretm/vee-validate-docs).

### Pull Requests

- The `master` branch serves Vue 2.0 version of the plugin, for Vue 1.0 version check the `vue1` branch.
- Respect the ESlint rules, but we are open to any suggestions or alterations.
- You don't have to build the library with each pull request, but you will if you plan to test it manually. No need to submit it in the PR to avoid as much conflicts as possible.
- The clearer the PR title is, the faster it will get merged.
- Make sure that your PR is up to date with the branch you are targeting, use git rebase for this.
- Unfinished/In-Progress PRs should have `[WIP]` prefix to them.
- Make sure to mention which issues are being fixed by the PR so they can be closed properly.

### Source Code

Currently we are using ES2015 (ES6) for the source code, using Babel and Webpack to convert it to ES5, the available builds are: non-minified and minified.

Also we are using ESlint for code style, it based of airbnb config but with few modifications, please respect them as much as you can.

### Testing

Each test file represents a unit test to the corresponding file in the src folder.

To run the tests:

`npm test`

Currently I'm not testing the directive and the mixin, I will work on adding those tests later if I can, help will be appreciated if we can test the other stuff.

### Building

Use `npm run build` to build the project both minified and unminified versions.


text:
package org.hillview.dataset.remoting;

import org.hillview.dataset.api.ControlMessage;
import java.io.Serializable;

/**
 * Wrap a ControlMessage object to be sent to a remote node
 */
public class ManageOperation extends RemoteOperation implements Serializable {
    public final ControlMessage message;
    public ManageOperation(final ControlMessage message) {
        this.message = message;
    }
}


text:
package ch.epfl.bluebrain.nexus.iam.client

import akka.actor.ActorSystem
import akka.http.scaladsl.client.RequestBuilding._
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.unmarshalling.FromEntityUnmarshaller
import akka.stream.scaladsl.Sink
import akka.stream.{ActorMaterializer, Materializer}
import cats.effect.{Effect, IO, LiftIO}
import cats.syntax.applicativeError._
import cats.syntax.apply._
import cats.syntax.flatMap._
import cats.syntax.functor._
import ch.epfl.bluebrain.nexus.commons.http.HttpClient
import ch.epfl.bluebrain.nexus.commons.http.HttpClient._
import ch.epfl.bluebrain.nexus.commons.http.JsonLdCirceSupport._
import ch.epfl.bluebrain.nexus.commons.rdf.syntax._
import ch.epfl.bluebrain.nexus.iam.client.IamClientError.{Forbidden, Unauthorized, UnknownError, UnmarshallingError}
import ch.epfl.bluebrain.nexus.iam.client.config.IamClientConfig
import ch.epfl.bluebrain.nexus.iam.client.types._
import ch.epfl.bluebrain.nexus.iam.client.types.events.Event
import ch.epfl.bluebrain.nexus.iam.client.types.events.Event.{AclEvent, PermissionsEvent, RealmEvent}
import ch.epfl.bluebrain.nexus.rdf.Iri.{AbsoluteIri, Path}
import io.circe.generic.auto._
import io.circe.syntax._
import io.circe.{DecodingFailure, Json, ParsingFailure}
import journal.Logger

import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, Future}
import scala.reflect.ClassTag

class IamClient[F[_]] private[client] (
    source: EventSource[Event],
    config: IamClientConfig,
    aclsClient: HttpClient[F, AccessControlLists],
    callerClient: HttpClient[F, Caller],
    permissionsClient: HttpClient[F, Permissions],
    jsonClient: HttpClient[F, Json]
)(implicit F: Effect[F], mt: Materializer) {

  /**
    * Retrieve the current ''acls'' for some particular ''path''.
    *
    * @param path        the target resource
    * @param ancestors   matches only the exact ''path'' (false) or its ancestors also (true)
    * @param self        matches only the caller identities
    * @param credentials an optionally available token
    */
  def acls(path: Path, ancestors: Boolean = false, self: Boolean = false)(
      implicit credentials: Option[AuthToken]): F[AccessControlLists] = {
    val endpoint = config.aclsIri + path
    val req      = requestFrom(endpoint, Query("ancestors" -> ancestors.toString, "self" -> self.toString))
    aclsClient(req)
  }

  /**
    * Retrieve the identities on a [[Caller]] object from the implicitly optional [[AuthToken]]
    *
    */
  def identities(implicit credentials: Option[AuthToken]): F[Caller] = {
    credentials
      .map(_ => callerClient(requestFrom(config.identitiesIri)))
      .getOrElse(F.pure(Caller.anonymous))
  }

  /**
    * Fetch available permissions.
    *
    * @param credentials an optionally available token
    * @return available permissions
    */
  def permissions(implicit credentials: Option[AuthToken]): F[Set[Permission]] =
    permissionsClient(requestFrom(config.permissionsIri)).map(_.permissions)

  /**
    * Replace ACL at a given path.
    *
    * @param path       [[Path]] for which to replace the ACL
    * @param acl        updated [[AccessControlList]]
    * @param rev        current revision
    * @param credentials an optionally available token
    */
  def putAcls(path: Path, acl: AccessControlList, rev: Option[Long] = None)(
      implicit credentials: Option[AuthToken]): F[Unit] = {
    implicit val _ = config
    val endpoint   = config.aclsIri + path
    val entity     = HttpEntity(ContentTypes.`application/json`, acl.asJson.noSpaces)
    val query      = rev.map(r => Query("rev" -> r.toString)).getOrElse(Query.Empty)
    val request    = Put(endpoint.toAkkaUri.withQuery(query), entity)
    val requestWithCredentials =
      credentials.map(token => request.addCredentials(OAuth2BearerToken(token.value))).getOrElse(request)
    jsonClient(requestWithCredentials) *> F.unit
  }

  /**
    * Checks the presence of a specific ''permission'' on a particular ''path''.
    *
    * @param path        the target resource
    * @param permission  the permission to check
    * @param credentials an optionally available token
    */
  def hasPermission(path: Path, permission: Permission)(implicit credentials: Option[AuthToken]): F[Boolean] =
    acls(path, ancestors = true, self = true).flatMap { acls =>
      val found = acls.value.exists { case (_, acl) => acl.value.permissions.contains(permission) }
      if (found) F.pure(true)
      else F.pure(false)
    }

  /**
    * It applies the provided function ''f'' to the ACLs Server-sent events (SSE)
    *
    * @param f      the function that gets executed when a new [[AclEvent]] appears
    * @param offset the optional offset from where to start streaming the events
    */
  def aclEvents(f: AclEvent => F[Unit], offset: Option[String] = None)(implicit cred: Option[AuthToken]): Unit = {
    val pf: PartialFunction[Event, F[Unit]] = { case ev: AclEvent => f(ev) }
    events(config.aclsIri + "events", pf, offset)
  }

  /**
    * It applies the provided function ''f'' to the Permissions Server-sent events (SSE)
    *
    * @param f      the function that gets executed when a new [[PermissionsEvent]] appears
    * @param offset the optional offset from where to start streaming the events
    */
  def permissionEvents(f: PermissionsEvent => F[Unit], offset: Option[String] = None)(
      implicit cred: Option[AuthToken]): Unit = {
    val pf: PartialFunction[Event, F[Unit]] = { case ev: PermissionsEvent => f(ev) }
    events(config.permissionsIri + "events", pf, offset)
  }

  /**
    * It applies the provided function ''f'' to the Realms Server-sent events (SSE)
    *
    * @param f      the function that gets executed when a new [[RealmEvent]] appears
    * @param offset the optional offset from where to start streaming the events
    */
  def realmEvents(f: RealmEvent => F[Unit], offset: Option[String] = None)(implicit cred: Option[AuthToken]): Unit = {
    val pf: PartialFunction[Event, F[Unit]] = { case ev: RealmEvent => f(ev) }
    events(config.realmsIri + "events", pf, offset)
  }

  /**
    * It applies the provided function ''f'' to the Server-sent events (SSE)
    *
    * @param f      the function that gets executed when a new [[Event]] appears
    * @param offset the optional offset from where to start streaming the events
    */
  def events(f: Event => F[Unit], offset: Option[String] = None)(implicit cred: Option[AuthToken]): Unit = {
    val pf: PartialFunction[Event, F[Unit]] = { case ev: Event => f(ev) }
    events(config.internalIri + "events", pf, offset)
  }

  private def events(iri: AbsoluteIri, f: PartialFunction[Event, F[Unit]], offset: Option[String])(
      implicit cred: Option[AuthToken]): Unit =
    source(iri, offset)
      .mapAsync(1) { event =>
        f.lift(event) match {
          case Some(evaluated) => F.toIO(evaluated).unsafeToFuture()
          case _               => Future.unit
        }
      }
      .to(Sink.ignore)
      .mapMaterializedValue(_ => ())
      .run()

  private def requestFrom(iri: AbsoluteIri, query: Query = Query.Empty)(implicit credentials: Option[AuthToken]) = {
    val request = Get(iri.toAkkaUri.withQuery(query))
    credentials.map(token => request.addCredentials(OAuth2BearerToken(token.value))).getOrElse(request)
  }

}

// $COVERAGE-OFF$
object IamClient {

  private def httpClient[F[_], A: ClassTag](
      implicit L: LiftIO[F],
      F: Effect[F],
      ec: ExecutionContext,
      mt: Materializer,
      cl: UntypedHttpClient[F],
      um: FromEntityUnmarshaller[A]
  ): HttpClient[F, A] = new HttpClient[F, A] {
    private val logger = Logger(s"IamHttpClient[${implicitly[ClassTag[A]]}]")

    override def apply(req: HttpRequest): F[A] =
      cl.apply(req).flatMap { resp =>
        resp.status match {
          case StatusCodes.Unauthorized =>
            cl.toString(resp.entity).flatMap { entityAsString =>
              F.raiseError[A](Unauthorized(entityAsString))
            }
          case StatusCodes.Forbidden =>
            logger.error(s"Received Forbidden when accessing '${req.method.name()} ${req.uri.toString()}'.")
            cl.toString(resp.entity).flatMap { entityAsString =>
              F.raiseError[A](Forbidden(entityAsString))
            }
          case other if other.isSuccess() =>
            val value = L.liftIO(IO.fromFuture(IO(um(resp.entity))))
            value.recoverWith {
              case pf: ParsingFailure =>
                logger.error(
                  s"Failed to parse a successful response of '${req.method.name()} ${req.getUri().toString}'.")
                F.raiseError[A](UnmarshallingError(pf.getMessage()))
              case df: DecodingFailure =>
                logger.error(
                  s"Failed to decode a successful response of '${req.method.name()} ${req.getUri().toString}'.")
                F.raiseError(UnmarshallingError(df.getMessage()))
            }
          case other =>
            cl.toString(resp.entity).flatMap { entityAsString =>
              logger.error(
                s"Received '${other.value}' when accessing '${req.method.name()} ${req.uri.toString()}', response entity as string: '$entityAsString.'")
              F.raiseError[A](UnknownError(other, entityAsString))
            }
        }
      }

    override def discardBytes(entity: HttpEntity): F[HttpMessage.DiscardedEntity] =
      cl.discardBytes(entity)

    override def toString(entity: HttpEntity): F[String] =
      cl.toString(entity)
  }

  /**
    * Constructs an ''IamClient[F]'' from implicitly available instances of [[IamClientConfig]], [[ActorSystem]] and [[Effect]].
    *
    * @tparam F the effect type
    * @return a new [[IamClient]]
    */
  final def apply[F[_]: Effect](implicit config: IamClientConfig, as: ActorSystem): IamClient[F] = {
    implicit val mt: ActorMaterializer        = ActorMaterializer()
    implicit val ec: ExecutionContextExecutor = as.dispatcher
    implicit val ucl: UntypedHttpClient[F]    = HttpClient.untyped[F]

    val aclsClient: HttpClient[F, AccessControlLists] = httpClient[F, AccessControlLists]
    val callerClient: HttpClient[F, Caller]           = httpClient[F, Caller]
    val permissionsClient: HttpClient[F, Permissions] = httpClient[F, Permissions]
    val jsonClient: HttpClient[F, Json]               = httpClient[F, Json]
    val sse: EventSource[Event]                       = EventSource[Event](config)
    new IamClient(sse, config, aclsClient, callerClient, permissionsClient, jsonClient)
  }
}
// $COVERAGE-ON$


text:
require 'test/unit'

begin
  require File.dirname(__FILE__) + '/../../../../config/boot'
  require 'active_record'
  require File.dirname(__FILE__) + '/../../chronic/lib/chronic'
  require 'validates_as_time'
rescue LoadError
  require 'rubygems'
  require 'activerecord'
  require 'chronic'
  require File.dirname(__FILE__) + '/../lib/validates_as_time'
end

class TestRecord < ActiveRecord::Base
  def self.columns; []; end
  attr_accessor :t0, :t1, :t2, :t3, :t4, :t5, :t6, :t7, :t8
  validates_as_time :t0
  validates_as_time :t1, :t2, :format => "%Y %j %H:%M", :allow_nil => false
  validates_as_time :t3, :default => Chronic.parse("next year")
  validates_as_time :t4, :format => "%Y-%m-%d"
  validates_as_time :t5, :message => "is not loved"
  validates_as_time :t6, :minimum => Chronic.parse("2008-01-01 00:00"),
                         :maximum => Chronic.parse("2009-01-01 00:00")
  validates_as_time :t7, :minimum => Chronic.parse("2008-01-01 00:00"),
                         :maximum => Chronic.parse("2009-01-01 00:00"),
                         :too_early => "is too early mate",
                         :too_late => "is too late mate"
  validates_as_time :t8, :allow_nil => false, :blank => "can't be empty"
end

class ValidatesAsTimeTest < Test::Unit::TestCase

  def test_set_string_reflected_in_get_time
    t = TestRecord.new
    t.t0_string = Chronic.parse("2008-01-01 23:59").strftime("%Y-%m-%d %H:%M")
    assert_equal Chronic.parse("2008-01-01 23:59").strftime("%Y-%m-%d %H:%M"),
                 t.t0.strftime("%Y-%m-%d %H:%M"),
                 "it should reflect a set string value via get time value"
  end

  def test_set_string_reflected_in_get_string
    t = TestRecord.new
    t.t0_string = Chronic.parse("2008-01-01 23:59").strftime("%Y-%m-%d %H:%M")
    assert_equal Chronic.parse("2008-01-01 23:59").strftime("%Y-%m-%d %H:%M"),
                 t.t0_string,
                 "it should reflect a set string value via get string value"
  end

  def test_set_time_reflected_in_get_time
    assert_equal Chronic.parse("2008-01-01 23:59").strftime("%Y-%m-%d %H:%M"),
                 TestRecord.new(:t0 => Chronic.parse("2008-01-01 23:59")).t0.strftime("%Y-%m-%d %H:%M"),
                 "it should reflect a set time value via get time value"
  end

  def test_set_time_reflected_in_get_string
    assert_equal Chronic.parse("2008-01-01 23:59").strftime("%Y-%m-%d %H:%M"),
                 TestRecord.new(:t0 => Chronic.parse("2008-01-01 23:59")).t0_string,
                 "it should reflect a set time value via get string value"
  end

  def test_invalid_format
    t = TestRecord.new(:t0_string => "2008-01-99 23:59")
    t.valid?
    assert_equal "is invalid", t.errors[:t0], "invalid format"
    assert_equal nil, t.t0, "time value is not affected by invalid string format after create"
    assert_equal "2008-01-99 23:59", t.t0_string, "string value responds back with given invald string format after create"

    t = TestRecord.new(:t0_string => "2008-01-01 23:59")
    t.t0_string = "2008-01-99 23:59"
    t.valid?
    assert_equal "is invalid", t.errors[:t0], "invalid format"
    assert_equal Chronic.parse("2008-01-01 23:59").strftime("%Y %j %H:%M"),
                 t.t0.strftime("%Y %j %H:%M"),
                 "time value is not affected by invalid string format after modify"
    assert_equal "2008-01-99 23:59", t.t0_string, "string value responds back with given invald string format after modify"
  end

  def test_multi_attributes
    assert_equal Chronic.parse("now").strftime("%Y %j %H:%M"),
                 TestRecord.new.t1_string,
                 "it should work with multiple attributes #1"
    assert_equal Chronic.parse("now").strftime("%Y %j %H:%M"),
                 TestRecord.new.t2_string,
                 "it should work with multiple attributes #2"
  end

  def test_option_default
    assert_equal Chronic.parse("now").strftime("%Y %j %H:%M"),
                 Chronic.parse(TestRecord.new.t0_string).strftime("%Y %j %H:%M"),
                 "it should work with a default default"
    assert_equal Chronic.parse("next year").year,
                 Chronic.parse(TestRecord.new.t3_string).year,
                "it should work with a custom default"
  end

  def test_option_format
    assert TestRecord.new.t0_string =~ /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/, "it should work with a default format"
    assert TestRecord.new.t4_string =~ /^\d{4}-\d{2}-\d{2}$/, "it should work with a custom format"
  end

  def test_option_message
    t = TestRecord.new(:t0_string => "2008-99-99 23:59")
    t.valid?
    assert_equal "is invalid", t.errors[:t0], "it should work with a default error message"
    t = TestRecord.new(:t5_string => "2008-99-99 23:59")
    t.valid?
    assert_equal "is not loved", t.errors[:t5], "it should work with a custom error message"
  end

  def test_option_minimum
    t = TestRecord.new(:t6_string => "2008-02-02 02:02")
    t.valid?
    assert t.errors[:t6].nil?, "it should allow the value when it's later than a custom minimum time"
    t = TestRecord.new(:t6_string => "2007-12-31 23:59")
    t.valid?
    assert_equal "cannot be before 2008-01-01 00:00", t.errors[:t6], "it should not allow the value when it's earlier than a custom minimum time"
  end

  def test_option_maximum
    t = TestRecord.new(:t6_string => "2008-02-02 02:02")
    t.valid?
    assert t.errors[:t6].nil?, "it should allow the value when it's earlier than a custom maximum time"
    t = TestRecord.new(:t6_string => "2009-01-01 00:00")
    t.valid?
    assert_equal "cannot be on or after 2009-01-01 00:00", t.errors[:t6], "it should not allow the value when it's later than a custom maximum time"
  end

  def test_option_too_early
    t = TestRecord.new(:t7_string => "2007-12-31 23:59")
    t.valid?
    assert_equal "is too early mate", t.errors[:t7], "it should work with a custom too_early message"
  end

  def test_option_too_late
    t = TestRecord.new(:t7_string => "2009-01-01 00:00")
    t.valid?
    assert_equal "is too late mate", t.errors[:t7], "it should work with a custom too_late message"
  end

  def test_option_allow_nil?
    t = TestRecord.new
    t.valid?
    assert t.errors[:t0].nil?, "it should allow nil values by default"
    assert_equal "can't be blank", t.errors[:t1], "it should not allow nil values when custom allow_nil option is set to false"
  end

  def test_option_blank
    t = TestRecord.new
    t.valid?
    assert_equal "can't be empty",
                 t.errors[:t8],
                 "it should show a custom blank message when the custom allow_nil option is set to false and the value is nil"
  end

end


text:
__git_files () {
    _wanted files expl 'local files' _files
}

gfork() {
  local branch=$1
  git checkout -b $branch origin/$branch
}

# gets the url for the given fork
__addremote_url() {
  # shellcheck disable=SC2039
  local fork remote current
  fork="$1"
  if ! git config --get remote.origin.url > /dev/null 2>&1; then
    echo "A remote called 'origin' doesn't exist. Aborting." >&2
    return 1
  fi
  remote="$(git config --get remote.origin.url)"
  current="$(echo "$remote" | sed -e 's/.*github.com\://' -e 's/\/.*//')"
  echo "$remote" | sed -e "s/$current/$fork/"
}

# adds a remote
# shellcheck disable=SC2039
add-remote() {
  # shellcheck disable=SC2039
  local fork="$1" name="$2" url
  test -z "$name" && name="$fork"
  url="$(__addremote_url "$fork")" || return 1
  git remote add "$name" "$url"
}

# adds an upstream remote
# shellcheck disable=SC2039
add-upstream() {
  add-remote "$1" "upstream"
}

git_update() {
	# Update repository.
	if (`git branch -r| grep -q origin`); then
		git pull origin master;
	fi
	if (`git branch -r| grep -q upstream`); then
		git fetch upstream;
		git merge upstream/master
	fi
}


text:
package com.actquizmobilenativeapp.pages;

import java.util.List;

import com.qmetry.qaf.automation.ui.WebDriverBaseTestPage;
import com.qmetry.qaf.automation.ui.annotations.FindBy;
import com.qmetry.qaf.automation.ui.api.PageLocator;
import com.qmetry.qaf.automation.ui.api.WebDriverTestPage;
import com.qmetry.qaf.automation.ui.webdriver.QAFWebElement;

public class QuestionsTestPage extends WebDriverBaseTestPage<WebDriverTestPage> {

	@FindBy(locator = "questions.btn.show")
	private QAFWebElement questionsBtnShow;
	@FindBy(locator = "questions.lbl.question")
	private QAFWebElement questionsLblQuestion;
	@FindBy(locator = "questions.lst.options")
	private List<QAFWebElement> questionsLstOptions;
	@FindBy(locator = "questions.lst.no.question")
	private List<QAFWebElement> questionsLstNoQuestion;
	//@FindBy(locator = "questions.header")
	private HeaderBar questionsHeader=new HeaderBar();

	public static int count=0;

	@Override
	protected void openPage(PageLocator pageLocator, Object... args) {
	}

	public QAFWebElement getQuestionsBtnShow() {
		return questionsBtnShow;
	}

	public QAFWebElement getQuestionsLblQuestion() {
		return questionsLblQuestion;
	}

	public List<QAFWebElement> getQuestionsLstOptions() {
		return questionsLstOptions;
	}

	public List<QAFWebElement> getQuestionsLstNoQuestion() {
		return questionsLstNoQuestion;
	}

	public HeaderBar getQuestionsHeader() {
		return questionsHeader;
	}

	public void verifyQuestionsPage() {
		getQuestionsLblQuestion().waitForPresent();
		getQuestionsLblQuestion().verifyPresent();
	}

	public void getQuestionsInfo() {
		getQuestionsLblQuestion().getText();
	}

	public void setMark(String markType) {
		getQuestionsHeader().markQuestion(markType);
	}

	public void verifyAndGetQuestionAndSetMark(String markType) {
		if(markType.contentEquals("Mastered")) {
			count=count+1;
		}
		//QAFTestBase.pause(5000);

		verifyQuestionsPage();
		getQuestionsInfo();
		setMark(markType);
	}

	public void getNextQuestion(int index) {
		System.out.println("Total questions present: "+getQuestionsLstNoQuestion().size());
		System.out.println("Question Number: "+getQuestionsLstNoQuestion().get(index).getText());
		getQuestionsLstNoQuestion().get(index).click();
	}

	public void navigateBackWithoutFinish() {
		getQuestionsHeader().getHeaderBtnBack().click();
		getQuestionsHeader().getHeaderAlertExitYes().click();
	}

	public void setCountZero() {
		count=0;
	}
}


text:
package net.mcft.copy.core.client;

import net.minecraft.client.renderer.Tessellator;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class GuiTextureResource extends ModResource {

	public final int defaultWidth;
	public final int defaultHeight;

	public GuiTextureResource(String modid, String location, int defaultWidth, int defaultHeight) {
		super(modid, "textures/gui/" + location + ".png");
		this.defaultWidth = defaultWidth;
		this.defaultHeight = defaultHeight;
	}

	/** Draws part of the texture to the screen. */
	public void drawQuad(int x, int y, int u, int v, int w, int h, float zLevel) {
		float scaleX = 1.0F / defaultWidth;
		float scaleY = 1.0F / defaultHeight;
		Tessellator tess = Tessellator.instance;
		tess.startDrawingQuads();
		tess.addVertexWithUV(x,     y + h, zLevel,  u      * scaleX, (v + h) * scaleY);
		tess.addVertexWithUV(x + w, y + h, zLevel, (u + w) * scaleX, (v + h) * scaleY);
		tess.addVertexWithUV(x + w, y,     zLevel, (u + w) * scaleX,  v      * scaleY);
		tess.addVertexWithUV(x,     y,     zLevel,  u      * scaleX,  v      * scaleY);
		tess.draw();
	}

	/** Draws part of the texture to the screen. */
	public void drawQuad(int x, int y, int u, int v, int w, int h) {
		drawQuad(x, y, u, v, w, h, 0);
	}

}


text:
package cognitivej.vision.face.task;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.util.HashMap;

public class FaceLandmarks {
    public Point pupilLeft, pupilRight, mouthLeft, mouthRight, eyebrowLeftOuter, eyebrowLeftInner, eyeLeftOuter, eyeLeftTop, eyeLeftBottom, eyeLeftInner,
            eyebrowRightInner, eyebrowRightOuter, eyeRightInner, eyeRightTop, eyeRightBottom, eyeRightOuter, noseRootLeft, noseRootRight, noseLeftAlarTop,
            noseRightAlarTop, noseTip, noseLeftAlarOutTip, noseRightAlarOutTip, mupperLipTop, upperLipTop, upperLipBottom, underLipTop, underLipBottom;

    public HashMap<String, Point> landmarks() {
        return new HashMap<String, Point>() {{
            put("pupilLeft", pupilLeft);
            put("pupilRight", pupilRight);
            put("mouthLeft", mouthLeft);
            put("mouthRight", mouthRight);
            put("eyebrowLeftOuter", eyebrowLeftOuter);
            put("eyebrowLeftInner", eyebrowLeftInner);
            put("eyeLeftOuter", eyeLeftOuter);
            put("eyeLeftTop", eyeLeftTop);
            put("eyeLeftBottom", eyeLeftBottom);
            put("eyeLeftInner", eyeLeftInner);
            put("eyebrowRightInner", eyebrowRightInner);
            put("eyebrowRightOuter", eyebrowRightOuter);
            put("eyeRightInner", eyeRightInner);
            put("eyeRightTop", eyeRightTop);
            put("eyeRightBottom", eyeRightBottom);
            put("eyeRightOuter", eyeRightOuter);
            put("noseRootLeft", noseRootLeft);
            put("noseRootRight", noseRootRight);
            put("noseLeftAlarTop", noseLeftAlarTop);
            put("noseRightAlarTop", noseRightAlarTop);
            put("noseTip", noseTip);
            put("noseLeftAlarOutTip", noseLeftAlarOutTip);
            put("noseRightAlarOutTip", noseRightAlarOutTip);
            put("mupperLipTop", mupperLipTop);
            put("upperLipTop", upperLipTop);
            put("upperLipBottom", upperLipBottom);
            put("underLipTop", underLipTop);
            put("underLipBottom", underLipBottom);
        }};
    }

    public class Point {
        public double x, y;

        public java.awt.Point asAwtPoint() {
            return new java.awt.Point((int) x, (int) y);
        }

        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
        }
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
    }
}


text:
// Copyright 2015-2025 Finsa S.p.A. <finsa@finsa.it>
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at:
//
// "http://www.apache.org/licenses/LICENSE-2.0"
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under
// the License.

using Finsa.Caravan.Common;
using Finsa.Caravan.Common.Logging;
using Finsa.Caravan.WebApi.Core;
using Finsa.Caravan.WebApi.Middlewares.Models;
using Microsoft.Owin;
using PommaLabs.KVLite.Core;
using PommaLabs.Thrower;
using System.IO.Compression;
using System.Threading.Tasks;

namespace Finsa.Caravan.WebApi.Middlewares
{
    /// <summary>
    ///   Middleware che si occupa della compressione del contenuto della response, se e solo se la
    ///   request ha dichiarato di accettare una risposta compressa (Accept-Enconding uguale a gzip o deflate).
    ///
    ///   Se la request supporta sia gzip che deflate, allora viene data precedenza a gzip.
    /// </summary>
    public sealed class HttpCompressionMiddleware : OwinMiddleware
    {
        /// <summary>
        ///   Header di codifica usato per indicare la compressione con GZIP.
        /// </summary>
        private const string GZipEncoding = "gzip";

        /// <summary>
        ///   Le impostazioni del componente.
        /// </summary>
        private readonly Settings _settings;

        /// <summary>
        ///   Il log.
        /// </summary>
        private readonly ICaravanLog _log;

        /// <summary>
        ///   Inizializza il componente usato per la compressione.
        /// </summary>
        /// <param name="next">Un riferimento al prossimo componente della pipeline.</param>
        /// <param name="settings">Le impostazioni del componente.</param>
        /// <param name="log">Il log su cui scrivere eventuali messaggi.</param>
        public HttpCompressionMiddleware(OwinMiddleware next, Settings settings, ICaravanLog log)
            : base(next)
        {
            // Preconditions
            Raise.ArgumentNullException.IfIsNull(settings, nameof(settings));
            Raise.ArgumentNullException.IfIsNull(log, nameof(log));

            _settings = settings;
            _log = log;
        }

        /// <summary>
        ///   Applica una rapida compressione alla risposta HTTP se il client ha specificato
        ///   esplicitamente che è in grado di accettare risposte compresse.
        /// </summary>
        /// <param name="context">Il contesto di Owin.</param>
        /// <returns>Task per proseguire nella catena di middleware.</returns>
        public async override Task Invoke(IOwinContext context)
        {
            // Recupero le informazioni sulla response.
            var owinRequest = context.Request;
            var owinResponse = context.Response;

            // Se la richiesta risulta tra quelle da ignorare, devo fare poco e niente.
            var uriIsIgnored = context.Environment.ContainsKey(Constants.UriIgnoredVariable);
            if (uriIsIgnored)
            {
                // Eseguo il prossimo componente e termino qui l'esecuzione.
                await Next.Invoke(context);
                return;
            }

            // Provo a decomprimere la request, nel caso sia compressa.
            var oldRequestBody = owinRequest.Body;
            var hasOldRequestBody = await TryDecompressRequestAsync(owinRequest);

            // Valuto se posso applicare un algoritmo di compressione osservando gli header della
            // richiesta HTTP (leggo l'header Accept-Encoding).
            var acceptEncoding = owinRequest.Headers.Get("Accept-Encoding");

            // Se l'header non è presente, allora NON devo applicare alcuna compressione.
            if (string.IsNullOrWhiteSpace(acceptEncoding))
            {
                _log.Debug($"Client has not specified the Accept-Enconding header - No compression will be applied");
                await Next.Invoke(context);
                return;
            }

            // Se GZIP o DEFLATE non sono tra gli algoritmi accettati, allora NON devo applicare
            // alcuna compressione della response.
            if (!acceptEncoding.Contains(GZipEncoding))
            {
                _log.Debug($"Client does not accept a compressed response - Accept-Enconding: {acceptEncoding}");
                await Next.Invoke(context);
                return;
            }

            if (_log.IsDebugEnabled)
            {
                _log.Debug($"Client accepts GZIP enconding - Accept-Enconding: {acceptEncoding}");
            }

            // Eseguo il successivo componente di middleware.
            await Next.Invoke(context);

            // Se lo stream può essere compresso, allora lo comprimo dentro il body iniziale.
            // Altrimenti, non eseguo ulteriori copie e restituisco al chiamante lo stream temporaneo
            // creato sopra.
            if (CanCompressResponse(owinResponse))
            {
                // Rewinds the current memory stream.
                var oldResponseBody = owinResponse.Body;
                oldResponseBody.Position = 0;

                // Replaces the response stream with a new compressed memory stream, caller will
                // dispose old stream.
                var compressed = new PooledMemoryStream();
                owinResponse.Body = compressed;

                owinResponse.Headers["Content-Encoding"] = GZipEncoding;
                using (var gzipStream = new GZipStream(compressed, CompressionLevel.Fastest, true))
                {
                    await oldResponseBody.CopyToAsync(gzipStream);
                }

                // Riavvolgo la posizione dello stream compresso.
                compressed.Position = 0;
            }

            // Ripristino i vecchi stream contenenti la request e la response, se presenti.
            if (hasOldRequestBody)
            {
                owinRequest.Body.Dispose();
                owinRequest.Body = oldRequestBody;
            }
        }

        /// <summary>
        ///   Prova a decomprimere il body della request, nel caso sia compresso.
        /// </summary>
        /// <param name="owinRequest">La request di OWIN.</param>
        private async Task<bool> TryDecompressRequestAsync(IOwinRequest owinRequest)
        {
            // Valuto se posso applicare un algoritmo di decompressione osservando gli header della
            // richiesta HTTP (leggo l'header Content-Encoding).
            var contentEncoding = owinRequest.Headers["Content-Enconding"];

            // Se l'header non è presente, allora NON devo applicare alcuna compressione.
            if (string.IsNullOrWhiteSpace(contentEncoding))
            {
                _log.Debug($"Client has not specified the Content-Enconding header - Request is not compressed");
                return false;
            }

            // Il primo requisito è che lo stream possa essere letto e riavvolto.
            var owinRequestBody = owinRequest.Body;
            if (!owinRequestBody.CanRead || !owinRequestBody.CanSeek)
            {
                _log.Debug("Request body cannot be read or its position cannot be changed");
                return false;
            }

            // Riavvolgo lo stream.
            owinRequestBody.Position = 0L;

            // Se GZIP o DEFLATE non sono tra gli algoritmi accettati, allora NON devo applicare
            // alcuna decompressione della request.
            if (!contentEncoding.Contains(GZipEncoding))
            {
                _log.Debug($"Client did not send a compressed request - Content-Enconding: {contentEncoding}");
                return false;
            }

            if (_log.IsDebugEnabled)
            {
                _log.Debug($"Client sent a GZIP encoded request - Content-Enconding: {contentEncoding}");
            }

            // Decomprimo lo stream della request.
            var decompressed = new PooledMemoryStream();
            using (var gzipStream = new GZipStream(decompressed, CompressionMode.Decompress, true))
            {
                await owinRequestBody.CopyToAsync(decompressed);
            }

            // Sostituisco lo stream della request con uno decompresso.
            decompressed.Position = 0L;
            owinRequest.Body = decompressed;

            return true;
        }

        /// <summary>
        ///   Determina, secondo alcune semplici regole, se sia corretto applicare la compressione
        ///   alla response.
        /// </summary>
        /// <param name="owinResponse">La response di OWIN.</param>
        /// <returns>Vero se può essere compressa, falso altrimenti.</returns>
        private bool CanCompressResponse(IOwinResponse owinResponse)
        {
            if (owinResponse.StatusCode != 200)
            {
                // Non comprimo le risposte che non sono OK.
                _log.Debug($"Response has not a 200/OK status code (found {owinResponse.StatusCode}), compression will not be applied");
                return false;
            }
            if (owinResponse.Body.Length < _settings.MinResponseLengthForCompression)
            {
                // Se la risposta è troppo corta, non la comprimo.
                _log.Debug($"Response body length is less than {_settings.MinResponseLengthForCompression} bytes (found {owinResponse.StatusCode}), compression will not be applied");
                return false;
            }
            if (!string.IsNullOrWhiteSpace(owinResponse.Headers["Content-Encoding"]))
            {
                // Se, per qualche motivo, la risposta fosse già codificata in altro modo, non
                // applico ulteriori codifiche.
                _log.Debug($"Response body has already been compressed (found '{owinResponse.Headers["Content-Encoding"]}' as 'Content-Encoding' header value), compression will not be applied");
                return false;
            }
            return true;
        }

        /// <summary>
        ///   Impostazioni del componente di middleware.
        /// </summary>
        public sealed class Settings : AbstractMiddlewareSettings
        {
            /// <summary>
            ///   La lunghezza minima, in byte, per cui viene attivata la compressione della risposta.
            ///
            ///   Viene impostata di default a 4096 byte.
            /// </summary>
            public int MinResponseLengthForCompression { get; set; } = 4096;
        }
    }
}


text:
chat
====

Simple Realtime Chat App with Socket.io, Node.js & Express.


text:
package boofcv.abst.feature.associate;

import boofcv.alg.feature.associate.DescriptorDistance;
import boofcv.struct.feature.MatchScoreType;
import boofcv.struct.feature.TupleDesc_F64;

/**
 * Scores based on Euclidean distance
 *
 * @see {@link DescriptorDistance#euclidean(boofcv.struct.feature.TupleDesc_F64, boofcv.struct.feature.TupleDesc_F64)}
 *
 * @author Peter Abeles
 */
public class ScoreAssociateEuclidean_F64 implements ScoreAssociation<TupleDesc_F64> {
	@Override
	public double score(TupleDesc_F64 a, TupleDesc_F64 b) {
		return DescriptorDistance.euclidean(a,b);
	}

	@Override
	public MatchScoreType getScoreType() {
		return MatchScoreType.NORM_ERROR;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_divider" >

    <solid android:color="#340004" />

</shape>


text:
package org.sakaiproject.commons.tool.entityprovider;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.sakaiproject.commons.api.CommonsEvents;
import org.sakaiproject.commons.api.CommonsManager;
import org.sakaiproject.commons.api.CommonsSecurityManager;
import org.sakaiproject.commons.api.PostReferenceFactory;
import org.sakaiproject.commons.api.QueryBean;
import org.sakaiproject.commons.api.SakaiProxy;
import org.sakaiproject.commons.api.datamodel.Comment;
import org.sakaiproject.commons.api.datamodel.Post;
import org.sakaiproject.commons.api.datamodel.PostsData;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;
import org.sakaiproject.entitybroker.entityprovider.capabilities.ActionsExecutable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Describeable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Outputable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.ReferenceParseable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.RequestAware;
import org.sakaiproject.entitybroker.entityprovider.extension.ActionReturn;
import org.sakaiproject.entitybroker.entityprovider.extension.Formats;
import org.sakaiproject.entitybroker.entityprovider.extension.RequestGetter;
import org.sakaiproject.entitybroker.exception.EntityException;
import org.sakaiproject.entitybroker.util.AbstractEntityProvider;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Adrian Fish (adrian.r.fish@gmail.com)
 */
@Setter @Slf4j
public class CommonsEntityProvider extends AbstractEntityProvider implements RequestAware, AutoRegisterEntityProvider, Outputable, Describeable, ActionsExecutable, ReferenceParseable {

    public final static String ENTITY_PREFIX = "commons";

    private final static String USER_AGENT
        = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2";

    private CommonsManager commonsManager;
    private CommonsSecurityManager commonsSecurityManager;
    private RequestGetter requestGetter;
    private SakaiProxy sakaiProxy;

    private final static List<String> contentTypes
        = Arrays.asList("image/png", "image/jpg", "image/jpeg", "image/gif");

    public Object getSampleEntity() {
        return new Post();
    }

    public String getEntityPrefix() {
        return ENTITY_PREFIX;
    }

    public EntityReference getParsedExemplar() {
       return new EntityReference("sakai:commons");
    }

    public String[] getHandledOutputFormats() {
        return new String[] { Formats.JSON,Formats.XML };
    }

    @EntityCustomAction(action = "posts", viewKey = EntityView.VIEW_LIST)
    public ActionReturn getPosts(EntityView view, Map<String, Object> params) {

        String userId = getCheckedUser();

        String commonsId = view.getPathSegment(2);
        String siteId = (String) params.get("siteId");
        String embedder = (String) params.get("embedder");

        if (StringUtils.isBlank(commonsId) || StringUtils.isBlank(siteId) || StringUtils.isBlank(embedder)) {
            throw new EntityException(
                "Bad request: To get the posts in a commons you need a url like '/direct/commons/posts/COMMONSID.json?siteId=siteId&embedder=SITE'"
                                            , "", HttpServletResponse.SC_BAD_REQUEST);
        }

        List<Post> posts = new ArrayList();

        boolean isUserSite = sakaiProxy.isUserSite(siteId);

        QueryBean query = QueryBean.builder()
            .commonsId(commonsId)
            .siteId(siteId)
            .embedder(embedder)
            .userSite(isUserSite)
            .callerId(userId).build();

        try {
            posts = commonsManager.getPosts(query);

            PostsData data = new PostsData();
            data.postsTotal = posts.size();

            int page = Integer.parseInt((String) params.get("page"));

            if (page == -1) {
                // This is a hack to support the multi tool pages. Infinite scroll does not work well
                // in a frame.
                data.status = "END";
                if (posts.size() > 200) {
                    posts = posts.subList(0, 200);
                }
                data.posts = posts;
            } else {
                int pageSize = 20;
                int start  = page * pageSize;

                if (start >= data.postsTotal) {
                    data.status = "END";
                } else {
                    int end = start + pageSize;

                    log.debug("end: {}", end);

                    if (end >= data.postsTotal) {
                        end = data.postsTotal;
                        data.status = "END";
                    }

                    data.posts = posts.subList(start, end);
                }
            }

            return new ActionReturn(data);
        } catch (Exception e) {
            log.error("Caught exception whilst getting posts.", e);
            throw new EntityException("Failed to retrieve posts for site " + siteId, "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @EntityCustomAction(action = "post", viewKey = EntityView.VIEW_LIST)
    public ActionReturn getPost(EntityView view, Map<String, Object> params) {

        String userId = getCheckedUser();

        String postId = (String) params.get("postId");

        if (StringUtils.isBlank(postId)) {
            throw new EntityException("You must supply a postId" , "", HttpServletResponse.SC_BAD_REQUEST);
        }

        Optional<Post> opPost = commonsManager.getPost(postId, true);

        if (opPost.isPresent()) {
            return new ActionReturn(opPost.get());
        } else {
            throw new EntityException("No post with id '" + postId + "'" , "", HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @EntityCustomAction(action = "savePost", viewKey = EntityView.VIEW_NEW)
    public ActionReturn handleSavePost(Map<String, Object> params) {

        log.debug("handleSavePost");

        String userId = getCheckedUser();

        String content = (String) params.get("content");
        String siteId = (String) params.get("siteId");
        String commonsId = (String) params.get("commonsId");
        String embedder = (String) params.get("embedder");

        if (StringUtils.isBlank(content) || StringUtils.isBlank(siteId)
                || StringUtils.isBlank(commonsId) || StringUtils.isBlank(embedder)) {
            throw new EntityException("You must supply a siteId, commonsId, embedder and some content"
                                                , "", HttpServletResponse.SC_BAD_REQUEST);
        }

        String id = (String) params.get("id");

        boolean isNew = "".equals(id);

        Post post = new Post();

        if (!isNew) {
            post = commonsManager.getPost(id, false).get();
            post.setContent(content);
        } else {
            post.setCreatorId(userId);
            post.setSiteId(siteId);
            post.setCommonsId(commonsId);
            post.setEmbedder(embedder);
            post.setContent(content);
        }

        Post createdOrUpdatedPost = commonsManager.savePost(post);
        if (createdOrUpdatedPost != null) {
            if (isNew) {
                sakaiProxy.postEvent(CommonsEvents.POST_CREATED,
                                        createdOrUpdatedPost.getReference(),
                                        createdOrUpdatedPost.getSiteId());
            } else {
                sakaiProxy.postEvent(CommonsEvents.POST_UPDATED,
                                        createdOrUpdatedPost.getReference(),
                                        createdOrUpdatedPost.getSiteId());
            }
            return new ActionReturn(createdOrUpdatedPost);
        } else {
            return new ActionReturn("FAIL");
        }
    }

    @EntityCustomAction(action = "deletePost", viewKey = EntityView.VIEW_LIST)
    public ActionReturn handleDeletePost(Map<String, Object> params) {

        log.debug("handleDeletePost");

        getCheckedUser();

        String postId = (String) params.get("postId");
        String commonsId = (String) params.get("commonsId");
        String siteId = (String) params.get("siteId");
        if (StringUtils.isBlank(postId) || StringUtils.isBlank(commonsId) || StringUtils.isBlank(siteId)) {
            throw new EntityException("You must supply a postId, a commonsId and a siteId."
                                                , "", HttpServletResponse.SC_BAD_REQUEST);
        }

        if (commonsManager.deletePost(postId)) {
            String reference = PostReferenceFactory.getReference(commonsId, postId);
            sakaiProxy.postEvent(CommonsEvents.POST_DELETED,
                                    reference,
                                    siteId);
            return new ActionReturn("SUCCESS");
        } else {
            return new ActionReturn("FAIL");
        }
    }

    @EntityCustomAction(action = "deleteComment", viewKey = EntityView.VIEW_LIST)
    public ActionReturn handleDeleteComment(Map<String, Object> params) {

        log.debug("handleDeleteComment");

        getCheckedUser();

        String siteId = (String) params.get("siteId");
        String commonsId = (String) params.get("commonsId");
        String postId = (String) params.get("postId");
        String embedder = (String) params.get("embedder");
        String commentId = (String) params.get("commentId");
        String commentCreatorId = (String) params.get("commentCreatorId");
        String postCreatorId = (String) params.get("postCreatorId");

        if (StringUtils.isBlank(siteId) || StringUtils.isBlank(commonsId) || StringUtils.isBlank(postId)
                || StringUtils.isBlank(embedder) || StringUtils.isBlank(commentId)
                || StringUtils.isBlank(commentCreatorId) || StringUtils.isBlank(postCreatorId)) {
            throw new EntityException("You must supply siteId, commonsId, postId, embedder, commentId, commentCreatorId and postCreatorId"
                                                , "", HttpServletResponse.SC_BAD_REQUEST);
        }

        if (commonsManager.deleteComment(siteId, commonsId, embedder, commentId, commentCreatorId, postCreatorId)) {
            String reference = CommonsManager.REFERENCE_ROOT + "/" + commonsId + "/posts/" + postId + "/comments/" + commentId;
            sakaiProxy.postEvent(CommonsEvents.COMMENT_DELETED, reference, siteId);
            return new ActionReturn("SUCCESS");
        } else {
            return new ActionReturn("FAIL");
        }
    }

    @EntityCustomAction(action = "saveComment", viewKey = EntityView.VIEW_NEW)
    public ActionReturn handleSaveComment(Map<String, Object> params) {

        log.debug("handleSaveComment");

        String userId = getCheckedUser();

        String postId = (String) params.get("postId");
        String content = (String) params.get("content");
        String commonsId = (String) params.get("commonsId");
        String siteId = (String) params.get("siteId");

        if (StringUtils.isBlank(content) || StringUtils.isBlank(commonsId) || StringUtils.isBlank(postId) || StringUtils.isBlank(siteId)) {
            throw new EntityException("You must supply a commonsId, siteId, postId and some content"
                                                , "", HttpServletResponse.SC_BAD_REQUEST);
        }

        String id = (String) params.get("id");

        Comment comment = new Comment();
        comment.setId(id);
        comment.setPostId(postId);
        comment.setCreatorId(userId);
        comment.setContent(content);

        content = escape(content);

        boolean isNew = StringUtils.isBlank(comment.getId());

        Comment savedComment = commonsManager.saveComment(commonsId, comment);
        if (savedComment != null) {
            String reference = CommonsManager.REFERENCE_ROOT + "/" + commonsId + "/posts/" + postId + "/comments/" + comment.getId();
            if (isNew) {
                sakaiProxy.postEvent(CommonsEvents.COMMENT_CREATED, reference, siteId);
            } else {
                sakaiProxy.postEvent(CommonsEvents.COMMENT_UPDATED, reference, siteId);
            }
            return new ActionReturn(savedComment);
        } else {
            return new ActionReturn("FAIL");
        }
    }

    @EntityCustomAction(action = "userPerms", viewKey = EntityView.VIEW_LIST)
    public Set<String> handleUserPermsGet(EntityView view, Map<String, Object> params) {

        String userId = getCheckedUser();

        String siteId = (String) params.get("siteId");
        String embedder = (String) params.get("embedder");

        if (StringUtils.isBlank(siteId) || StringUtils.isBlank(embedder)) {
            throw new EntityException("No siteId or embedder supplied", "", HttpServletResponse.SC_BAD_REQUEST);
        }

        return sakaiProxy.getSitePermissionsForCurrentUser(siteId, embedder);
    }

    @EntityCustomAction(action = "perms", viewKey = EntityView.VIEW_LIST)
    public Map<String, Set<String>> handlePermsGet(EntityView view, Map<String, Object> params) {

        String userId = getCheckedUser();

        String siteId = (String) params.get("siteId");

        if (StringUtils.isBlank(siteId)) {
            throw new EntityException("No siteId supplied", "", HttpServletResponse.SC_BAD_REQUEST);
        }

        return sakaiProxy.getSitePermissions(siteId);
    }

    @EntityCustomAction(action = "savePermissions", viewKey = EntityView.VIEW_NEW)
    public String handleSavePermissions(EntityView view, Map<String, Object> params) {

        String userId = getCheckedUser();

        String siteId = (String) params.get("siteId");

        if (sakaiProxy.setPermissionsForSite(siteId, params)) {
            return "success";
        } else {
            throw new EntityException("Failed to set perms", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @EntityCustomAction(action = "getUrlMarkup", viewKey = EntityView.VIEW_LIST)
    public ActionReturn getUrlMarkup(OutputStream outputStream, EntityView view, Map<String, Object> params) {

        String userId = getCheckedUser();

        String urlString = (String) params.get("url");

        if (StringUtils.isBlank(urlString)) {
            throw new EntityException("No url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
        }

        try {
            CookieHandler.setDefault( new CookieManager(null, CookiePolicy.ACCEPT_ALL));
            URL url = new URL(urlString);
            URLConnection c = url.openConnection();

            if (c instanceof HttpURLConnection) {
                HttpURLConnection conn = (HttpURLConnection) c;
                conn.setRequestProperty("User-Agent", USER_AGENT);
                conn.setInstanceFollowRedirects(false);
                conn.connect();
                String contentEncoding = conn.getContentEncoding();
                String contentType = conn.getContentType();
                int responseCode = conn.getResponseCode();
                log.debug("Response code: {}", responseCode);

                int redirectCounter = 1;
                while ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                        || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                        || responseCode == HttpURLConnection.HTTP_SEE_OTHER) && redirectCounter < 20) {
                    String newUri = conn.getHeaderField("Location");
                    log.debug("{}. New URI: {}", responseCode, newUri);
                    String cookies = conn.getHeaderField("Set-Cookie");
                    url = new URL(newUri);
                    c = url.openConnection();
                    conn = (HttpURLConnection) c;
                    conn.setInstanceFollowRedirects(false);
                    conn.setRequestProperty("User-Agent", USER_AGENT);
                    conn.setRequestProperty("Cookie", cookies);
                    conn.connect();
                    contentEncoding = conn.getContentEncoding();
                    contentType = conn.getContentType();
                    responseCode = conn.getResponseCode();
                    log.debug("Redirect counter: {}", redirectCounter);
                    log.debug("Response code: {}", responseCode);
                    redirectCounter += 1;
                }

                if (contentType != null
                        && (contentType.startsWith("text/html")
                                || contentType.startsWith("application/xhtml+xml")
                                || contentType.startsWith("application/xml"))) {
                    String mimeType = contentType.split(";")[0].trim();
                    log.debug("mimeType: {}", mimeType);
                    log.debug("encoding: {}", contentEncoding);

                    BufferedReader reader
                        = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    BufferedWriter writer
                        = new BufferedWriter(new OutputStreamWriter(outputStream));

                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        writer.write(line);
                    }

                    return new ActionReturn(contentEncoding, mimeType, outputStream);
                } else {
                    log.debug("Invalid content type {}. Throwing bad request ...", contentType);
                    throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST);
                }
            } else {
                throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST);
            }
        } catch (MalformedURLException mue) {
            throw new EntityException("Invalid url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ioe) {
            throw new EntityException("Failed to download url contents", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @EntityCustomAction(action = "uploadImage", viewKey = EntityView.VIEW_NEW)
    public String uploadImage(EntityView view, Map<String, Object> params) {

        String userId = getCheckedUser();

        String siteId = (String) params.get("siteId");
        FileItem fileItem = (FileItem) params.get("imageFile");
        String contentType = fileItem.getContentType();
        if (!contentTypes.contains(contentType)) {
            throw new EntityException("Invalid image type supplied.", "", HttpServletResponse.SC_BAD_REQUEST);
        }
        String url = sakaiProxy.storeFile(fileItem, siteId);

        if (url == null) {
            throw new EntityException("Failed to save file", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        return url;
    }

    private String getCheckedUser() throws EntityException {

        String userId = developerHelperService.getCurrentUserId();
        if (userId == null) {
            throw new EntityException("You must be logged in", "", HttpServletResponse.SC_UNAUTHORIZED);
        }
        return userId;
    }

    private String escape(String unescaped) {
        return StringEscapeUtils.escapeJava(unescaped);
    }
}


text:
/**
* @author Saeid Mohadjer <info@saeidmohadjer.com>
* @link https://github.com/smohadjer/jquery.sameHeight
* @license http://opensource.org/licenses/MIT
*
* @version 0.0.8
*
* based on: http://jqueryboilerplate.com/
* jQuery plugin for making adjacent elements the same height. By default elements
* in different rows can have different heights, but if oneHeightForAll is set to
* true then all elements have the same height.
*/

;(function ($, window, document, undefined) {
	'use strict';

	var pluginName = 'sameHeight',
		defaults = {
			oneHeightForAll: false,
			useCSSHeight: false
		};

	//private method
	var getHeightOfTallest = function(elms) {
		var height = 0;

		$.each(elms, function() {
			var _h = $(this).outerHeight();

			if (_h > height) {
				height = _h;
			}
		});

		return height;
	};

	// The actual plugin constructor
	function Plugin(element, options) {
		this.$element = $(element);
		this.options = $.extend({}, defaults, options);
		this.init();
	}

	// methods
	var methods = {
		init: function() {
			var self = this;
			self.index = 0;

			self.$elms = self.$element.children();

			self.cssProperty = self.options.useCSSHeight ? 'height' : 'min-height';

			$(window).on('resize.' + pluginName, function() {
				//remove previously set height or min-height
				self.$elms.css(self.cssProperty, '');
				initSameHeight();
			});

			//use setTimeout to make sure any code in stack is executed before
			//calculating height
			setTimeout(function() {
				initSameHeight();
			}, 0);

			function initSameHeight() {
				//if there are adjacent elements
				if (self.getRow(0).length > 1) {
					self.setMinHeight(0);

					if (self.options.callback) {
						self.options.callback();
					}
				}
			}
		},

		setMinHeight: function(index){
			var self = this;
			var row = self.options.oneHeightForAll ? self.$elms : self.getRow(index);

			var height = getHeightOfTallest(row);

			$.each(row, function() {
				$(this).css(self.cssProperty, height);
			});

			if (!self.options.oneHeightForAll && self.index < self.$elms.length - 1) {
				self.setMinHeight(self.index);
			}
		},

		getRow: function(index) {
			var self = this;
			var row = [];
			var $first = self.$elms.eq(index);
			var top = $first.position().top;

			row.push($first);

			self.$elms.slice(index + 1).each(function() {
				var $elm = $(this);
				if ($elm.position().top === top) {
					row.push($elm);
					self.index = $elm.index();
				} else {
					self.index = $elm.index();
					return false;
				}
			});

			return row;
		},

		destroy: function() {
			var self = this;
			//remove event handlers
			$(window).off('resize.' + pluginName);

			//remove dom changes
			self.$elms.css(self.cssProperty, '');
			self.$element.removeData('plugin_' + pluginName);
		}
	};

	// build
	$.extend(Plugin.prototype, methods);

	// A really lightweight plugin wrapper around the constructor,
	// preventing against multiple instantiations
	$.fn[pluginName] = function(options) {
		this.each(function() {
			if(!$.data(this, 'plugin_' + pluginName)) {
				$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
			}
		});

		return this;
	};

})(jQuery, window, document);


text:
Data structures, parsers, and encoders for RDF data sets based on the RDF 1.1
abstract syntax and RFC 3987. The interface is intended to support incremental
graph processing in constant space.


text:
var countBs = function(word){
   return countChar(word, "B");
};

var countChar = function(word, char){
   var count = 0;
   for(var i=0; i<word.length; i++){
      if(word.charAt(i) == char){
         count ++;
      }
   }
   return count;
}

console.log(countBs("BBC"));
console.log(countChar("kakkerlak", "k"));


text:
#include "tensorflow/lite/experimental/micro/memory_planner/linear_memory_planner.h"

namespace tflite {

LinearMemoryPlanner::LinearMemoryPlanner()
    : current_buffer_count_(0), next_free_offset_(0) {}
LinearMemoryPlanner::~LinearMemoryPlanner() {}

TfLiteStatus LinearMemoryPlanner::AddBuffer(
    tflite::ErrorReporter* error_reporter, int size, int first_time_used,
    int last_time_used) {
  if (current_buffer_count_ >= kMaxBufferCount) {
    error_reporter->Report("Too many buffers (max is %d)", kMaxBufferCount);
    return kTfLiteError;
  }
  buffer_offsets_[current_buffer_count_] = next_free_offset_;
  next_free_offset_ += size;
  ++current_buffer_count_;
  return kTfLiteOk;
}

int LinearMemoryPlanner::GetMaximumMemorySize() { return next_free_offset_; }

int LinearMemoryPlanner::GetBufferCount() { return current_buffer_count_; }

TfLiteStatus LinearMemoryPlanner::GetOffsetForBuffer(
    tflite::ErrorReporter* error_reporter, int buffer_index, int* offset) {
  if ((buffer_index < 0) || (buffer_index >= current_buffer_count_)) {
    error_reporter->Report("buffer index %d is outside range 0 to %d",
                           buffer_index, current_buffer_count_);
    return kTfLiteError;
  }
  *offset = buffer_offsets_[buffer_index];
  return kTfLiteOk;
}

}  // namespace tflite


text:
. ./scripts/helper.sh || . ./helper.sh || wget -q 'https://github.com/jmcerrejon/PiKISS/raw/master/scripts/helper.sh'
clear
check_board || { echo "Missing file helper.sh. I've tried to download it for you. Try to run the script again." && exit 1; }

readonly INSTALL_DIR="$HOME/games/"
readonly PACKAGES=(libsdl-mixer1.2)
readonly BINARY_URL="https://www.retroguru.com/xump/xump-v.latest-raspberrypi.zip"

if which "$INSTALL_DIR"/xump_rpi >/dev/null; then
    read -p "Warning!: Xump already installed. Press [ENTER] to exit..."
    exit
fi

generate_icon() {
    echo "Generating icon..."
    if [[ ! -e ~/.local/share/applications/Xump.desktop ]]; then
        cat <<EOF >~/.local/share/applications/Xump.desktop
[Desktop Entry]
Name=Xump
Exec=${PWD}/games/xump/xump_rpi
Icon=terminal
Type=Application
Comment=Xump - The Final Run is a simple multi-platform puzzler by Retroguru
Categories=Game;ActionGame;
Path=${PWD}/games/xump/
EOF
    fi
}

install() {
    install_packages_if_missing "${PACKAGES[@]}"
    download_and_extract "$BINARY_URL" "$INSTALL_DIR/xump"
    chmod +x "$INSTALL_DIR/xump/xump_rpi"
    generate_icon
    echo -e "Done!. To play, on Desktop go to Menu > Games or via terminal: $INSTALL_DIR/xump and type: ./xump_rpi\n\nEnjoy!"
    exit_message
}

install_script_message
echo "
Install Xump (Raspberry Pi version)
===================================

· More Info: https://www.retroguru.com/xump/
· Install path: $INSTALL_DIR
"

install


text:
FROM tianon/debian:7.0
EXPOSE 5984

RUN echo "\ndeb http://packages.erlang-solutions.com/debian wheezy contrib\n" >> /etc/apt/sources.list
RUN apt-get update
RUN apt-get install -y --force-yes wget make erlang build-essential libtool autoconf automake autoconf-archive pkg-config libmozjs185-dev libicu-dev python-simplejson
ADD http://archive.apache.org/dist/couchdb/source/1.4.0/apache-couchdb-1.4.0.tar.gz /tmp/apache-couchdb-1.4.0.tar.gz
RUN cd /tmp && tar xvzf apache-couchdb-1.4.0.tar.gz
RUN cd /tmp/apache-couchdb-* && ./configure --prefix=/usr/local --with-js-lib=/usr/lib --with-js-include=/usr/include/mozjs --enable-init && make && make install
RUN useradd -d /var/lib/couchdb couchdb
RUN chown -R couchdb:couchdb /usr/local/lib/couchdb /usr/local/etc/couchdb /usr/local/var/lib/couchdb /usr/local/var/log/couchdb /usr/local/var/run/couchdb
RUN chmod -R g+rw /usr/local/lib/couchdb /usr/local/etc/couchdb /usr/local/var/lib/couchdb /usr/local/var/log/couchdb /usr/local/var/run/couchdb
RUN ln -s /usr/local/etc/logrotate.d/couchdb /etc/logrotate.d/couchdb
RUN ln -s /usr/local/etc/init.d/couchdb /etc/init.d
RUN update-rc.d couchdb defaults

RUN echo "[httpd]\n\
bind_address = 0.0.0.0\n\
port = 5984" > /usr/local/etc/couchdb/local.ini

ENV ERL_MAX_PORTS 4096
ENV ERL_FLAGS "+A 4"

CMD ["/usr/local/bin/couchdb"]


text:
package memoizeit.analysis.version;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import memoizeit.tuples.serialization.Tags;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;

public final class Version {

	public static final class Repository {

		private static int GLOBAL_CURRENT_CLASS_VERSION;
		private static final Map<String, Integer> CLASS_VERSIONS;
		private static final Map<Integer, Integer> CLASS_HASH_VERSIONS;

		static {
			GLOBAL_CURRENT_CLASS_VERSION = INITIAL_MAJOR_VERSION;
			CLASS_VERSIONS = new ConcurrentHashMap<String, Integer>();
			CLASS_HASH_VERSIONS = new ConcurrentHashMap<Integer, Integer>();
		}

		public static final int getOrCreateClassVersion(final String className) {
			if (!CLASS_VERSIONS.containsKey(className)) {
				CLASS_VERSIONS.put(className, ++GLOBAL_CURRENT_CLASS_VERSION);
			}
			return CLASS_VERSIONS.get(className);
		}

		private static final int getOrCreateHashVersion(int classVersion) {
			if (!CLASS_HASH_VERSIONS.containsKey(classVersion)) {
				CLASS_HASH_VERSIONS.put(classVersion, INITIAL_MAJOR_VERSION);
			}
			return CLASS_HASH_VERSIONS.get(classVersion);
		}

		public static final int getNewHashVersion(int classVersion) {
			int hashVersion = getOrCreateHashVersion(classVersion);
			hashVersion = hashVersion + 1;
			CLASS_HASH_VERSIONS.put(classVersion, hashVersion);
			return hashVersion;
		}

	}

	public static final int NULL_MAJOR_VERSION = Integer.MIN_VALUE;
	public static final int INITIAL_MAJOR_VERSION = 0;

	private static final Table<Integer, Integer, Version> CACHE = HashBasedTable.create();
	protected static final Table<Integer, String, Integer> VERSIONS = HashBasedTable.create();

	public static final Version NULL_VERSION = getOrCreate(NULL_MAJOR_VERSION, NULL_MAJOR_VERSION);
	public static final Version INVALID_VERSION = getOrCreate(INITIAL_MAJOR_VERSION, INITIAL_MAJOR_VERSION);

	public static synchronized int getOrCreateMinor(int classVersion, final String hash) {
		if (VERSIONS.contains(classVersion, hash)) {
			return VERSIONS.get(classVersion, hash);
		}
		int hashVersion = Repository.getNewHashVersion(classVersion);
		VERSIONS.put(classVersion, hash, hashVersion);
		return hashVersion;
	}

	public static synchronized Version getOrCreateInitial(final String className) {
		int classVersion = Repository.getOrCreateClassVersion(className);
		int hashVersion = INITIAL_MAJOR_VERSION;
		if (VERSIONS.contains(classVersion, className)) {
			hashVersion = VERSIONS.get(classVersion, className);
		} else {
			hashVersion = Repository.getOrCreateHashVersion(classVersion);
			VERSIONS.put(classVersion, className, hashVersion);
		}
		return Version.getOrCreate(classVersion, hashVersion);
	}

	public static synchronized Version getOrCreate(int classVersion, int hashVersion) {
		if (CACHE.contains(classVersion, hashVersion)) {
			return CACHE.get(classVersion, hashVersion);
		}
		final Version version = new Version();
		version.major = classVersion;
		version.minor = hashVersion;
		CACHE.put(classVersion, hashVersion, version);
		return version;
	}

	private int minor;
	private int major;

	public boolean isNull() {
		return major == NULL_MAJOR_VERSION;
	}

	public boolean isInvalid() {
		return major == INITIAL_MAJOR_VERSION;
	}

	public boolean isType() {
		return !isNull() && !isInvalid() && minor == INITIAL_MAJOR_VERSION;
	}

	public int getMinor() {
		return minor;
	}

	public int getMajor() {
		return major;
	}

	@Override
	public String toString() {
		if (isNull()) {
			return Tags.NULL;
		}  else if (isInvalid()){
			return Tags.INVALID;
		} else {
			return String.format("@v%d_%d", major, minor);
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

using Grpc.Core.Internal;
using NUnit.Framework;

namespace Grpc.Core.Internal.Tests
{
    /// <summary>
    /// For testing purposes.
    /// </summary>
    internal class FakeNativeCall : INativeCall
    {
        private bool shouldStartCallFail;
        public IUnaryResponseClientCallback UnaryResponseClientCallback
        {
            get;
            set;
        }

        public IReceivedStatusOnClientCallback ReceivedStatusOnClientCallback
        {
            get;
            set;
        }

        public IReceivedMessageCallback ReceivedMessageCallback
        {
            get;
            set;
        }

        public IReceivedResponseHeadersCallback ReceivedResponseHeadersCallback
        {
            get;
            set;
        }

        public ISendCompletionCallback SendCompletionCallback
        {
            get;
            set;
        }

        public ISendStatusFromServerCompletionCallback SendStatusFromServerCallback
        {
            get;
            set;
        }

        public IReceivedCloseOnServerCallback ReceivedCloseOnServerCallback
        {
            get;
            set;
        }

        public bool IsCancelled
        {
            get;
            set;
        }

        public bool IsDisposed
        {
            get;
            set;
        }

        public void Cancel()
        {
            IsCancelled = true;
        }

        public void CancelWithStatus(Status status)
        {
            IsCancelled = true;
        }

        public string GetPeer()
        {
            return "PEER";
        }

        public void StartUnary(IUnaryResponseClientCallback callback, SliceBufferSafeHandle payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
        {
            StartCallMaybeFail();
            UnaryResponseClientCallback = callback;
        }

        public void StartUnary(BatchContextSafeHandle ctx, SliceBufferSafeHandle payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
        {
            StartCallMaybeFail();
            throw new NotImplementedException();
        }

        public void StartClientStreaming(IUnaryResponseClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
        {
            StartCallMaybeFail();
            UnaryResponseClientCallback = callback;
        }

        public void StartServerStreaming(IReceivedStatusOnClientCallback callback, SliceBufferSafeHandle payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
        {
            StartCallMaybeFail();
            ReceivedStatusOnClientCallback = callback;
        }

        public void StartDuplexStreaming(IReceivedStatusOnClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags)
        {
            StartCallMaybeFail();
            ReceivedStatusOnClientCallback = callback;
        }

        public void StartReceiveMessage(IReceivedMessageCallback callback)
        {
            ReceivedMessageCallback = callback;
        }

        public void StartReceiveInitialMetadata(IReceivedResponseHeadersCallback callback)
        {
            ReceivedResponseHeadersCallback = callback;
        }

        public void StartSendInitialMetadata(ISendCompletionCallback callback, MetadataArraySafeHandle metadataArray)
        {
            SendCompletionCallback = callback;
        }

        public void StartSendMessage(ISendCompletionCallback callback, SliceBufferSafeHandle payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata)
        {
            SendCompletionCallback = callback;
        }

        public void StartSendCloseFromClient(ISendCompletionCallback callback)
        {
            SendCompletionCallback = callback;
        }

        public void StartSendStatusFromServer(ISendStatusFromServerCompletionCallback callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
            SliceBufferSafeHandle payload, WriteFlags writeFlags)
        {
            SendStatusFromServerCallback = callback;
        }

        public void StartServerSide(IReceivedCloseOnServerCallback callback)
        {
            ReceivedCloseOnServerCallback = callback;
        }

        public void Dispose()
        {
            IsDisposed = true;
        }

        /// <summary>
        /// Emulate CallSafeHandle.CheckOk() failure for all future attempts
        /// to start a call.
        /// </summary>
        public void MakeStartCallFail()
        {
            shouldStartCallFail = true;
        }

        private void StartCallMaybeFail()
        {
            if (shouldStartCallFail)
            {
                throw new InvalidOperationException("Start call has failed.");
            }
        }
    }
}


text:
package org.springframework.transaction.interceptor;

import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * Transaction attribute that takes the EJB approach to rolling
 * back on runtime, but not checked, exceptions.
 *
 * @author Rod Johnson
 * @since 16.03.2003
 */
@SuppressWarnings("serial")
public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute {

	private String qualifier;

	/**
	 * Create a new DefaultTransactionAttribute, with default settings.
	 * Can be modified through bean property setters.
	 * @see #setPropagationBehavior
	 * @see #setIsolationLevel
	 * @see #setTimeout
	 * @see #setReadOnly
	 * @see #setName
	 */
	public DefaultTransactionAttribute() {
		super();
	}

	/**
	 * Copy constructor. Definition can be modified through bean property setters.
	 * @see #setPropagationBehavior
	 * @see #setIsolationLevel
	 * @see #setTimeout
	 * @see #setReadOnly
	 * @see #setName
	 */
	public DefaultTransactionAttribute(TransactionAttribute other) {
		super(other);
	}

	/**
	 * Create a new DefaultTransactionAttribute with the the given
	 * propagation behavior. Can be modified through bean property setters.
	 * @param propagationBehavior one of the propagation constants in the
	 * TransactionDefinition interface
	 * @see #setIsolationLevel
	 * @see #setTimeout
	 * @see #setReadOnly
	 */
	public DefaultTransactionAttribute(int propagationBehavior) {
		super(propagationBehavior);
	}

	/**
	 * Associate a qualifier value with this transaction attribute.
	 *
This may be used for choosing a corresponding transaction manager
	 * to process this specific transaction.
	 */
	public void setQualifier(String qualifier) {
		this.qualifier = qualifier;
	}

	/**
	 * Return a qualifier value associated with this transaction attribute.
	 */
	@Override
	public String getQualifier() {
		return this.qualifier;
	}

	/**
	 * The default behavior is as with EJB: rollback on unchecked exception.
	 * Additionally attempt to rollback on Error.
	 *
This is consistent with TransactionTemplate's default behavior.
	 */
	@Override
	public boolean rollbackOn(Throwable ex) {
		return (ex instanceof RuntimeException || ex instanceof Error);
	}

	/**
	 * Return an identifying description for this transaction attribute.
	 *
Available to subclasses, for inclusion in their {@code toString()} result.
	 */
	protected final StringBuilder getAttributeDescription() {
		StringBuilder result = getDefinitionDescription();
		if (this.qualifier != null) {
			result.append("; '").append(this.qualifier).append("'");
		}
		return result;
	}

}


text:
cask 'pycharm' do
  version '2016.3.2'
  sha256 '20436a4faffe5d8251c3a41c59f0aa10548719a10f7052ccbf0ff236e5237838'

  url "https://download.jetbrains.com/python/pycharm-professional-#{version}.dmg"
  appcast 'https://data.services.jetbrains.com/products/releases?code=PCP&latest=true&type=release',
          checkpoint: '07878d7ff3f6c98608f0c7819c5b4ead2f1a6ac06cd57d60444f3b77e4015fab'
  name 'PyCharm'
  homepage 'https://www.jetbrains.com/pycharm/'

  conflicts_with cask: 'pycharm-eap'

  app 'PyCharm.app'

  uninstall delete: '/usr/local/bin/charm'

  zap delete: [
                "~/Library/Preferences/PyCharm#{version.major_minor}",
                "~/Library/Application Support/PyCharm#{version.major_minor}",
                "~/Library/Caches/PyCharm#{version.major_minor}",
                "~/Library/Logs/PyCharm#{version.major_minor}",
              ]
end


text:
package io.joynr.provider;

public interface DeferredListener {

    public void onSettlement();

}