text:
/**
 * Controller for changing privacy settings for a node and its children.
 */
'use strict';

var $ = require('jquery');
var ko = require('knockout');
var Raven = require('raven-js');
var $osf = require('./osfHelpers');
var osfHelpers = require('js/osfHelpers');
var m = require('mithril');
var NodesPrivacyTreebeard = require('js/nodesPrivacySettingsTreebeard');

var MESSAGES = {
    makeProjectPublicWarning:
    'Please review your projects, components, and add-ons for sensitive or restricted information before making them public.' +
    '

Once they are made public, you should assume they will always be public. You can ' +
        'return them to private later, but search engines (including Google's cache) or others may access files, wiki pages, or analytics before you do.',
    makeProjectPrivateWarning:
    '

Public forks and registrations of this project will remain public.
' +
    '
Search engines (including Google\'s cache) or others may have accessed files, wiki pages, or analytics while this project was public.

',
    makeSupplementalProjectPrivateWarning:
    '

Preprints will remain public.

Public forks and registrations of this project will remain public.
' +
    '
Search engines (including Google\'s cache) or others may have accessed files, wiki pages, or analytics while this project was public.

',
    makeEmbargoPublicWarning: 'By clicking confirm, an email will be sent to project administrator(s) to approve ending the embargo. If approved, this registration, including any components, will be made public immediately. This action is irreversible.',
    makeEmbargoPublicTitle: 'End embargo early',
    selectNodes: 'Adjust your privacy settings by checking the boxes below. ' +
    '

Checked projects and components will be public.
Unchecked components will be private.',
    confirmWarning: {
        nodesPublic: 'The following projects and components will be made public.',
        nodesPrivate: 'The following projects and components will be made private.',
        nodesNotChangedWarning: 'No privacy settings were changed. Go back to make a change.',
        tooManyNodesWarning: 'You can only change the privacy of 100 projects and components at a time.  Please go back and limit your selection.',
    },
    preprintPrivateWarning: 'This project/component contains supplemental materials for a preprint.'  +
        '
Making this project/component private will prevent others from accessing it.
'

};

function _flattenNodeTree(nodeTree) {
    var ret = [];
    var stack = [nodeTree];
    while (stack.length) {
        var node = stack.pop();
        ret.push(node);
        stack = stack.concat(node.children);
    }
    return ret;
}

/**
 * take treebeard tree structure of nodes and get a dictionary of parent node and all its
 * children
 */
function getNodesOriginal(nodeTree, nodesOriginal) {
    var flatNodes = _flattenNodeTree(nodeTree);
    $.each(flatNodes, function(_, nodeMeta) {
        nodesOriginal[nodeMeta.node.id] = {
            public: nodeMeta.node.is_public,
            id: nodeMeta.node.id,
            title: nodeMeta.node.title,
            isAdmin: nodeMeta.node.is_admin,
            changed: false,
            isSupplementalProject: nodeMeta.node.is_supplemental_project,
        };
    });
    nodesOriginal[nodeTree.node.id].isRoot = true;
    return nodesOriginal;
}

/**
 * patches all the nodes in a changed state
 * uses API v2 bulk requests
 */
function patchNodesPrivacy(nodes, type) {
    var nodesV2Url = window.contextVars.apiV2Prefix + type + '/';
    var nodesPatch = $.map(nodes, function (node) {
        return {
            'type': type,
            'id': node.id,
            'attributes': {
                'public': node.public
            }
        };
    });
    return $osf.ajaxJSON('PATCH', nodesV2Url, {
        data: {
            data: nodesPatch,
        },
        isCors: true,
        fields: {
            processData: false,
            contentType: 'application/vnd.api+json; ext=bulk',
        }
    });
}

/**
 * view model which corresponds to nodes_privacy.mako (#nodesPrivacy)
 *
 * @type {NodesPrivacyViewModel}
 */
var NodesPrivacyViewModel = function(node, onSetPrivacy) {
    var self = this;
    self.WARNING = 'warning';
    self.SELECT = 'select';
    self.CONFIRM = 'confirm';

    self.onSetPrivacy = onSetPrivacy;

    self.parentIsEmbargoed = node.is_embargoed;
    self.parentIsPublic = node.is_public;
    self.parentNodeType = node.node_type;
    self.isSupplementalProject = node.is_supplemental_project;
    self.dataType = node.is_registration ? 'registrations' : 'nodes';
    self.treebeardUrl = window.contextVars.node.urls.api  + 'tree/';
    self.nodesOriginal = {};
    self.nodesChanged = ko.observable();
    //state of current nodes
    self.nodesState = ko.observableArray();
    self.nodesState.subscribe(function(newValue) {
        var nodesChanged = 0;
        for (var key in newValue) {
            if (newValue[key].public !== self.nodesOriginal[key].public) {
                newValue[key].changed = true;
                nodesChanged++;
            }
            else {
                newValue[key].changed = false;
            }
        }
        self.nodesChanged(nodesChanged > 0);
        m.redraw(true);
    });
    //original node state on page load
    self.nodesChangedPublic = ko.observableArray([]);
    self.nodesChangedPrivate = ko.observableArray([]);
    self.hasChildren = ko.observable(false);
    $('#nodesPrivacy').on('hidden.bs.modal', function () {
        self.clear();
    });

    self.page = ko.observable(self.WARNING);

    self.pageTitle = ko.computed(function() {
        if (self.page() === self.WARNING &&  self.parentIsEmbargoed) {
            return MESSAGES.makeEmbargoPublicTitle;
        }

        return {
            warning: self.parentIsPublic ?
                'Make ' + self.parentNodeType + ' private' :
                'Warning',
            select: 'Change privacy settings',
            confirm: 'Projects and components affected'
        }[self.page()];
    });

    self.message = ko.computed(function() {
        if (self.page() === self.WARNING && self.parentIsEmbargoed) {
            return MESSAGES.makeEmbargoPublicWarning;
        }

        if (self.page() === self.WARNING && self.isSupplementalProject && self.parentIsPublic) {
              return MESSAGES.preprintPrivateWarning + MESSAGES.makeSupplementalProjectPrivateWarning;
        }

        return {
            warning: self.parentIsPublic ?
                MESSAGES.makeProjectPrivateWarning :
                MESSAGES.makeProjectPublicWarning,
            select: MESSAGES.selectNodes,
            confirm: MESSAGES.confirmWarning
        }[self.page()];
    });
};

/**
 * get node tree for treebeard from API V1
 */
NodesPrivacyViewModel.prototype.fetchNodeTree = function() {
    var self = this;

    return $.ajax({
        url: self.treebeardUrl,
        type: 'GET',
        dataType: 'json'
    }).done(function(response) {
        self.nodesOriginal = getNodesOriginal(response[0], self.nodesOriginal);
        var size = 0;
        $.each(Object.keys(self.nodesOriginal), function(_, key) {
            if (self.nodesOriginal.hasOwnProperty(key)) {
                size++;
            }
        });
        self.hasChildren(size > 1);
        var nodesState = $.extend(true, {}, self.nodesOriginal);
        var nodeParent = response[0].node.id;
        //change node state and response to reflect button push by user on project page (make public | make private)
        nodesState[nodeParent].public = response[0].node.is_public = !self.parentIsPublic;
        nodesState[nodeParent].changed = true;
        self.nodesState(nodesState);
    }).fail(function(xhr, status, error) {
        $osf.growl('Error', 'Unable to retrieve project settings');
        Raven.captureMessage('Could not GET project settings.', {
            extra: {
                url: self.treebeardUrl, status: status, error: error
            }
        });
    });
};

NodesPrivacyViewModel.prototype.selectProjects = function() {
    this.page(this.SELECT);
};

NodesPrivacyViewModel.prototype.confirmWarning =  function() {
    var nodesState = ko.toJS(this.nodesState);
    for (var node in nodesState) {
        if (nodesState[node].changed) {
            if (nodesState[node].public) {
                this.nodesChangedPublic().push(nodesState[node].title);
            }
            else {
                this.nodesChangedPrivate().push(nodesState[node].title);
            }
        }
    }
    this.page(this.CONFIRM);
};

NodesPrivacyViewModel.prototype.confirmChanges =  function() {
    var self = this;

    var nodesState = ko.toJS(this.nodesState());
    nodesState = Object.keys(nodesState).map(function(key) {
        return nodesState[key];
    });
    var nodesChanged = nodesState.filter(function(node) {
        return node.changed;
    });
    //The API's bulk limit is 100 nodes.  We catch the exception in nodes_privacy.mako.
    if (nodesChanged.length <= 100) {
        $osf.block('Updating Privacy');
        patchNodesPrivacy(nodesChanged, self.dataType).then(function () {
            self.onSetPrivacy(nodesChanged);

            self.nodesChangedPublic([]);
            self.nodesChangedPrivate([]);
            self.page(self.WARNING);
            window.location.reload();
        }).fail(function (xhr) {
            $osf.unblock();
            var errorMessage = 'Unable to update project privacy';
            if (xhr.responseJSON && xhr.responseJSON.errors) {
                errorMessage = xhr.responseJSON.errors[0].detail;
            }
            $osf.growl('Problem changing privacy', errorMessage);
            Raven.captureMessage('Could not PATCH project settings.');
            self.clear();
            $('#nodesPrivacy').modal('hide');
        }).always(function() {
            $osf.unblock();
        });
    }
};

NodesPrivacyViewModel.prototype.clear = function() {
    this.nodesChangedPublic([]);
    this.nodesChangedPrivate([]);
    this.page(this.WARNING);
};

NodesPrivacyViewModel.prototype.selectAll = function() {
    var nodesState = ko.toJS(this.nodesState());
    for (var node in nodesState) {
        if (nodesState[node].isAdmin) {
            nodesState[node].public = true;
            nodesState[node].changed = nodesState[node].public !== this.nodesOriginal[node].public;
        }
    }
    this.nodesState(nodesState);
    m.redraw(true);
};

NodesPrivacyViewModel.prototype.selectNone = function() {
    var nodesState = ko.toJS(this.nodesState());
    for (var node in nodesState) {
        if (nodesState[node].isAdmin) {
            nodesState[node].public = false;
            nodesState[node].changed = nodesState[node].public !== this.nodesOriginal[node].public;

        }
    }
    this.nodesState(nodesState);
    m.redraw(true);
};

NodesPrivacyViewModel.prototype.back = function() {
    this.nodesChangedPublic([]);
    this.nodesChangedPrivate([]);
    this.page(this.SELECT);
};

NodesPrivacyViewModel.prototype.makeEmbargoPublic = function() {
    var self = this;

    var nodesChanged = $.map(self.nodesOriginal, function(node) {
	if (node.isRoot) {
            node.public = true;
	    return node;
	}
	return null;
    }).filter(Boolean);
    $osf.block('Submitting request to end embargo early ...');
    patchNodesPrivacy(nodesChanged, self.dataType).then(function (res) {
        $osf.unblock();
        $('.modal').modal('hide');
        self.onSetPrivacy(nodesChanged, true);
        $osf.growl(
            'Email sent',
            'The administrator(s) can approve or cancel the action within 48 hours. If 48 hours pass without any action taken, then the registration will become public.',
            'success'
        );
    });
};

function NodesPrivacy (selector, node, onSetPrivacy) {
    var self = this;

    self.selector = selector;
    self.$element = $(self.selector);
    self.viewModel = new NodesPrivacyViewModel(node, onSetPrivacy);
    self.viewModel.fetchNodeTree().done(function(response) {
        new NodesPrivacyTreebeard('nodesPrivacyTreebeard', response, self.viewModel.nodesState, self.viewModel.nodesOriginal);
    });
    self.init();
}

NodesPrivacy.prototype.init = function() {
    osfHelpers.applyBindings(this.viewModel, this.selector);
};

module.exports = {
    _NodesPrivacyViewModel: NodesPrivacyViewModel,
    NodesPrivacy: NodesPrivacy
};


text:
@implementation BLPushTransitionAnimator
- (instancetype)initWithTargetStyle:(BLTransitionAnimatorStyle)animatorStyle
{
    self = [self init];
    if (self) {
        self.animatorStyle = animatorStyle;
    }
    return self;
}

//| ----------------------------------------------------------------------------
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return TransitionDuration;
}

//| ----------------------------------------------------------------------------
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UIView *containerView = transitionContext.containerView;

    UIView *fromView;
    UIView *toView;

    //从文本控制器里边拿到 源控制器view(fromView) 和  目标控制器的 view(toView)
    if ([transitionContext respondsToSelector:@selector(viewForKey:)]) {
        fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    } else {
        fromView = fromViewController.view;
        toView = toViewController.view;
    }

    fromView.frame = [transitionContext initialFrameForViewController:fromViewController];
    toView.frame = [transitionContext finalFrameForViewController:toViewController];

    //获取from 和 toview 的 frame
    CGRect fromFrame = [transitionContext initialFrameForViewController:fromViewController];
    CGRect toFrame = [transitionContext finalFrameForViewController:toViewController];

    //判断是present 还是dismiss
   BOOL isPush = ([toViewController.navigationController.viewControllers indexOfObject:toViewController] > [fromViewController.navigationController.viewControllers indexOfObject:fromViewController]);

    if (isPush){
        [containerView addSubview:toView];
    }else{
        [containerView insertSubview:toView belowSubview:fromView];
    }

    //执行动画的时间
    NSTimeInterval transitionDuration = [self transitionDuration:transitionContext];

    switch (self.animatorStyle) {
        case BLTransitionAnimatorTop:{
            if (isPush) {

                fromView.frame = fromFrame;
                toView.frame = CGRectMake(0, -toFrame.size.height, toFrame.size.width, toFrame.size.height);
            } else {
                fromView.frame = fromFrame;
                toView.frame = toFrame;
            }
            [UIView animateWithDuration:transitionDuration animations:^{

                if (isPush) {
                    toView.frame = toFrame;
                } else {
                    fromView.frame = CGRectMake(0, -fromFrame.size.height, fromFrame.size.width, fromFrame.size.height);
                }
            } completion:^(BOOL finished) {
                // When we complete, tell the transition context
                // passing along the BOOL that indicates whether the transition
                // finished or not.
                BOOL wasCancelled = [transitionContext transitionWasCancelled];
                if (wasCancelled)
                    [toView removeFromSuperview];
                [transitionContext completeTransition:!wasCancelled];
            }];
        }
            break;
        case BLTransitionAnimatorBottom:{

            if (isPush) {
                fromView.frame = fromFrame;
                toView.frame = CGRectMake(0, toFrame.size.height, toFrame.size.width, toFrame.size.height);
            } else {
                fromView.frame = fromFrame;
                toView.frame = toFrame;
            }
            [UIView animateWithDuration:transitionDuration animations:^{

                if (isPush) {
                    toView.frame = toFrame;
                } else {
                    // For a dismissal, the fromView slides off the screen.
                    fromView.frame = CGRectMake(0, fromFrame.size.height, fromFrame.size.width, fromFrame.size.height);
                }
            } completion:^(BOOL finished) {
                // When we complete, tell the transition context
                // passing along the BOOL that indicates whether the transition
                // finished or not.
                BOOL wasCancelled = [transitionContext transitionWasCancelled];
                if (wasCancelled)
                    [toView removeFromSuperview];
                [transitionContext completeTransition:!wasCancelled];
            }];
        }
            break;
        case BLTransitionAnimatorLeft:{

            if (isPush) {
                fromView.frame = fromFrame;
                toView.frame = CGRectMake(-toFrame.size.width, 0, toFrame.size.width, toFrame.size.height);
            } else {
                fromView.frame = fromFrame;
                toView.frame = toFrame;
            }
            [UIView animateWithDuration:transitionDuration animations:^{

                if (isPush) {
                    toView.frame = toFrame;
                } else {

                    fromView.frame = CGRectMake(-fromFrame.size.width, 0, fromFrame.size.width, fromFrame.size.height);
                }
            } completion:^(BOOL finished) {

                BOOL wasCancelled = [transitionContext transitionWasCancelled];
                if (wasCancelled)
                    [toView removeFromSuperview];
                [transitionContext completeTransition:!wasCancelled];
            }];
        }
            break;
        case BLTransitionAnimatorRight:{
            if (isPush) {
                fromView.frame = fromFrame;
                toView.frame = CGRectMake(toFrame.size.width, 0, toFrame.size.width, toFrame.size.height);
            } else {
                fromView.frame = fromFrame;
                toView.frame = toFrame;
            }
            [UIView animateWithDuration:transitionDuration animations:^{

                if (isPush) {
                    toView.frame = toFrame;
                } else {
                    fromView.frame = CGRectMake(fromFrame.size.width, 0, fromFrame.size.width, fromFrame.size.height);
                }
            } completion:^(BOOL finished) {

                BOOL wasCancelled = [transitionContext transitionWasCancelled];
                if (wasCancelled)
                    [toView removeFromSuperview];
                [transitionContext completeTransition:!wasCancelled];
            }];
        }
            break;
        case BLTransitionAnimatorCustom:{
            BLTransitionType type ;
            if (isPush) {

                type = BLTransitionTypePush;
            } else {
               type = BLTransitionTypePop;
            }
            BLDIYTrasitionAnimation *diy = [[BLDIYTrasitionAnimation alloc]init];

            [diy customAnimationType:type ToView:toView FromView:fromView transitionDuration:transitionDuration finished:^(NSString *finished) {
//                NSLog(@"%@",finished);
                BOOL wasCancelled = [transitionContext transitionWasCancelled];
                if (wasCancelled)
                    [toView removeFromSuperview];
                [transitionContext completeTransition:!wasCancelled];

            }];

        }
            break;

        default:
            break;
    }

}
@end

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/chocopoche/short_url.png?branch=master)](https://travis-ci.org/chocopoche/short_url)

Yet another url shortener built for Silex's PHP framework!

## Install

First, install the package and its dependencies:

    $ git clone https://github.com/chocopoche/short_url.git
    $ cd short_url
    $ curl -sS https://getcomposer.org/installer | php
    $ php composer.phar update

You may have to fix perms on the vendor/google directory, as its not world
readable after extracting the tarball.

    $ chmod -R a+rX vendor/google

Then creates the database, here is how to do so with an sqlite database:

    $ app/console db:create
    $ app/console db:import-schema

To run tests:

    $ vendor/bin/phpunit

To let users authenticate themselves to keep track of their urls, enable
Google OAuth2 by creating an application on the [console](https://code.google.com/apis/console/).

Configure your database in `app/bootstrap.php` and your GoogleOAuth client id
and secret in `config/app.php`.

## Features

Url slugs are generated with the SQL row id integer, which is hashed with a
*bidirectional encryption (Feistel cipher) that maps the integer space onto
itself*. Pasted from [https://gist.github.com/baldurrensch/3710618](https://gist.github.com/baldurrensch/3710618)

The resulting integer is then mapped with a bijective algorithm that uses a
configurable alphabet. Those functions are pasted from [http://www.flickr.com/groups/api/discuss/72157616713786392/](http://www.flickr.com/groups/api/discuss/72157616713786392/).

This way there is no need to store the short code in the database, and the short
codes generated are not obvious to decode just by reading them (I mean you
can't just increment the string to find the next record).

- /{short_code} redirects to the long url
- /{short_code}.png shows a QR Code
- /{short_code}/details shows the details available for the shortened url
- /last/ redirects to the last shortened url
- /shorten/ usefull with the help of the javascript bookmarklet
- /mine/ When you are authenticated, shorten urls will be associated with your
  account and you'll be able to see your last shorten urls.

**Bookmarklet**

HTML code to generate a link:

    Shorten

Or just add a bookmark with the following url:

    javascript:location='http://tmb.io/shorten/?url='+encodeURIComponent(location.href); void 0

## Live demo

A live demo is available at [tmb.io](http://tmb.io).

## API Doc

Available at [tmb.io/doc/](http://tmb.io/doc/).


text:
package org.yotchang4s.pixiv.illust

import org.yotchang4s.pixiv.http._
import org.yotchang4s.pixiv.tag._
import org.yotchang4s.pixiv._
import org.jsoup.Jsoup
import scala.util.Try
import scala.util.Success
import scala.util.Failure
import scala.util.Either
import org.jsoup.nodes.Document
import org.yotchang4s.pixiv.PixivException._
import org.yotchang4s.pixiv.user.User
import java.io.BufferedReader
import java.io.IOException
import java.util.Date

private[pixiv] trait IllustComponentImpl extends IllustComponent {
  private val illustUrlBase = "http://spapi.pixiv.net/iphone/illust.php?"

  class IllustRepositoryImpl extends IllustRepository {
    def findIllustBy(id: IllustId)(implicit config: Config): Either[PixivException, Illust] = {
      findIllustDetailBy(id)(config)
    }

    def findIllustDetailBy(id: IllustId)(implicit config: Config): Either[PixivException, IllustDetail] = {
      val illustDetailUrl = {
        val iu = illustUrlBase + "illust_id=" + id.value
        config.authToken match {
          case Some(a) => iu + "&PHPSESSID=" + a
          case None => iu
        }
      }

      try {
        val http = new Http
        http.userAgent("Yapix")

        val response = http.get(illustDetailUrl)
        val responseString = response.asString

        val illustDetail = IllustDetailCsvParser.parse(responseString)

        Right(illustDetail)
      } catch {
        case e: IOException => throw new PixivException(IOError, e)
        case e: Exception => throw new PixivException(UnknownError, e)
      }
    }
  }
}

private[pixiv] class IllustImpl(@transient val illust: IllustComponent,
  val identity: IllustId,
  val title: String,
  val thumbnailImageUrl: String) extends Illust {

  private[this] var illustDetail: Option[IllustDetail] = None

  def detail(implicit config: Config) = {
    synchronized {
      illustDetail match {
        case Some(i) => Right(i)
        case None =>
          illust.illust.findIllustDetailBy(identity)(config) match {
            case Right(i) =>
              illustDetail = Some(i)
              Right(i)
            case Left(e) => Left(e)
          }
      }
    }
  }

  override def toString = identity.value
}

private[pixiv] class IllustDetailImpl(
  val illust: Illust,
  val caption: String,
  val postedDateTime: Date,
  val middleImageUrl: String,
  val imageUrl: String,
  val tags: List[String],
  val pageCount: Int,
  val viewCount: Int,
  val evaluationCount: Int,
  val evaluation: Int,
  val bookmarkCount: Int,
  val user: User) extends IllustDetail {

  def detail(implicit config: Config): Right[PixivException, IllustDetail] = Right(this)
}


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the Cryptocurrent skill, try saying...

* *Alexa, ask Cryptocurrent what's the current price for dogecoin*

* *Alexa, ask Cryptocurrent for the current dogecoin price*

* *Alexa, ask Cryptocurrent for dogecoin*

Use Cryptocurrent to get the current prices for man popular cryptocurrencies such as Dogecoin. More currencies to come!

***

### Skill Details

* **Invocation Name:** crypto current
* **Category:** null
* **ID:** amzn1.ask.skill.936c3512-5fdf-409b-819e-79a871ae927d
* **ASIN:** B01KFZGCE2
* **Author:** Sharvil Parekh
* **Release Date:** August 19, 2016 @ 08:20:41
* **In-App Purchasing:** No


text:
require 'spec_helper'
require 'fileutils'

describe Flynn::Recipes::Refinerycms do
  it_should_behave_like('a recipe')
end


text:
<?php
/**
 * "Abstract" class for a number of different payment
 * types allowing a user to pay for something on a site.
 *
 * @see DPSPayment
 * @see WorldPayPayment
 * @see ChequePayment
 *
 * This can't be an abstract class because sapphire doesn't
 * support abstract DataObject classes.
 *
 * @package payment
 */
class Payment extends DataObject {

	/**
 	 * Incomplete (default): Payment created but nothing confirmed as successful
 	 * Success: Payment successful
 	 * Failure: Payment failed during process
 	 * Pending: Payment awaiting receipt/bank transfer etc
 	 */
	public static $db = array(
		'Status' => "Enum('Incomplete,Success,Failure,Pending','Incomplete')",
		'Amount' => 'Money',
		'Message' => 'Text',
		'IP' => 'Varchar',
		'ProxyIP' => 'Varchar',
		'PaidForID' => "Int",
		'PaidForClass' => 'Varchar',

		//This is used only when the payment is one of the recurring payments, when a scheduler is trying to
		//find which is the latest one for the recurring payments
		'PaymentDate' => "Date",

		//Usered for store any Exception during this payment Process.
		'ExceptionError' => 'Text'
	);

	public static $has_one = array(
		'RecurringPayment' => 'RecurringPayment',
		'PaidBy' => 'Member',
	);

	/**
	 * Instances of Payment supported (usable) on this site.
	 * @var array
	 */
	protected static $supported_methods = array(
		'ChequePayment' => 'Cheque'
	);

	/**
	 * Make payment table transactional.
	 */
	static $create_table_options = array(
		'MySQLDatabase' => 'ENGINE=InnoDB'
	);

	/**
	 * The currency code used for payments.
	 * @var string
	 */
	protected static $site_currency = 'USD';

	/**
	 * the testable form of the payment method
	 */
	protected static $testable_form = array();

	/**
	 * Set the currency code that this site uses.
	 * @param string $currency Currency code. e.g. "NZD"
	 */
	public static function set_site_currency($currency) {
		self::$site_currency = $currency;
	}

	/**
	 * Return the site currency in use.
	 * @return string
	 */
	public static function site_currency() {
		return self::$site_currency;
	}

	/**
	 * Set the payment types that this site supports.
	 * The classes should all be subclasses of Payment.
	 *
	 * @param array $methodMap A map of class names to human-readable descriptions of the payment methods.
	 */
	static function set_supported_methods($methodMap) {
		self::$supported_methods = $methodMap;
	}

	function populateDefaults() {
		parent::populateDefaults();

		$this->Amount->Currency = Payment::site_currency();
		$this->setClientIP();
 	}

	/**
	 * Set the IP address of the user to this payment record.
	 * This isn't perfect - IP addresses can be hidden fairly easily.
	 */
	function setClientIP() {
		$proxy = null;
		$ip = null;

		if(isset($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
		elseif(isset($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];
		else $ip = null;

		if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$proxy = $ip;
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}

		// Only set the IP and ProxyIP if none currently set
		if(!$this->IP) $this->IP = $ip;
		if(!$this->ProxyIP) $this->ProxyIP = $proxy;
	}

	/**
	 * Returns the Payment type currently in use.
	 * @return string
	 */
	function PaymentMethod() {
		if(isset(self::$supported_methods[$this->ClassName])) {
			return self::$supported_methods[$this->ClassName];
		}
	}

	/**
	 * Return a set of payment fields from all enabled
	 * payment methods for this site, given the . {@link Payment::set_supported_methods()}
	 * is used to define which methods are available.
	 *
	 * @return FieldSet
	 */
	static function combined_form_fields($amount) {

		// Create the initial form fields, which defines an OptionsetField
		// allowing the user to choose which payment method to use.
		$fields = new FieldSet(
			new HeaderField(_t('Payment.PAYMENTTYPE', 'Payment Type'), 3),
			new OptionsetField(
				'PaymentMethod',
				'',
				self::$supported_methods,
				array_shift(array_keys(self::$supported_methods))
			)
		);

		// If the user defined an numerically indexed array, throw an error
		if(ArrayLib::is_associative(self::$supported_methods)) {
			foreach(self::$supported_methods as $methodClass => $methodTitle) {

				// Create a new CompositeField with method specific fields,
				// as defined on each payment method class using getPaymentFormFields()
				$methodFields = new CompositeField(singleton($methodClass)->getPaymentFormFields());
				$methodFields->setID("MethodFields_$methodClass");
				$methodFields->addExtraClass('paymentfields');

				// Add those fields to the initial FieldSet we first created
				$fields->push($methodFields);
			}
		} else {
			user_error('Payment::set_supported_methods() requires an associative array.', E_USER_ERROR);
		}

		// Add the amount and subtotal fields for the payment amount
		$fields->push(new ReadonlyField('Amount', _t('Payment.AMOUNT', 'Amount'), $amount));

		return $fields;
	}

	/**
	 * Return the form requirements for all the payment methods.
	 *
	 * @return An array suitable for passing to CustomRequiredFields
	 */
	static function combined_form_requirements() {
		$requirements = array();

		// Loop on available methods
		foreach(self::$supported_methods as $method => $methodTitle) {
			$methodRequirements = singleton($method)->getPaymentFormRequirements();
			if($methodRequirements) {
				// Put limiters into the JS/PHP code to only use those requirements for this payment method
				$methodRequirements['js'] = "for(var i=0; i <= this.elements.PaymentMethod.length-1; i++) "
					. "if(this.elements.PaymentMethod[i].value == '$method' && this.elements.PaymentMethod[i].checked == true) {"
					. $methodRequirements['js'] . " } ";

				$methodRequirements['php'] = "if(\$data['PaymentMethod'] == '$method') { " .
					$methodRequirements['php'] . " } ";

				$requirements[] = $methodRequirements;
			}
		}

		return $requirements;
	}

	/**
	 * Return the payment form fields that should
	 * be shown on the checkout order form for the
	 * payment type. Example: for {@link DPSPayment},
	 * this would be a set of fields to enter your
	 * credit card details.
	 *
	 * @return FieldSet
	 */
	function getPaymentFormFields() {
		user_error("Please implement getPaymentFormFields() on $this->class", E_USER_ERROR);
	}

	/**
	 * Define what fields defined in {@link Order->getPaymentFormFields()}
	 * should be required.
	 *
	 * @see DPSPayment->getPaymentFormRequirements() for an example on how
	 * this is implemented.
	 *
	 * @return array
	 */
	function getPaymentFormRequirements() {
		user_error("Please implement getPaymentFormRequirements() on $this->class", E_USER_ERROR);
	}

	/**
	 * Perform payment processing for the type of
	 * payment. For example, if this was a credit card
	 * payment type, you would perform the data send
	 * off to the payment gateway on this function for
	 * your payment subclass.
	 *
	 * This is used by {@link OrderForm} when it is
	 * submitted.
	 *
	 * @param array $data The form request data - see OrderForm
	 * @param OrderForm $form The form object submitted on
	 */
	function processPayment($data, $form) {
		user_error("Please implement processPayment() on $this->class", E_USER_ERROR);
	}

	function getForm($whichTest){
		user_error("Please implement getForm() on $this->class", E_USER_ERROR);
	}

	function payAsRecurring() {
		user_error("Please implement payAsRecurring() on $this->class", E_USER_ERROR);
	}

	function handleError($e){
		$this->ExceptionError = $e->getMessage();
		$this->write();
	}

	function PaidObject(){
		return DataObject::get_by_id($this->PaidForClass, $this->PaidForID);
	}
}
abstract class Payment_Result {

	protected $value;

	function __construct($value = null) {
		$this->value = $value;
	}

	function getValue() {
		return $this->value;
	}

	abstract function isSuccess();

	abstract function isProcessing();

}
class Payment_Success extends Payment_Result {

	function isSuccess() {
		return true;
	}

	function isProcessing() {
		return false;
	}

}
class Payment_Processing extends Payment_Result {

	function isSuccess() {
		return false;
	}

	function isProcessing() {
		return true;
	}

}
class Payment_Failure extends Payment_Result {

	function isSuccess() {
		return false;
	}

	function isProcessing() {
		return false;
	}
}


text:
using System;

namespace FluidDbClient.Oracle
{
    public class OracleDatabase : Database
    {
        public OracleDatabase(string name, string connectionString, Action<string> log = null)
            : base(name, connectionString, new OracleDbProvider(connectionString), log)
        { }
    }
}


text:
#ifndef DFINSTANCE_LINUX_H
#define DFINSTANCE_LINUX_H
#include "dfinstance.h"
#include "dwarf.h"

class MemoryLayout;

class DFInstanceLinux : public DFInstance {
    Q_OBJECT
public:
	DFInstanceLinux(QObject *parent=0);
    ~DFInstanceLinux();

	// factory ctor
	bool find_running_copy();
    QVector<uint> enumerate_vector(const uint &addr);
    char read_char(const uint &addr);
    short read_short(const uint &addr);
    ushort read_ushort(const uint &addr);
    uint read_uint(const uint &addr);
    int read_int(const uint &addr);
    uint read_raw(const uint &addr, const uint &bytes, void *buffer);
	QString read_string(const uint &addr);

	// Writing
    uint write_raw(const uint &addr, const uint &bytes, void *buffer);
    uint write_string(const uint &addr, const QString &str);
    uint write_int(const uint &addr, const int &val);

    bool attach();
    bool detach();

protected:
    uint calculate_checksum();
};

#endif // DFINSTANCE_H


text:
package net.floodlightcontroller.statistics;

import java.util.Date;

import org.projectfloodlight.openflow.types.DatapathId;
import org.projectfloodlight.openflow.types.OFPort;
import org.projectfloodlight.openflow.types.U64;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import net.floodlightcontroller.statistics.web.SwitchPortBandwidthSerializer;

@JsonSerialize(using=SwitchPortBandwidthSerializer.class)
public class SwitchPortBandwidth {
	private DatapathId id;
	private OFPort pt;
	private U64 rx;
	private U64 tx;
	private Date time;
	private U64 rxValue;
	private U64 txValue;

	private SwitchPortBandwidth() {}
	private SwitchPortBandwidth(DatapathId d, OFPort p, U64 rx, U64 tx, U64 rxValue, U64 txValue) {
		id = d;
		pt = p;
		this.rx = rx;
		this.tx = tx;
		time = new Date();
		this.rxValue = rxValue;
		this.txValue = txValue;
	}

	public static SwitchPortBandwidth of(DatapathId d, OFPort p, U64 rx, U64 tx, U64 rxValue, U64 txValue) {
		if (d == null) {
			throw new IllegalArgumentException("Datapath ID cannot be null");
		}
		if (p == null) {
			throw new IllegalArgumentException("Port cannot be null");
		}
		if (rx == null) {
			throw new IllegalArgumentException("RX bandwidth cannot be null");
		}
		if (tx == null) {
			throw new IllegalArgumentException("TX bandwidth cannot be null");
		}
		if (rxValue == null) {
			throw new IllegalArgumentException("RX value cannot be null");
		}
		if (txValue == null) {
			throw new IllegalArgumentException("TX value cannot be null");
		}
		return new SwitchPortBandwidth(d, p, rx, tx, rxValue, txValue);
	}

	public DatapathId getSwitchId() {
		return id;
	}

	public OFPort getSwitchPort() {
		return pt;
	}

	public U64 getBitsPerSecondRx() {
		return rx;
	}

	public U64 getBitsPerSecondTx() {
		return tx;
	}

	protected U64 getPriorByteValueRx() {
		return rxValue;
	}

	protected U64 getPriorByteValueTx() {
		return txValue;
	}

	public long getUpdateTime() {
		return time.getTime();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((pt == null) ? 0 : pt.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SwitchPortBandwidth other = (SwitchPortBandwidth) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (pt == null) {
			if (other.pt != null)
				return false;
		} else if (!pt.equals(other.pt))
			return false;
		return true;
	}
}


text:
To write a gzip/zip file, libSBML needs to be configured and linked with
the zlib library at
compile time.  It also needs to be linked with the bzip2 library to write files in bzip2 format.  (Both
of these are the default configurations for libSBML.)  Errors about
unreadable files will be logged and this method will return
false if a compressed filename is given and libSBML was
not linked with the corresponding required library.


text:
package org.springframework.boot.docs.springbootfeatures.nosql;

import org.neo4j.driver.Driver;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.core.ReactiveDatabaseSelectionProvider;
import org.springframework.data.neo4j.core.transaction.ReactiveNeo4jTransactionManager;

@Configuration(proxyBeanMethods = false)
public class Neo4jReactiveTransactionManagerConfiguration {

	@Bean
	public ReactiveNeo4jTransactionManager reactiveTransactionManager(Driver driver,
			ReactiveDatabaseSelectionProvider databaseNameProvider) {
		return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider);
	}

}


text:
/// <reference path="APIRequest.d.ts" />
/// <reference path="APIResponse.d.ts" />
/// <reference path="BaseUIBridge.d.ts" />
/// <reference path="CommonUtil.d.ts" />
/// <reference path="IAdaptiveRPGroup.d.ts" />
/// <reference path="IBaseUI.d.ts" />
/// <reference path="IUI.d.ts" />

declare module Adaptive {
    /**
       @class Adaptive.UIBridge
       @extends Adaptive.BaseUIBridge
       Interface for Managing the UI operations

       @author Carlos Lozano Diez
       @since v2.0
    */
    class UIBridge extends BaseUIBridge implements IUI {
        /**
           @method constructor
           Default constructor.
        */
        constructor();
    }
}


text:
<?php

declare(strict_types = 1);

namespace ShieldSSO\Controller;

use Exception;
use ShieldSSO\Application;
use ShieldSSO\OAuth\Entity\User as OAuthUser;
use ShieldSSO\Contract\Repository\UserRepositoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Zend\Diactoros\Response;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Exception\OAuthServerException;

class OAuthController
{
    /**
     * @param Application $app
     * @param ServerRequestInterface $request
     *
     * @return ResponseInterface|RedirectResponse
     */
    public function authorizeAction(Application $app, ServerRequestInterface $request)
    {
        $response = new Response;

        try {
            /** @var AuthorizationServer $server */
            /** @var UserRepositoryInterface $userRepository */

            if (!$app['security.authorization_checker']->isGranted('ROLE_USER')) {
                $app['session']->getFlashBag()->add('auth_redirect', $request->getUri());

                return $app->redirect($app['url_generator']->generate('login'));
            }

            $server = $app['oauth.server'];
            $authRequest = $server->validateAuthorizationRequest($request);

            $token = $app['security.token_storage']->getToken();
            $user = $token->getUser();

            $oauthUser = new OAuthUser;
            $oauthUser->setLogin($user->getUsername());
            $authRequest->setUser($oauthUser);

            $authRequest->setAuthorizationApproved(true);

            return $server->completeAuthorizationRequest($authRequest, $response);
        } catch (OAuthServerException $exception) {
            return $exception->generateHttpResponse($response);
        } catch (Exception $exception) {
            $response->getBody()->write(json_encode(['message' => 'Unknown error occurred']));

            return $response->withStatus(500);
        }
    }

    /**
     * @param Application $app
     * @param ServerRequestInterface $request
     *
     * @return ResponseInterface
     */
    public function tokenAction(Application $app, ServerRequestInterface $request): ResponseInterface
    {
        $response = new Response;

        try {
            /** @var AuthorizationServer $server */

            $server = $app['oauth.server'];

            return $server->respondToAccessTokenRequest($request, $response);

        } catch (OAuthServerException $exception) {
            return $exception->generateHttpResponse($response);
        } catch (Exception $exception) {
            $response->getBody()->write(json_encode(['message' => 'Unknown error occurred']));

            return $response->withStatus(500);
        }
    }
}


text:
package org.olat.presentation.contactform;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.mail.Address;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.olat.data.basesecurity.Identity;
import org.olat.lms.commons.mail.ContactMessage;
import org.olat.presentation.framework.core.PresentationFrameworkTestContext;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.components.Component;
import org.olat.presentation.framework.core.control.Controller;
import org.olat.presentation.framework.core.control.DefaultController;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.system.event.Event;
import org.olat.system.mail.ContactList;
import org.olat.system.mail.ObjectMother;

@RunWith(Theories.class)
public class ContactFormControllerTest {
	private Identity theFromIdentity;
	private ContactMessage contactMessage;
	private ContactList contactList;
	private UserRequest ureq;
	private ContactUIModel contactUIModel;
	private WindowControl wControl;
	private ContactFormView contactFormView;
	private Controller source;
	private Component initialComponent;
	private MessageSendStatus sendStatus;

	private ArgumentCaptor<String> wControlMessageCaptor;
	private List<ContactList> toContactLists;

	@Before
	public void setup(){
		wControlMessageCaptor = ArgumentCaptor.forClass(String.class);

		Locale locale = Locale.ENGLISH;
		org.olat.lms.commons.i18n.ObjectMother.setupI18nManagerForFallbackLocale(locale);

		toContactLists = new ArrayList<ContactList>();
		contactList = new ContactList("simple");
		contactList.add(ObjectMother.createPeterBichselPrincipal());
		contactList.add(ObjectMother.createHeidiBirkenstockPrincipal());
		contactList.add(ObjectMother.createNicolas33Principal());
		toContactLists.add(contactList);

		theFromIdentity = ObjectMother.getIdentityFrom(ObjectMother.createHeidiBirkenstockPrincipal());
		contactMessage = new ContactMessage(theFromIdentity);
		contactMessage.addEmailTo(contactList);

		contactUIModel = new ContactUIModel(contactMessage);
		contactUIModel.copyToSenderSendTemplate = mock(ExceptionHandlingMailSendingTemplate.class);
		contactUIModel.toRecipientsSendTemplate = mock(ExceptionHandlingMailSendingTemplate.class);
		configureSendTemplatesForSuccess();

		PresentationFrameworkTestContext guiTestContext = org.olat.presentation.framework.core.ObjectMother.createPresentationFrameworkEnvironment(locale);
		ureq = guiTestContext.getUserRequest();
		wControl = guiTestContext.getWindowControl();

		contactFormView = mock(ContactFormView.class);
		when(contactFormView.getUreq()).thenReturn(ureq);
		when(contactFormView.getWindowControl()).thenReturn(wControl);

		source = mock(Controller.class);
		initialComponent = mock(Component.class);
		when(contactFormView.getInitialComponent(any(DefaultController.class))).thenReturn(initialComponent);
		when(contactFormView.is(source)).thenReturn(true);

	}

	@Test
	public void shouldSendMailToRecipientsOnlyWithoutException() {
		//setup
		configureViewForSuccessfullSentMessage();
		setCopyToSenderCheckbox(false);

		//exercise
		ContactFormController contactFormController = new ContactFormController(contactFormView, contactUIModel);
		contactFormController.event(ureq, source, Event.DONE_EVENT);

		//verify
		verifySendingToRecipientsOnly();
		verifySuccessFullSendingInfoMessageSet();
	}

	@Test
	public void shouldSendMailToRecipientsAndCopyToSenderWithoutException() {
		//setup
		configureViewForSuccessfullSentMessage();
		setCopyToSenderCheckbox(true);

		//exercise
		ContactFormController contactFormController = new ContactFormController(contactFormView, contactUIModel);
		contactFormController.event(ureq, source, Event.DONE_EVENT);

		//verify
		verifySendingToRecipientsAndCopyToSender();
		verifySuccessFullSendingInfoMessageSet();
	}

	@Theory
	public void shouldShowErrorMessageWhileSendingMailToRecipientsAndCopyToSenderWithFailure(SendStatusWithErrorMessage sendStatusWrapper) {
		//setup
		sendStatus = sendStatusWrapper.sendStatusWithErrorMessage;
		configureViewForSuccessfullSentMessage();
		when(contactUIModel.copyToSenderSendTemplate.send()).thenReturn(sendStatus);
		when(contactUIModel.toRecipientsSendTemplate.send()).thenReturn(sendStatus);
		setCopyToSenderCheckbox(true);

		//exercise
		ContactFormController contactFormController = new ContactFormController(contactFormView, contactUIModel);
		contactFormController.event(ureq, source, Event.DONE_EVENT);

		//verify
		verifySendingToRecipientsAndCopyToSender();
		verifyFailedSendingErrorMessageSet();
	}

	@Theory
	public void shouldShowInfoMessageWhileSendingMailToRecipientsAndCopyToSenderWithFailure(SendStatusWithInfoMessage sendStatusWrapper) {
		//setup
		sendStatus = sendStatusWrapper.sendStatusWithInfoMessage;
		configureViewForSuccessfullSentMessage();
		when(contactUIModel.copyToSenderSendTemplate.send()).thenReturn(sendStatus);
		when(contactUIModel.toRecipientsSendTemplate.send()).thenReturn(sendStatus);
		setCopyToSenderCheckbox(true);

		//exercise
		ContactFormController contactFormController = new ContactFormController(contactFormView, contactUIModel);
		contactFormController.event(ureq, source, Event.DONE_EVENT);

		//verify
		verifySendingToRecipientsAndCopyToSender();
		verifyFailedSendingInfoMessageSet();
	}

	/*
	 * the following construct is needed to have different sets of DataPoints to run with several @Theory annotated tests.
	 * In this case some MessageSendStatus are handled with an error message, others with an info message. To verify this
	 * different messages while avoiding code duplication and/or separate testclasses, the wrapping construct is choosen.
	 * see also http://stackoverflow.com/questions/7554458/how-to-attach-a-datapoint-with-a-theory
	 */
	public static class SendStatusWithErrorMessage {
		public MessageSendStatus sendStatusWithErrorMessage;
		public SendStatusWithErrorMessage(MessageSendStatus sendStatusWithErrorMessage){
			this.sendStatusWithErrorMessage = sendStatusWithErrorMessage;
		}
	}

	@DataPoint public static SendStatusWithErrorMessage messageFailed =
			new SendStatusWithErrorMessage(ExceptionHandlingMailSendingTemplate.handleMessagingException());
	@DataPoint public static SendStatusWithErrorMessage addressFailedOne =
			new SendStatusWithErrorMessage(ExceptionHandlingMailSendingTemplate.createSendProblemsCausedByAddresses(false));
	@DataPoint public static SendStatusWithErrorMessage addressFailedTwo =
			new SendStatusWithErrorMessage(ExceptionHandlingMailSendingTemplate.createPartialyNotSentMessageSendStatus(false));

	public static class SendStatusWithInfoMessage {
		public MessageSendStatus sendStatusWithInfoMessage;
		public SendStatusWithInfoMessage(MessageSendStatus sendStatusWithInfoMessage){
			this.sendStatusWithInfoMessage = sendStatusWithInfoMessage;
		}
	}
	@DataPoint public static SendStatusWithInfoMessage couldNotConnect =
			new SendStatusWithInfoMessage(ExceptionHandlingMailSendingTemplate.createCouldNotConnectToSmtpHostMessageSendStatus());
	@DataPoint public static SendStatusWithInfoMessage unknownSmtp =
			new SendStatusWithInfoMessage(ExceptionHandlingMailSendingTemplate.createUnknownSMTPHost());
	@DataPoint public static SendStatusWithInfoMessage noRecipients =
			new SendStatusWithInfoMessage(ExceptionHandlingMailSendingTemplate.createNoRecipientMessageSendStatus());
	private static Address[] invalidAddresses = null;
	{
		try {
			invalidAddresses = InternetAddress.parse("invalid1, invalid2, invalid3", false);
		} catch (AddressException e) {
			throw new RuntimeException(e);
		}
	}
	@DataPoint public static SendStatusWithInfoMessage invalidAddr =
			new SendStatusWithInfoMessage(ExceptionHandlingMailSendingTemplate.createInvalidAddressesMessageSendStatus(invalidAddresses));
	@DataPoint public static SendStatusWithInfoMessage invalidDomain =
			new SendStatusWithInfoMessage(ExceptionHandlingMailSendingTemplate.createInvalidDomainMessageSendStatus());
	@DataPoint public static SendStatusWithInfoMessage smtpAuthFailed =
			new SendStatusWithInfoMessage(ExceptionHandlingMailSendingTemplate.createAuthenticationFailedMessageSendStatus());

	private void configureSendTemplatesForSuccess() {
		sendStatus = ExceptionHandlingMailSendingTemplate.createSuccessfullSentEmailMessageStatus();
		when(contactUIModel.copyToSenderSendTemplate.send()).thenReturn(sendStatus);
		when(contactUIModel.toRecipientsSendTemplate.send()).thenReturn(sendStatus);
	}

	private void verifySuccessFullSendingInfoMessageSet() {
		verify(wControl,times(1)).setInfo(wControlMessageCaptor.capture());
		String infoMessage = wControlMessageCaptor.getValue();
		assertEquals("Your message was sent successfully.", infoMessage);
	}

	private void verifyFailedSendingErrorMessageSet(){
		verify(wControl,times(1)).setError(wControlMessageCaptor.capture());
		String errorMessage = wControlMessageCaptor.getValue();

		boolean isExpectedErrorMessage = errorMessage.startsWith("Your message could only be sent partially");
		isExpectedErrorMessage = isExpectedErrorMessage || errorMessage.startsWith("Your message could not be sent");

		assertTrue(isExpectedErrorMessage);
	}

	private void verifyFailedSendingInfoMessageSet(){
		verify(wControl,times(1)).setInfo(wControlMessageCaptor.capture());
		String infoMessage = wControlMessageCaptor.getValue();

		boolean isExpectedInfoMessage = infoMessage.startsWith("Sender's and/or recipient's address incorrect.");
		isExpectedInfoMessage = isExpectedInfoMessage || infoMessage.startsWith("Your message could not be sent");

		assertTrue(isExpectedInfoMessage);
	}

	private void verifySendingToRecipientsOnly() {
		verify(contactUIModel.copyToSenderSendTemplate,never()).send();
		verify(contactUIModel.toRecipientsSendTemplate,times(1)).send();
	}

	private void verifySendingToRecipientsAndCopyToSender(){
		verify(contactUIModel.copyToSenderSendTemplate,times(1)).send();
		verify(contactUIModel.toRecipientsSendTemplate,times(1)).send();
	}

	private void setCopyToSenderCheckbox(boolean enabled) {
		when(contactFormView.isTcpFrom()).thenReturn(enabled);
	}

	private void configureViewForSuccessfullSentMessage() {
		when(contactFormView.getSubject()).thenReturn("Subject from form");
		when(contactFormView.getBody()).thenReturn("My complete new body text as mail.");
		when(contactFormView.getAttachments()).thenReturn(null);
		when(contactFormView.getEmailToContactLists()).thenReturn(toContactLists);
	}

}


text:
package com.bridge.mycityvibes.ui;

import android.support.v4.media.MediaMetadataCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by abbey.ola on 23/12/2016.
 */

public class OfflineStore
{
	public static ArrayList<MediaMetadataCompat> offlinetracks = new ArrayList<>();

	public static List<MediaMetadataCompat> loveIt = new ArrayList<>();
	public static String yam;
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.RepresentationModel;
using static EVE_All_API.YamlUtils;

namespace EVE_All_API.StaticData
{
    public class EveUnit : YamlSequencePage<EveUnit>
    {
        #region caching
        public static void SaveAll(BinaryWriter save)
        {
            lock (units)
            {
                Loader.SaveDict<EveUnit>(units, save, Save);
            }
        }

        public static bool LoadAll(BinaryReader load)
        {
            lock (units)
            {
                units = Loader.LoadDict<EveUnit>(load, Load);
            }
            return true;
        }

        public static void Save(EveUnit attrib, BinaryWriter save)
        {
            attrib.Save(save);
        }

        public static EveUnit Load(BinaryReader load)
        {
            return new EveUnit(load);
        }

        public void Save(BinaryWriter save)
        {
            save.Write(unitID);
            Loader.Save(unitName, save);
            Loader.Save(displayName, save);
            Loader.Save(description, save);
        }

        private EveUnit(BinaryReader load)
        {
            unitID = load.ReadInt32();
            Loader.Load(out unitName, load);
            Loader.Load(out displayName, load);
            Loader.Load(out description, load);
        }
        #endregion caching

        private static Dictionary<int, EveUnit> units = new Dictionary<int, EveUnit>();
        public static EveUnit GetUnit(int _unitID)
        {
            if (units.ContainsKey(_unitID))
            {
                return units[_unitID];
            }
            return null;
        }

        public readonly int unitID;
        public readonly string unitName;
        public readonly string displayName;
        public readonly string description;

        public EveUnit(YamlNode node)
        {
            YamlMappingNode mapping = (YamlMappingNode)node;
            foreach (var entry in mapping.Children)
            {
                string paramName = entry.Key.ToString();
                switch (paramName)
                {
                    case "unitName":
                        unitName = entry.Value.ToString();
                        break;
                    case "unitID":
                        unitID = Int32.Parse(entry.Value.ToString());
                        break;
                    case "displayName":
                        displayName = entry.Value.ToString();
                        break;
                    case "description":
                        description = entry.Value.ToString();
                        break;
                    default:
                        System.Diagnostics.Debug.WriteLine("EveUnit unknown value:" + entry.Key + " = " + entry.Value);
                        break;
                }
            }
            units[unitID] = this;
        }

    }
}


text: CREATE INDEX `index_Keyword_keyword` ON `Keyword` (`keyword` )


text:
'use strict';

var isCallable = require('./is-callable');

module.exports = function (fn) {
	if (!isCallable(fn)) {
		throw new TypeError(fn + " is not a function");
	}
	return fn;
};


text:
s.Sound = new Class({
	toString: 'Sound',

	construct: function(options) {
		this.enabled = options.enabled !== undefined ? options.enabled : true;

		this.sounds = options.sounds || {};

		this.ready = {};

		this.preload();
	},

	destruct: function() {
		// TODO: Remove event listeners from Audio objects?
		this.ready = {};
	},

	preload: function() {
		// Preload each sound
		for (var name in this.sounds) {
			var soundUrl = this.sounds[name];

			// Create array to hold Audio instances
			this.ready[soundUrl] = [];

			// Create an instance of each sound
			this.ready[soundUrl].push(this.create(soundUrl));
		}
	},

	create: function(soundUrl) {
		// Create a new Audio object with the URL provided
		var soundObj = new Audio(soundUrl);

		var that = this;

		// When the Audio is done playing, add it back to the ready array
		soundObj.addEventListener('ended', function() {
			that.ready[soundUrl].push(soundObj);
		});

		return soundObj;
	},

	getInstance: function(name) {
		// Check if we have the requested sound
		var soundUrl = this.sounds[name];
		if (!soundUrl) {
			console.error('Bug: invalid sound requested');
			return false;
		}

		// Create ready array, if necessary. Only required if preload() isn't called
		if (!this.ready[soundUrl])
			this.ready[soundUrl] = [];

		// Check for an already created Audio instance to use
		var soundObj;
		if (this.ready[soundUrl].length) {
			// Pull the Audio instance from the ready array
			soundObj = this.ready[soundUrl].shift();
		}
		else {
			// Create a new Audio instance
			soundObj = this.create(soundUrl);
		}

		return soundObj;
	},

	play: function(name, volume) {
		if (!this.enabled)
			return false;

		var soundObj = this.getInstance(name);
		soundObj.volume = volume || 1;

		// Play the sound
		if (soundObj)
			soundObj.play();
	}
});


text:
package pl.touk.poker.android.content;

import android.content.SharedPreferences;

import javax.inject.Inject;

public class SharedPreferencesAdapter {

    private final SharedPreferences mSharedPreferences;

    @Inject
    public SharedPreferencesAdapter(SharedPreferences sharedPreferences) {
        mSharedPreferences = sharedPreferences;
    }

    public void persistenceAdd(String key, int value) {
        mSharedPreferences.edit().putInt(key, value).commit();
    }

    public void persistenceAdd(String key, String value) {
        mSharedPreferences.edit().putString(key, value).commit();
    }

    public int get(String key, int defaultValue) {
        return mSharedPreferences.getInt(key, defaultValue);
    }

    public String get(String key, String defaultValue) {
        return mSharedPreferences.getString(key, defaultValue);
    }

    public static SharedPreferencesAdapter create(SharedPreferences sharedPreferences) {
        return new SharedPreferencesAdapter(sharedPreferences);
    }
}


text:
package ch.becompany.akka.io.csv

import scala.util.{Success, Try}
import cats.data.Validated
import cats.data.Validated.{invalid, valid}

trait Parser[T] {
  def apply(s: String): Validated[String, T]
}

trait TryParser[T] extends Parser[T] {

  def parse(s: String): T

  def apply(s: String): Validated[String, T] =
    Validated.fromTry(Try(parse(s))).leftMap(t => s"${t.getClass.getName} ${t.getMessage}")
}

object TryParser {
  def apply[T](parseFunc: String => T): TryParser[T] = new TryParser[T] {
    def parse(s: String): T = parseFunc(s)
  }
}

object Parsers {

  implicit def optionParser[T](implicit parser: Parser[T]): Parser[Option[T]] =
    new Parser[Option[T]] {
      def apply(s: String) = s match {
        case "" => valid(None)
        case t => parser(t).map(Some(_))
      }
    }

  implicit val stringParser: Parser[String] = new Parser[String] {
    def apply(s: String) = valid(s)
  }

  implicit val intParser: Parser[Int] = TryParser(_.toInt)

  implicit val longParser: Parser[Long] = TryParser(_.toLong)

  implicit val doubleParser: Parser[Double] = TryParser(_.toDouble)

}


text:
#include "condor_common.h"
#include "condor_attributes.h"
#include "condor_config.h"
#include "starter.h"
#include "condor_ver_info.h"
#include "java_proc.h"
#include "java_config.h"

extern CStarter * Starter;

JavaProc::JavaProc( ClassAd * jobAd, const char *xdir ) : VanillaProc(jobAd)
{
	execute_dir = strdup(xdir);
}

JavaProc::~JavaProc()
{
	free(execute_dir);
}

int JavaProc::StartJob()
{

	MyString java_cmd;
	char* jarfiles = NULL;
	ArgList args;
	MyString arg_buf;

	// Since we are adding to the argument list, we may need to deal
	// with platform-specific arg syntax in the user's args in order
	// to successfully merge them with the additional java VM args.
	args.SetArgV1SyntaxToCurrentPlatform();

	// Construct the list of jar files for the command line
	// If a jar file is transferred locally, use its local name
	// (in the execute directory)
	// otherwise use the original name

	StringList jarfiles_orig_list;
	StringList jarfiles_local_list;
	StringList* jarfiles_final_list = NULL;

	if( JobAd->LookupString(ATTR_JAR_FILES,&jarfiles) ) {
		jarfiles_orig_list.initializeFromString( jarfiles );
		free( jarfiles );
		jarfiles = NULL;

		char * jarfile_name;
		const char * base_name;
		struct stat stat_buff;
		if( Starter->jic->iwdIsChanged() ) {
				// If the job's IWD has been changed (because we're
				// running in the sandbox due to file transfer), we
				// need to use a local version of the path to the jar
				// files, not the full paths from the submit machine.
			jarfiles_orig_list.rewind();
			while( (jarfile_name = jarfiles_orig_list.next()) ) {
					// Construct the local name
				base_name = condor_basename( jarfile_name );
				MyString local_name = execute_dir;
				local_name += DIR_DELIM_CHAR;
				local_name += base_name;

				if( stat(local_name.Value(), &stat_buff) == 0 ) {
						// Jar file exists locally, use local name
					jarfiles_local_list.append( local_name.Value() );
				} else {
						// Use the original name
					jarfiles_local_list.append (jarfile_name);
				}
			} // while(jarfiles_orig_list)

				// jarfiles_local_list is our real copy...
			jarfiles_final_list = &jarfiles_local_list;

		} else {  // !iwdIsChanged()

				// just use jarfiles_orig_list as our real copy...
			jarfiles_final_list = &jarfiles_orig_list;
		}
	}

	startfile.formatstr("%s%cjvm.start",execute_dir,DIR_DELIM_CHAR);
	endfile.formatstr("%s%cjvm.end",execute_dir,DIR_DELIM_CHAR);

	if( !java_config(java_cmd,&args,jarfiles_final_list) ) {
		dprintf(D_FAILURE|D_ALWAYS,"JavaProc: Java is not configured!\n");
		return 0;
	}

	JobAd->Assign(ATTR_JOB_CMD, java_cmd.Value());

	arg_buf.formatstr("-Dchirp.config=%s%cchirp.config",execute_dir,DIR_DELIM_CHAR);
	args.AppendArg(arg_buf.Value());

	char *jvm_args1 = NULL;
	char *jvm_args2 = NULL;
	MyString jvm_args_error;
	bool jvm_args_success = true;
	JobAd->LookupString(ATTR_JOB_JAVA_VM_ARGS1, &jvm_args1);
	JobAd->LookupString(ATTR_JOB_JAVA_VM_ARGS2, &jvm_args2);
	if(jvm_args2) {
		jvm_args_success = args.AppendArgsV2Raw(jvm_args2, &jvm_args_error);
	}
	else if(jvm_args1) {
		jvm_args_success = args.AppendArgsV1Raw(jvm_args1, &jvm_args_error);
	}
	free(jvm_args1);
	free(jvm_args2);
	if (!jvm_args_success) {
		dprintf(D_ALWAYS, "JavaProc: failed to parse JVM args: %s\n",
				jvm_args_error.Value());
		return 0;
	}

	args.AppendArg("CondorJavaWrapper");
	args.AppendArg(startfile.Value());
	args.AppendArg(endfile.Value());

	MyString args_error;
	if(!args.AppendArgsFromClassAd(JobAd,&args_error)) {
		dprintf(D_ALWAYS,"JavaProc: failed to read job arguments: %s\n",
				args_error.Value());
		return 0;
	}

	// We are just talking to ourselves, so it is fine to use argument
	// syntax compatible with this current version of Condor.
	CondorVersionInfo ver_info;
	if(!args.InsertArgsIntoClassAd(JobAd,&ver_info,&args_error)) {
		dprintf(D_ALWAYS,"JavaProc: failed to insert java job arguments: %s\n",
				args_error.Value());
		return 0;
	}

	dprintf(D_ALWAYS,"JavaProc: Cmd=%s\n",java_cmd.Value());
	MyString args_string;
	args.GetArgsStringForDisplay(&args_string);
	dprintf(D_ALWAYS,"JavaProc: Args=%s\n",args_string.Value());

	return VanillaProc::StartJob();
}

/*
Scan an exception hierarchy line.
Save the last exception name as the 'name', and look for
three specific middle types to save as the 'type'.
*/

int JavaProc::ParseExceptionLine( const char *line, MyString &exname, MyString &type )
{
	char *copy, *tok, *last;

	exname = "";
	type = "";

	copy = strdup(line);
	if(!copy) return 0;

	last = 0;
	tok = strtok(copy," \t\n");
	while(tok) {
		if(
			!strcmp(tok,"java.lang.Error") ||
			!strcmp(tok,"java.lang.LinkageError") ||
			!strcmp(tok,"java.lang.Exception") ||
			!strcmp(tok,"java.lang.RuntimeException")
		) {
			type = tok;
		}
		last = tok;
		tok = strtok(0," \t\n");
	}

	if(last) {
		exname = last;
		free(copy);
		return 1;
	} else {
		free(copy);
		return 0;
	}
}

/*
Read the exception line from the status file,
and stash the necessary info in this object.
*/

int JavaProc::ParseExceptionFile( FILE *file )
{
	if(!ex_hier.readLine(file)) return 0;
	if(!ex_hier.readLine(file)) return 0;

	/* Kill the newline at the end of the line */
	ex_hier.chomp();
	if(!ParseExceptionLine(ex_hier.Value(),ex_name,ex_type)) return 0;
	return 1;
}

/*
Given a POSIX exit status and the wrapper status files,
return exactly how the job exited.  Along the way, fill
in information about exceptions into the JobAd.
*/

java_exit_mode_t JavaProc::ClassifyExit( int status )
{
	FILE *file;
	int fields;

	char tmp[11]; // enough for "abnormal"
	tmp[0] = 0;

	int normal_exit = WIFEXITED(status);
	int exit_code = WEXITSTATUS(status);
	int sig_num = WTERMSIG(status);

	java_exit_mode_t exit_mode;

	if(normal_exit) {
		dprintf(D_ALWAYS,
		        "JavaProc: JVM exited normally with code %d\n",
		        exit_code);
		file = safe_fopen_wrapper_follow(startfile.Value(),"r");
		if(file) {
			dprintf(D_ALWAYS,
			        "JavaProc: Wrapper left start record %s\n",
			        startfile.Value());
			fclose(file);
			file = safe_fopen_wrapper_follow(endfile.Value(),"r");
			if(file) {
				dprintf(D_ALWAYS,
				        "JavaProc: Wrapper left end record %s\n",
				        endfile.Value());
				fields = fscanf(file,"%10s",tmp); // no more than sizeof(tmp)
				if(fields!=1) {
					dprintf(D_FAILURE|D_ALWAYS,
					        "JavaProc: Job called System.exit(%d)\n",
					        exit_code);
					exit_mode = JAVA_EXIT_NORMAL;
				} else if(!strcmp(tmp,"normal")) {
					dprintf(D_FAILURE|D_ALWAYS,
					        "JavaProc: Job returned from main()\n");
					exit_mode = JAVA_EXIT_NORMAL;
				} else if(!strcmp(tmp,"abnormal")) {
					ParseExceptionFile(file);
					if(!strcmp(ex_type.Value(),"java.lang.Error")) {
						dprintf(D_FAILURE|D_ALWAYS,
					            "JavaProc: Job threw a %s (%s), "
						            "will retry it later.\n",
						        ex_name.Value(),
						        ex_type.Value());
						exit_mode = JAVA_EXIT_SYSTEM_ERROR;
					} else {
						dprintf(D_FAILURE|D_ALWAYS,
						        "JavaProc: Job threw a %s (%s), "
						            "will return it to the user.\n",
						        ex_name.Value(),
						        ex_type.Value());
						exit_mode = JAVA_EXIT_EXCEPTION;
					}
				} else if(!strcmp(tmp,"noexec")) {
					ParseExceptionFile(file);
					dprintf(D_FAILURE|D_ALWAYS,
					        "JavaProc: Job could not be executed\n");
					exit_mode = JAVA_EXIT_EXCEPTION;
				} else {
					dprintf(D_FAILURE|D_ALWAYS,
					        "JavaProc: Unknown wrapper result '%s'\n",
					        tmp);
					exit_mode = JAVA_EXIT_SYSTEM_ERROR;
				}
				fclose(file);
			} else {
				dprintf(D_FAILURE|D_ALWAYS,
				        "JavaProc: Wrapper did not leave end record %s\n",
				        endfile.Value());
				dprintf(D_ALWAYS,
				        "JavaProc: Thus, job called System.exit(%d)\n",
				        exit_code);
				exit_mode = JAVA_EXIT_NORMAL;
			}
		} else {
			dprintf(D_FAILURE|D_ALWAYS,
			        "JavaProc: Wrapper did not leave start record.\n");
			dprintf(D_ALWAYS,
			        "JavaProc: I'll assume Java is misconfigured here.\n");
			exit_mode = JAVA_EXIT_SYSTEM_ERROR;
		}
	} else {
		dprintf(D_FAILURE|D_ALWAYS,
		        "JavaProc: JVM exited abnormally with signal %d\n",
		        sig_num);
		exit_mode = JAVA_EXIT_SYSTEM_ERROR;
	}

	dprintf(D_ALWAYS,"JavaProc: unlinking %s and %s\n",startfile.Value(),endfile.Value());

	priv_state s = set_priv(PRIV_ROOT);
	MSC_SUPPRESS_WARNING_FIXME(6031) // return value of unlink ignored.
	unlink(startfile.Value());
	MSC_SUPPRESS_WARNING_FIXME(6031) // return value of unlink ignored.
	unlink(endfile.Value());
	set_priv(s);

	return exit_mode;
}

/*
If the job exits with an exception, make it look
similar to exiting a C program with a signal.
Code that digs Java can look in the update ad for
the actual ExceptionName, and code that doesn't
dig Java still gets the general idea.
*/

#ifdef WIN32
#define EXCEPTION_EXIT_CODE 1
#else
#define EXCEPTION_EXIT_CODE (SIGTERM)
#endif

/*
If our job exited, then parse the output of the wrapper,
and return a POSIX status that resembles exactly what
happened.
*/
bool
JavaProc::JobReaper(int pid, int status)
{
	if(pid==JobPid) {
		dprintf(D_ALWAYS,"JavaProc: JVM pid %d has finished\n",pid);
		dprintf( D_FULLDEBUG, "pid=%d, JobPid=%d\n",pid,JobPid );

		switch( ClassifyExit(status) ) {
			case JAVA_EXIT_NORMAL:
				/* status is unchanged */
				break;
			case JAVA_EXIT_EXCEPTION:
				status = EXCEPTION_EXIT_CODE;
				break;
			default:
			case JAVA_EXIT_SYSTEM_ERROR:
				status = 0;
				requested_exit = true;
				break;
		}

		return VanillaProc::JobReaper(pid,status);

	} else {
		return false;
	}
}

/*
If any exception information has been filled in,
then throw it into the update ad.
*/

bool JavaProc::PublishUpdateAd( ClassAd* ad )
{
	if(ex_hier.Length()) {
		ad->Assign(ATTR_EXCEPTION_HIERARCHY,ex_hier.Value());
		dprintf(D_ALWAYS,"JavaProc: %s \"%s\"\n",ATTR_EXCEPTION_HIERARCHY,ex_hier.Value());
	}

	if(ex_name.Length()) {
		ad->Assign(ATTR_EXCEPTION_NAME,ex_name.Value());
		dprintf(D_ALWAYS,"JavaProc: %s \"%s\"\n", ATTR_EXCEPTION_NAME, ex_name.Value());
	}

	if(ex_type.Length()) {
		ad->Assign(ATTR_EXCEPTION_TYPE,ex_type.Value());
		dprintf(D_ALWAYS,"JavaProc: %s \"%s\"\n",ATTR_EXCEPTION_TYPE,ex_type.Value());
	}

	return VanillaProc::PublishUpdateAd(ad);
}

char const *
JavaProc::getArgv0()
{
	return NULL; // java does not like argv0 to be a lie, so don't lie
}


text:
io.js is built against modern versions of [V8](https://code.google.com/p/v8/). By keeping up-to-date with the latest releases of this engine we ensure new features from the [JavaScript ECMA-262 specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm) are brought to io.js developers in a timely manner, as well as continued performance and stability improvements.

Version 1.1.0 of io.js ships with V8 4.1.0.14, which includes ES6 features well beyond version 3.26.33 that will be shipped with joyent/node@0.12.x.

## No more --harmony flag

On joyent/node@0.12.x (V8 3.26), the `--harmony` runtime flag enabled all **completed**, **staged** and **in progress** ES6 features together, in bulk (with the exception of nonstandard/non-harmonious semantics for `typeof` which were hidden under `--harmony-typeof`). This meant that some really buggy or even broken features like [proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) were just as readily available for developers as [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*), which had very little or even no known-issues. As such, it was best practice to either enable only certain features by using specific runtime harmony feature flags (e.g. `--harmony-generators`), or simply enable all of them and then use a restricted subset.

With io.js@1.x (V8 4.1+), all that complexity goes away. All harmony features are now logically split into three groups for **shipping**, **staged** and **in progress** features:

*   All **shipping** features, the ones that V8 has considered stable, like [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*), [templates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings), [new string methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla#Additions_to_the_String_object) and many others are turned **on by default on io.js** and do **NOT** require any kind of runtime flag.
*   Then there are **staged** features which are almost-completed features that haven't been completely tested or updated to the latest spec yet and therefore are not considered stable by the V8 team (e.g. there might be some edge cases left to discover). This is probably the equivalent of the state of [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) on 3.26. These are the "use at your own risk" type of features that now require a runtime flag: `--es_staging` (or its synonym, `--harmony`).
*   Finally, all **in progress** features can be activated individually by their respective harmony flag (e.g. `--harmony_arrow_functions`), although this is highly discouraged unless for testing purposes.

## Which ES6 features ship with io.js by default (no runtime flag required)?

*   Block scoping

    *   [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)

    *   [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)

    *   `function`-in-blocks

    >As of v8 3.31.74.1, block-scoped declarations are [intentionally implemented with a non-compliant limitation to strict mode code](https://groups.google.com/forum/#!topic/v8-users/3UXNCkAU8Es). Developers should be aware that this will change as v8 continues towards ES6 specification compliance.

*   Collections

    *   [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)

    *   [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)

    *   [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)

    *   [WeakSet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet)*   [Generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*)

*   [Binary and Octal literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals)

*   [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

*   [New String methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla#Additions_to_the_String_object)

*   [Symbols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)

*   [Template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings)

You can view a more detailed list, including a comparison with other engines, on the [compat-table](https://kangax.github.io/compat-table/es6/) project page.

## Which ES6 features are behind the --es_staging flag?

*   [Classes](https://github.com/lukehoban/es6features#classes) (strict mode only)
*   [Object literal extensions](https://github.com/lukehoban/es6features#enhanced-object-literals)

*   [`Symbol.toStringTag`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) (user-definable results for `Object.prototype.toString`)

## I have my infrastructure set up to leverage the --harmony flag. Should I remove it?

The current behaviour of the `--harmony` flag on io.js is to enable **staged** features only. After all, it is now a synonym of `--es_staging`. As mentioned above, these are completed features that have not been considered stable yet. If you want to play safe, especially on production environments, consider removing this runtime flag until it ships by default on V8 and, consequently, on io.js. If you keep this enabled, you should be prepared for further io.js upgrades to break your code if V8 changes their semantics to more closely follow the standard.

## How do I find which version of V8 ships with a particular version of io.js?

io.js provides a simple way to list all dependencies and respective versions that ship with a specific binary through the `process` global object. In case of the V8 engine, type the following in your terminal to retrieve its version:

```sh
iojs -p process.versions.v8
```


text:
package org.teachingkidsprogramming.section04mastery;

import java.awt.Color;

import org.teachingextensions.logo.Tortoise;
import org.teachingextensions.logo.utils.ColorUtils.ColorWheel;
import org.teachingextensions.logo.utils.ColorUtils.PenColors;

public class DigiFlower
{
  public static void main(String[] args)
  {
    Tortoise.show();
    Tortoise.setSpeed(10);
    Tortoise.getBackgroundWindow().setBackground(PenColors.Grays.Silver);
    //        Do the following 15 times --#13.1
    for (int i = 0; i < 15; i++)
      createColorPalette();
    drawOctogon();
    Tortoise.turn(360 / 15);
  }
  private static void drawOctogon()
  {
    //    ------------- Recipe for drawOctogon --#10.2
    for (int i = 0; i < 8; i++)
    {
      Tortoise.setPenColor(ColorWheel.getNextColor());
      Tortoise.move(50);
      Tortoise.turn(360 / 8);
    }
    //    ------------- End of drawOctogon recipe --#10.3
  }
  private static void createColorPalette()
  {
    //    ------------- Recipe for createColorPalette --#9.2
    Color color1 = PenColors.Reds.Red;
    Color color2 = PenColors.Oranges.DarkOrange;
    Color color3 = PenColors.Yellows.Gold;
    Color color4 = PenColors.Yellows.Yellow;
    ColorWheel.addColor(color1);
    ColorWheel.addColor(color2);
    ColorWheel.addColor(color3);
    ColorWheel.addColor(color4);
    ColorWheel.addColor(color4);
    ColorWheel.addColor(color3);
    ColorWheel.addColor(color2);
    ColorWheel.addColor(color1);
    //    ------------- End of createColorPalette recipe --#9.3
  }
}


text:
import Ember from "ember";
export default Ember.Component.extend({
  didInitAttrs() {
    Ember.run.schedule("afterRender", function() {
      Ember.$(document).foundation();
    });
  },
});


text:
Retrieve a specific user record.

{@inheritdoc}

### get_list

Retrieve a collection of user records.

{@inheritdoc}

### create

Create a new user record.
The created record is returned in the response.

{@inheritdoc}

{@request:json_api}
Example:

`</api/users>`

```JSON
{
   "data":{
      "type":"users",
      "attributes":{
         "username":"testapiuser",
         "email":"testuser@oroinc.com",
         "firstName":"Bob",
         "lastName":"Fedeson",
         "password":"Password1!"
      },
      "relationships":{
         "owner":{
            "data":{
               "type":"businessunits",
               "id":"1"
            }
         },
         "organization":{
            "data":{
               "type":"organizations",
               "id":"1"
            }
         }
      }
   }
}
```
{@/request}

### update

Edit a specific user record.

{@inheritdoc}

{@request:json_api}
Example:

`</api/users/54>`

```JSON
{
   "data":{
      "type":"users",
      "id":"54",
      "attributes":{
         "phone":"455-78-54",
         "title":"administrator",
         "password_expires_at":"2017-01-01T00:00:00Z",
         "middleName":"Karl",
         "birthday":"1964-07-05",
         "enabled":true
      },
      "relationships":{
         "businessUnits":{
            "data":[
               {
                  "type":"businessunits",
                  "id":"1"
               }
            ]
         },
         "roles":{
            "data":[
               {
                  "type":"userroles",
                  "id":"3"
               }
            ]
         },
         "organizations":{
            "data":[
               {
                  "type":"organizations",
                  "id":"1"
               },
               {
                  "type":"organizations",
                  "id":"2"
               }
            ]
         },
         "auth_status":{
            "data":{
               "type":"authstatuses",
               "id":"active"
            }
         }
      }
   }
}
```
{@/request}

### delete

Delete a specific user record.

{@inheritdoc}

### delete_list

Delete a collection of user records.
The list of records that will be deleted, could be limited by filters.

{@inheritdoc}

## FIELDS

### id

#### update

{@inheritdoc}

**The required field**

### emails

An array of email addresses.

Format of data: [{"email": first@email.com}, {"email": second@email.com}]

#### create, update

An array of email addresses.

Format of data: [{"email": first@email.com}, {"email": second@email.com}]

Data should contain full collection of email addresses of the business customer.

### username

#### create

{@inheritdoc}

**The required field**

#### update

{@inheritdoc}

**Please note:**

*This field is **required** and must remain defined.*

### email

#### create

{@inheritdoc}

**The required field**

#### update

{@inheritdoc}

**Please note:**

*This field is **required** and must remain defined.*

### firstName

#### create

{@inheritdoc}

**The required field**

#### update

{@inheritdoc}

**Please note:**

*This field is **required** and must remain defined.*

### lastName

#### create

{@inheritdoc}

**The required field**

#### update

{@inheritdoc}

**Please note:**

*This field is **required** and must remain defined.*

### password

#### create

{@inheritdoc}

**Please note:**

*The password must conform to the system security policy.*

**The required field**

## SUBRESOURCES

### avatar

#### get_subresource

Retrieve the avatar configured for a specific user record.

#### get_relationship

Retrieve the ID of the avatar configured for a specific user.

#### update_relationship

Replace the avatar for a specific user.

{@request:json_api}
Example:

`</api/users/1/relationships/avatar>`

```JSON
{
  "data": {
    "type": "files",
    "id": "1"
  }
}
```
{@/request}

### businessUnits

#### get_subresource

Retrieve the business unit records that a specific user has access to.

#### get_relationship

Retrieve the IDs of the business units that a specific user has access to.

#### add_relationship

Set the business units that a specific user has access to.

{@request:json_api}
Example:

`</api/users/1/relationships/businessUnits>`

```JSON
{
  "data": [
    {
      "type": "businessunits",
      "id": "1"
    },
    {
      "type": "businessunits",
      "id": "2"
    }
  ]
}
```
{@/request}

#### update_relationship

Replace the business units that a specific user has access to.

{@request:json_api}
Example:

`</api/users/1/relationships/businessUnits>`

```JSON
{
  "data": [
    {
      "type": "businessunits",
      "id": "1"
    },
    {
      "type": "businessunits",
      "id": "2"
    }
  ]
}
```
{@/request}

#### delete_relationship

Remove the business units that a specific user has access to.

### groups

#### get_subresource

Retrieve the group records that a specific user belongs to.

#### get_relationship

Retrieve the IDs of the groups that a specific user belongs to.

#### add_relationship

Set the groups that a specific user belongs to.

{@request:json_api}
Example:

`</api/users/1/relationships/groups>`

```JSON
{
  "data": [
    {
      "type": "usergroups",
      "id": "1"
    },
    {
      "type": "usergroups",
      "id": "2"
    }
  ]
}
```
{@/request}

#### update_relationship

Replace the groups that a specific user belongs to.

{@request:json_api}
Example:

`</api/users/1/relationships/groups>`

```JSON
{
  "data": [
    {
      "type": "usergroups",
      "id": "1"
    },
    {
      "type": "usergroups",
      "id": "2"
    }
  ]
}
```
{@/request}

#### delete_relationship

Remove the groups that a specific user belongs to.

### organization

#### get_subresource

Retrieve the record of the organization that a specific user belongs to.

#### get_relationship

Retrieve the ID of the organization that a specific user belongs to.

#### update_relationship

Replace the organization that a specific user belongs to.

{@request:json_api}
Example:

`</api/users/1/relationships/organization>`

```JSON
{
  "data": {
    "type": "organizations",
    "id": "1"
  }
}
```
{@/request}

### organizations

#### get_subresource

Retrieve the records of the organizations that a specific user has access to.

#### get_relationship

Retrieve the IDs of the organizations that a specific user has access to.

#### add_relationship

Set the organizations that a specific user has access to.

{@request:json_api}
Example:

`</api/users/1/relationships/organizations>`

```JSON
{
  "data": [
    {
      "type": "organizations",
      "id": "1"
    },
    {
      "type": "organizations",
      "id": "2"
    },
    {
      "type": "organizations",
      "id": "5"
    }
  ]
}
```
{@/request}

#### update_relationship

Replace the organizations that a specific user has access to.

{@request:json_api}
Example:

`</api/users/1/relationships/organizations>`

```JSON
{
  "data": [
    {
      "type": "organizations",
      "id": "1"
    },
    {
      "type": "organizations",
      "id": "2"
    },
    {
      "type": "organizations",
      "id": "5"
    }
  ]
}
```
{@/request}

#### delete_relationship

Remove the organizations that a specific user has access to.

### owner

#### get_subresource

Retrieve the record of the business unit that is the owner of a specific user.

#### get_relationship

Retrieve the ID of the business unit that is the owner of a specific user.

#### update_relationship

Replace the owner of a specific user.

{@request:json_api}
Example:

`</api/users/1/relationships/owner>`

```JSON
{
  "data": {
    "type": "businessunits",
    "id": "1"
  }
}
```
{@/request}

### roles

#### get_subresource

Retrieve the records of the roles that are assigned to a specific user.

#### get_relationship

Retrieve the IDs of the roles that are assigned to a specific user.

#### add_relationship

Set the roles that will be assigned to a specific user.

{@request:json_api}
Example:

`</api/users/1/relationships/roles>`

```JSON
{
  "data": [
    {
      "type": "userroles",
      "id": "3"
    }
  ]
}
```
{@/request}

#### update_relationship

Replace the roles for a specific user.

{@request:json_api}
Example:

`</api/users/1/relationships/roles>`

```JSON
{
  "data": [
    {
      "type": "userroles",
      "id": "3"
    }
  ]
}
```
{@/request}

#### delete_relationship

Remove the roles that are assigned to a specific user.

### auth_status

#### get_subresource

Retrieve the user's authentication status.

#### get_relationship

Retrieve the ID of the user's authentication status.

#### update_relationship

Replace the user's authentication status.

{@request:json_api}
Example:

`</api/users/1/relationships/auth_status>`

```JSON
{
  "data": {
    "type": "authstatuses",
    "id": "active"
  }
}
```
{@/request}


text:
package org.easyaccess.simplemenus;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import org.easyaccess.EasyAccessActivity;
import org.easyaccess.R;
import org.easyaccess.Utils;

public class InternetMenu extends EasyAccessActivity {

	/** Create the Email menu activity **/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.internet);
		super.onCreate(savedInstanceState);

		/** Launch respective app, depending on which button is pressed **/
		/**
		Button btnChrome = (Button) v.findViewById(R.id.btnChrome);
		btnChrome.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {

					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse("http://www.google.com"));
					startActivity(intent);

				} catch (Exception e) {
					launchOrDownloadFromFragment("com.android.chrome");
				}
			}
		});
		**/

		setButtonClickUri(R.id.btnChrome, "com.android.chrome");
		setButtonClickUri(R.id.btnFirefox, "org.mozilla.firefox_beta");

		/** Put most everything before here **/
	}

	@Override
	protected void onResume() {
		LinearLayout layout = (LinearLayout) findViewById(R.id.internetMenu);
		// Apply the selected font color, font size and font type to the
		// activity

		Utils.applyFontColorChanges(getApplicationContext(), layout);
		Utils.applyFontSizeChanges(getApplicationContext(), layout);
		Utils.applyFontTypeChanges(getApplicationContext(), layout);

		super.onResume();
	}

}


text:
class EventNameForPublishableEvents < ActiveRecord::Migration
  def self.up
    add_column "publishable_events", "event_name", :string
  end

  def self.down
    remove_column "publishable_events", "event_name"
  end
end


text:
#include "test/core/end2end/end2end_tests.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <grpc/byte_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpc/support/useful.h>
#include "test/core/end2end/cq_verifier.h"

enum { TIMEOUT = 200000 };

static void *tag(gpr_intptr t) { return (void *)t; }

static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,
                                            const char *test_name,
                                            grpc_channel_args *client_args,
                                            grpc_channel_args *server_args) {
  grpc_end2end_test_fixture f;
  gpr_log(GPR_INFO, "%s/%s", test_name, config.name);
  f = config.create_fixture(client_args, server_args);
  config.init_client(&f, client_args);
  config.init_server(&f, server_args);
  return f;
}

static gpr_timespec n_seconds_time(int n) {
  return GRPC_TIMEOUT_SECONDS_TO_DEADLINE(n);
}

static gpr_timespec five_seconds_time(void) { return n_seconds_time(5); }

static void drain_cq(grpc_completion_queue *cq) {
  grpc_event *ev;
  grpc_completion_type type;
  do {
    ev = grpc_completion_queue_next(cq, five_seconds_time());
    GPR_ASSERT(ev);
    type = ev->type;
    grpc_event_finish(ev);
  } while (type != GRPC_QUEUE_SHUTDOWN);
}

static void shutdown_server(grpc_end2end_test_fixture *f) {
  if (!f->server) return;
  grpc_server_shutdown(f->server);
  grpc_server_destroy(f->server);
  f->server = NULL;
}

static void shutdown_client(grpc_end2end_test_fixture *f) {
  if (!f->client) return;
  grpc_channel_destroy(f->client);
  f->client = NULL;
}

static void end_test(grpc_end2end_test_fixture *f) {
  shutdown_server(f);
  shutdown_client(f);

  grpc_completion_queue_shutdown(f->server_cq);
  drain_cq(f->server_cq);
  grpc_completion_queue_destroy(f->server_cq);
  grpc_completion_queue_shutdown(f->client_cq);
  drain_cq(f->client_cq);
  grpc_completion_queue_destroy(f->client_cq);
}

/* Cancel before invoke */
static void test_cancel_before_invoke(grpc_end2end_test_config config) {
  grpc_call *c;
  grpc_end2end_test_fixture f = begin_test(config, __FUNCTION__, NULL, NULL);
  gpr_timespec deadline = five_seconds_time();
  cq_verifier *v_client = cq_verifier_create(f.client_cq);

  c = grpc_channel_create_call_old(f.client, "/foo", "foo.test.google.fr",
                                   deadline);
  GPR_ASSERT(c);

  GPR_ASSERT(GRPC_CALL_OK == grpc_call_cancel(c));

  GPR_ASSERT(GRPC_CALL_OK ==
             grpc_call_invoke_old(c, f.client_cq, tag(2), tag(3), 0));
  cq_expect_client_metadata_read(v_client, tag(2), NULL);
  cq_expect_finished_with_status(v_client, tag(3), GRPC_STATUS_CANCELLED, NULL,
                                 NULL);
  cq_verify(v_client);

  grpc_call_destroy(c);

  cq_verifier_destroy(v_client);
  end_test(&f);
  config.tear_down_data(&f);
}

void grpc_end2end_tests(grpc_end2end_test_config config) {
  test_cancel_before_invoke(config);
}