text:
class Handicap < ApplicationRecord
  has_many :teams
  scope :srs_keelboat, -> { where(type: 'SrsKeelboat')}
  scope :srs_multihull, -> { where(type: 'SrsMultihull')}
  scope :srs_dingy, -> { where(type: 'SrsDingy')}
  scope :srs_certificate, -> { where(type: 'SrsCertificate')}
  scope :srs_multihull_certificate, -> { where(type: 'SrsMultihullCertificate')}
  scope :sxk_certificate, -> { where(type: 'SxkCertificate')}
  scope :active, -> { where("expired_at IS ?", nil)}

  # The column 'name' is boat_type_name.
  #
  # For all certificates, the 'registry_id' is the unique identifier.
  # For non-certificates, the 'name' (boat type name) is the unique identifier.
  # This gives the invariant: (type, registry_id, name, expired_at) is unique.

  default_scope { order 'name', 'sail_number' }

  def description
    if not self.expired_at.nil?
      exp = "Utgått #{self.expired_at} - "
    else
      exp = ""
    end
    if not self.boat_name.nil?
      boatname = " #{self.boat_name}"
    else
      boatname = ""
    if not self.srs.nil?
      srs = "SRS: #{self.srs}, "
    else
      srs = ""
    end
    end
    "#{exp}#{self.name}#{boatname}, #{srs}SXK: #{self.sxk}, #{Handicap.short_types[self.type]}"
  end

  def short_description
    if not self.expired_at.nil?
      exp = "Utgått #{self.expired_at} - "
    else
      exp = ""
    end
    if not self.boat_name.nil?
      boatname = " #{self.boat_name}"
    else
      boatname = ""
    end
    if not self.srs.nil?
      srs = "SRS: #{self.srs}, "
    else
      srs = ""
    end
    "#{exp}#{self.name}#{boatname}, #{srs}SXK: #{self.sxk}"
  end

  def self.types
    types = {}
    types['SxkCertificate'] = 'SXK-mätbrev (för individuell båt)'
    types['SrsCertificate'] = 'SRS-mätbrev enskrov (för individuell båt)'
    types['SrsMultihullCertificate'] = 'SRS-mätbrev flerskrov (för individuell båt)'
    types['SrsKeelboat'] = 'Enskrovsbåt enligt SRS-tabellen'
    types['SrsMultihull'] = 'Flerskrovsbåt enligt SRS-tabellen'
    types['SrsDingy'] = 'Jolle enligt SRS-tabellen'
    types['SoonSrsCertificate'] = 'Kommer att skaffa SRS-mätbrev'
    types['SoonSxkCertificate'] = 'Kommer att skaffa SXK-mätbrev'

    types
  end

  def self.short_types
    types = {}
    types['SxkCertificate'] = 'SXK-mätbrev'
    types['SrsCertificate'] = 'SRS-mätbrev enskrov'
    types['SrsMultihullCertificate'] = 'SRS-mätbrev flerskrov'
    types['SrsKeelboat'] = 'SRS enskrov'
    types['SrsMultihull'] = 'SRS flerskrov'
    types['SrsDingy'] = 'SRS jolle'
    types['SoonSrsCertificate'] = 'Interimistiskt'
    types['SoonSxkCertificate'] = 'Interimistiskt'

    types
  end

  def self.import(type, source, external_system, handicaps, user, dryrun=false)
    yesterday = DateTime.now.in_time_zone.end_of_day - 1.day
    # keep track of all active handicaps
    cur_handicaps = Hash.new
    for h in Handicap.active.where("type = ?", type)
      cur_handicaps[h.id] = true
    end
    isCert = (type == 'SrsCertificate' ||
              type == 'SrsMultihullCertificate' ||
              type == 'SxkCertificate')
    for h in handicaps
      srs = h[:srs]
      if not srs.nil?
        sxk = (srs * 1.22).round(2)
      else
        sxk = h[:sxk]
      end
      # check if a current handicap exists
      if isCert
        cur = Handicap.find_by(type: type,
                               registry_id: h[:registry_id],
                               expired_at: nil)
      else
        cur = Handicap.find_by(type: type,
                               name: h[:name],
                               expired_at: nil)
      end
      is_new = cur.nil?
      is_expired = (not h[:expired_at].nil?)
      has_changed = (not is_new and
                     (cur.sxk != sxk or (not srs.nil? and cur.srs != srs)))

      cur_handicaps.delete(cur.id) unless cur.nil?

      if is_new and is_expired
        # skip expired handicaps that we don't have as current
        next
      end

      if not(is_new) and (has_changed or is_expired)
        # we found an existing handicap that has a new sxk rating, or
        # has expired.
        # we need to mark it as expired, and check if there are any
        # active teams that use this handicap.  these teams need to set
        # a new handicap.
        if has_changed
          puts "Changed rating to #{sxk}: #{cur.description} (#{cur.id})"
        else
          puts "Expired handicap: #{cur.description} (#{cur.id})"
        end
        Team.handicap_changed(cur.id, user, dryrun)
        if not is_expired
          cur.expired_at = yesterday
        else
          cur.expired_at = h[:expired_at]
        end
        cur.save! unless dryrun
      end

      # safety check
      if sxk.nil? or not (sxk > 0)
        if isCert
          id = h[:registry_id]
        else
          id = h[:name]
        end
        puts "Handicap #{id} has sxk #{sxk}, ignoring"
        next
      end

      # we need to create a new handicap if this is new and not expired,
      # or if this is a changed existing and not expired.
      if (is_new or has_changed) and not(is_expired)
        case type
        when 'SrsKeelboat'
          newh = SrsKeelboat.new
        when 'SrsMultihull'
          newh = SrsMultihull.new
        when 'SrsDingy'
          newh = SrsDingy.new
        when 'SrsCertificate'
          newh = SrsCertificate.new
        when 'SrsMultihullCertificate'
          newh = SrsMultihullCertificate.new
        when 'SxkCertificate'
          newh = SxkCertificate.new
        end
        newh.srs = srs
        newh.sxk = sxk
        newh.source = source
        newh.external_system = external_system
        newh.registry_id = h[:registry_id]
        newh.name = h[:name]
        newh.owner_name = h[:owner_name]
        newh.boat_name = h[:boat_name]
        newh.sail_number = h[:sail_number]
        newh.expired_at = h[:expired_at]
        puts "Add handicap: #{newh.description}"
        newh.save! unless dryrun
      end
    end
    # cur_handicaps now contains handicaps that need to be expired
    for cur_id in cur_handicaps
      cur = Handicap.find(cur_id[0])
      puts "Remove: handicap #{cur.description} (#{cur.id})"
      Team.handicap_changed(cur.id, user, dryrun)
      cur.expired_at = yesterday
      cur.save! unless dryrun
    end
  end

end


text:
<?xml version='1.0' encoding='utf-8'?>
<TEI xmlns="http://www.tei-c.org/ns/1.0" xml:id="PrL-0223">
   <teiHeader>
      <fileDesc>
         <titleStmt>
            <title>Private Letter: 1867 September 2: to Mantell</title>
            <author>
               <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/9614/">William Colenso</name>
            </author>
         </titleStmt>
         <publicationStmt>

         </publicationStmt>
         <sourceDesc>

ATL Ms-papers-0083-261.

         </sourceDesc>
      </fileDesc>
      <profileDesc>
         <correspDesc>

               <correspAction type="received">
                  <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/73192/">Mantell</name>
               </correspAction>
            </correspDesc>
         <creation xmlns:tei="http://www.tei-c.org/ns/1.0">
            <date when="1867-09-02">1867 September 2</date>
         </creation>
      </profileDesc>
   </teiHeader>
   <text>
      <front>

1867 September 2: to Mantell<note xml:id="ftn2-143" place="foot" n="143"> ATL Ms-papers-0083-261.</note>

      </front>

Auckland<lb/>Sept 2/67

Hon. Walter Mantell<lb/>&c               &c

My dear Sir

I have your note of this mg., wishing me to inform you, of "Mr Donaldson's efforts at Napier, their utility."—

Unfortunately, I cannot say much, if anything, in his favor.

1<hi rend="sup">st</hi>. from his antecedents: I should infer he would never be <hi rend="italic">stable</hi>.

2<hi rend="sup">nd</hi>. from what I have heard Karaitiana and other Natives say, I was of opinion, they did not value his exertions too highly.—

3<hi rend="sup">rd.</hi> I look upon his plan (as far as he has told me of it, & let it be known through the Papers—in which he is a terrible scribbler)—as a highly questionable one—as to its usefulnes, or even being attainable.

4. I know nothing of <hi rend="italic">his peculiar fitness </hi>for the office of teaching Maories; am rather inclined to doubt it.

5. He is <hi rend="italic">now</hi> thoroughly sober: but <hi rend="italic">you </hi>
            <hi rend="underline italic">know</hi> what the Maories say of a man who <hi rend="italic">was </hi>t'other way; and who seeks to get a living by living in their <hi rend="italic">pas</hi> to teach them: they cannot (or rarely) appreciate a good motive. D's. <hi rend="italic">seeking</hi> to do them good (in his way) actually operates against him.— As to, "whether the Provl. Authors. will join the Genl. Govt. in aiding &c."—

I don't think they would:—

1. Because D. sent in a petition for aid, 6 months ago, which led to a debate & was refused.– –<lb/>  α. Bec. did not believe in its practicality<lb/>  β. Bec. so much<hi rend="italic">set aside </hi>for <hi rend="italic">Maori </hi>Teaching already in the Prov:—Grey gave 3, or 4000 ac. of the <hi rend="italic">best land</hi> of Prov., & the Natives gave same amount—a property worth ₤10,000.— <lb/>  γ. S. Williams at Te Aute has had, from ₤7000 yearly granted for Schools, ₤1000. or more; &<hi rend="italic">has not a single scholar</hi>!! (This I had from <hi rend="italic">his</hi> Natives just before I left.)<lb/>  δ. Bec. Donaldson's plan runs counter to the Bp's.—whose aim is & has been to draw away the N. youth from their<hi rend="italic">pas</hi> to the <hi rend="italic">quasi </hi>College.—

I think I have said enough: you will see I have written <hi rend="italic">confidentially </hi>to you.

            <hi rend="italic">Ormond </hi>is a Mr. of Provl. Council, & of Exec. Cl. also; he could give you (perhaps) more information.

                     In haste

             Yours faithfully

                             Wm. Colenso.

   </text>
</TEI>

redpajama_set_name: RedPajamaGithub


text:
//
//  WMNavigationController.m
//  QQSlideMenu
//
//  Created by wamaker on 15/6/15.
//  Copyright (c) 2015年 wamaker. All rights reserved.
//

#import "WMNavigationController.h"
#import "WMNavigationInteractiveTransition.h"

@interface WMNavigationController () <UIGestureRecognizerDelegate>
@property (nonatomic, weak) UIPanGestureRecognizer *popRecognizer;
@property (nonatomic, strong) WMNavigationInteractiveTransition *navT;

@end

@implementation WMNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIGestureRecognizer *gesture = self.interactivePopGestureRecognizer;
    gesture.enabled = NO;
    UIView *gestureView = gesture.view;

    self.navigationBarHidden = YES;

    UIPanGestureRecognizer *popRecognizer = [[UIPanGestureRecognizer alloc] init];
    popRecognizer.delegate = self;
    popRecognizer.maximumNumberOfTouches = 1;
    [gestureView addGestureRecognizer:popRecognizer];

    _navT = [[WMNavigationInteractiveTransition alloc] initWithViewController:self];
    [popRecognizer addTarget:_navT action:@selector(handleControllerPop:)];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    /**
     *  这里有两个条件不允许手势执行,1、当前控制器为根控制器;2、如果这个push、pop动画正在执行(私有属性)
     */
    return self.viewControllers.count != 1 && ![[self valueForKey:@"_isTransitioning"] boolValue];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
 //   NSLog(@"%@", NSStringFromClass([touch.view class]));

    // 若为UITableViewCellContentView(即点击了tableViewCell),则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]||[NSStringFromClass([touch.view class]) isEqualToString:@"UITableView"]||[NSStringFromClass([touch.view class]) isEqualToString:@"UIScrollView"]) {

   //     NSLog(@"return no");
        return NO;
    }
  //  NSLog(@"return YES");
    return  YES;
}

- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer
{
  //   NSLog(@"++%@", NSStringFromClass([otherGestureRecognizer.view class]));
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
  //   NSLog(@"--%@", NSStringFromClass([otherGestureRecognizer.view class]));
    if ([otherGestureRecognizer.view isKindOfClass:[UITableViewCell class]]
        ) {
         NSLog(@"return Yes");
        return YES;
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end


text:
package org.wso2.developerstudio.eclipse.ds.impl;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;

import org.wso2.developerstudio.eclipse.ds.DsPackage;
import org.wso2.developerstudio.eclipse.ds.QueryProperty;

/**
 *
 * An implementation of the model object 'Query Property'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.wso2.developerstudio.eclipse.ds.impl.QueryPropertyImpl#getValue Value}

 *
{@link org.wso2.developerstudio.eclipse.ds.impl.QueryPropertyImpl#getName Name}

 *

 *

 *
 * @generated
 */
public class QueryPropertyImpl extends EObjectImpl implements QueryProperty {
	/**
	 * The default value of the '{@link #getValue() Value}' attribute.
	 *
	 *
	 * @see #getValue()
	 * @generated
	 * @ordered
	 */
	protected static final String VALUE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getValue() Value}' attribute.
	 *
	 *
	 * @see #getValue()
	 * @generated
	 * @ordered
	 */
	protected String value = VALUE_EDEFAULT;

	/**
	 * The default value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	protected static final String NAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	protected String name = NAME_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected QueryPropertyImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	protected EClass eStaticClass() {
		return DsPackage.Literals.QUERY_PROPERTY;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getValue() {
		return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setValue(String newValue) {
		String oldValue = value;
		value = newValue;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DsPackage.QUERY_PROPERTY__VALUE, oldValue, value));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
		return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setName(String newName) {
		String oldName = name;
		name = newName;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DsPackage.QUERY_PROPERTY__NAME, oldName, name));
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case DsPackage.QUERY_PROPERTY__VALUE:
				return getValue();
			case DsPackage.QUERY_PROPERTY__NAME:
				return getName();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case DsPackage.QUERY_PROPERTY__VALUE:
				setValue((String)newValue);
				return;
			case DsPackage.QUERY_PROPERTY__NAME:
				setName((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case DsPackage.QUERY_PROPERTY__VALUE:
				setValue(VALUE_EDEFAULT);
				return;
			case DsPackage.QUERY_PROPERTY__NAME:
				setName(NAME_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case DsPackage.QUERY_PROPERTY__VALUE:
				return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value);
			case DsPackage.QUERY_PROPERTY__NAME:
				return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (value: ");
		result.append(value);
		result.append(", name: ");
		result.append(name);
		result.append(')');
		return result.toString();
	}

} // QueryPropertyImpl


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

using System.Net.Http;
using System.Threading;
using Newtonsoft.Json;

namespace Consul
{
    /// <summary>
    /// KVPair is used to represent a single K/V entry
    /// </summary>
    public class KVPair
    {
        public string Key { get; set; }

        [JsonProperty]
        public ulong CreateIndex { get; private set; }

        [JsonProperty]
        public ulong ModifyIndex { get; set; }

        [JsonProperty]
        public ulong LockIndex { get; private set; }

        public ulong Flags { get; set; }
        public byte[] Value { get; set; }
        public string Session { get; set; }

        public KVPair(string key)
        {
            Key = key;
        }
    }

    /// <summary>
    /// KV is used to manipulate the K/V API
    /// </summary>
    public class KV
    {
        private readonly Client _client;

        public KV(Client c)
        {
            _client = c;
        }

        /// <summary>
        /// Get is used to lookup a single key
        /// </summary>
        /// <param name="key">The key name</param>
        /// <returns>A query result containing the requested key/value pair, or a query result with a null response if the key does not exist</returns>
        public QueryResult<KVPair> Get(string key)
        {
            return Get(key, QueryOptions.Empty);
        }

        /// <summary>
        /// Get is used to lookup a single key
        /// </summary>
        /// <param name="key">The key name</param>
        /// <param name="q">Customized query options</param>
        /// <returns>A query result containing the requested key/value pair, or a query result with a null response if the key does not exist</returns>
        public QueryResult<KVPair> Get(string key, QueryOptions q)
        {
            var req = _client.CreateQueryRequest<KVPair[]>(string.Format("/v1/kv/{0}", key), q);
            var res = req.Execute();
            var ret = new QueryResult<KVPair>()
            {
                KnownLeader = res.KnownLeader,
                LastContact = res.LastContact,
                LastIndex = res.LastIndex,
                RequestTime = res.RequestTime
            };
            if (res.Response != null && res.Response.Length > 0)
            {
                ret.Response = res.Response[0];
            }
            return ret;
        }

        /// <summary>
        /// List is used to lookup all keys under a prefix
        /// </summary>
        /// <param name="prefix">The prefix to search under. Does not have to be a full path - e.g. a prefix of "ab" will find keys "abcd" and "ab11" but not "acdc"</param>
        /// <param name="q">Customized query options</param>
        /// <returns>A query result containing the keys matching the prefix</returns>
        public QueryResult<KVPair[]> List(string prefix)
        {
            return List(prefix, QueryOptions.Empty);
        }

        /// <summary>
        /// List is used to lookup all keys under a prefix
        /// </summary>
        /// <param name="prefix">The prefix to search under. Does not have to be a full path - e.g. a prefix of "ab" will find keys "abcd" and "ab11" but not "acdc"</param>
        /// <param name="q">Customized query options</param>
        /// <returns>A query result containing the keys matching the prefix</returns>
        public QueryResult<KVPair[]> List(string prefix, QueryOptions q)
        {
            return List(prefix, q, CancellationToken.None);
        }

        /// <summary>
        /// <see cref="List(string,QueryOptions)"/>
        /// </summary>
        /// <param name="prefix"><see cref="List(string,QueryOptions)"/></param>
        /// <param name="q"><see cref="List(string,QueryOptions)"/></param>
        /// <param name="cancel">Cancellation token for long poll request. If set, OperationCanceledException will
        /// be thrown</param>
        /// <returns></returns>
        public QueryResult<KVPair[]> List(string prefix, QueryOptions q, CancellationToken cancel)
        {
            var req = _client.CreateQueryRequest<KVPair[]>(string.Format("/v1/kv/{0}", prefix), q);
            req.Params["recurse"] = string.Empty;
            return req.Execute(cancel);
        }

        /// <summary>
        /// Keys is used to list all the keys under a prefix.
        /// </summary>
        /// <param name="prefix">The key prefix to filter on</param>
        /// <returns>A query result containing a list of key names</returns>
        public QueryResult<string[]> Keys(string prefix)
        {
            return Keys(prefix, string.Empty, QueryOptions.Empty);
        }

        /// <summary>
        /// Keys is used to list all the keys under a prefix. Optionally, a separator can be used to limit the responses.
        /// </summary>
        /// <param name="prefix">The key prefix to filter on</param>
        /// <param name="separator">The terminating suffix of the filter - e.g. a separator of "/" and a prefix of "/web/" will match "/web/foo" and "/web/foo/" but not "/web/foo/baz"</param>
        /// <returns>A query result containing a list of key names</returns>
        public QueryResult<string[]> Keys(string prefix, string separator)
        {
            return Keys(prefix, separator, QueryOptions.Empty);
        }

        /// <summary>
        /// Keys is used to list all the keys under a prefix. Optionally, a separator can be used to limit the responses.
        /// </summary>
        /// <param name="prefix">The key prefix to filter on</param>
        /// <param name="separator">The terminating suffix of the filter - e.g. a separator of "/" and a prefix of "/web/" will match "/web/foo" and "/web/foo/" but not "/web/foo/baz"</param>
        /// <param name="q">Customized query options</param>
        /// <returns>A query result containing a list of key names</returns>
        public QueryResult<string[]> Keys(string prefix, string separator, QueryOptions q)
        {
            var req = _client.CreateQueryRequest<string[]>(string.Format("/v1/kv/{0}", prefix), q);
            req.Params["keys"] = string.Empty;
            if (!string.IsNullOrEmpty(separator))
            {
                req.Params["separator"] = separator;
            }
            return req.Execute();
        }

        /// <summary>
        /// Put is used to write a new value. Only the Key, Flags and Value properties are respected.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <returns>A write result indicating if the write attempt succeeded</returns>
        public WriteResult<bool> Put(KVPair p)
        {
            return Put(p, WriteOptions.Empty);
        }

        /// <summary>
        /// Put is used to write a new value. Only the Key, Flags and Value is respected.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <param name="q">Customized write options</param>
        /// <returns>A write result indicating if the write attempt succeeded</returns>
        public WriteResult<bool> Put(KVPair p, WriteOptions q)
        {
            var req = _client.CreateWriteRequest<byte[], bool>(string.Format("/v1/kv/{0}", p.Key), p.Value, q);
            if (p.Flags > 0)
            {
                req.Params["flags"] = p.Flags.ToString();
            }
            return req.Execute();
        }

        /// <summary>
        /// CAS is used for a Check-And-Set operation. The Key, ModifyIndex, Flags and Value are respected. Returns true on success or false on failures.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <returns>A write result indicating if the write attempt succeeded</returns>
        public WriteResult<bool> CAS(KVPair p)
        {
            return CAS(p, WriteOptions.Empty);
        }

        /// <summary>
        /// CAS is used for a Check-And-Set operation. The Key, ModifyIndex, Flags and Value are respected. Returns true on success or false on failures.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <param name="q">Customized write options</param>
        /// <returns>A write result indicating if the write attempt succeeded</returns>
        public WriteResult<bool> CAS(KVPair p, WriteOptions q)
        {
            var req = _client.CreateWriteRequest<byte[], bool>(string.Format("/v1/kv/{0}", p.Key), p.Value, q);
            if (p.Flags > 0)
            {
                req.Params["flags"] = p.Flags.ToString();
            }
            req.Params["cas"] = p.ModifyIndex.ToString();
            return req.Execute();
        }

        /// <summary>
        /// Acquire is used for a lock acquisiiton operation. The Key, Flags, Value and Session are respected.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <returns>A write result indicating if the acquisition attempt succeeded</returns>
        public WriteResult<bool> Acquire(KVPair p)
        {
            return Acquire(p, WriteOptions.Empty);
        }

        /// <summary>
        /// Acquire is used for a lock acquisiiton operation. The Key, Flags, Value and Session are respected.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <param name="q">Customized write options</param>
        /// <returns>A write result indicating if the acquisition attempt succeeded</returns>
        public WriteResult<bool> Acquire(KVPair p, WriteOptions q)
        {
            var req = _client.CreateWriteRequest<object, bool>(string.Format("/v1/kv/{0}", p.Key), q);
            if (p.Flags > 0)
            {
                req.Params["flags"] = p.Flags.ToString();
            }
            req.Params["acquire"] = p.Session;
            return req.Execute();
        }

        /// <summary>
        /// Release is used for a lock release operation. The Key, Flags, Value and Session are respected.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <returns>A write result indicating if the release attempt succeeded</returns>
        public WriteResult<bool> Release(KVPair p)
        {
            return Release(p, WriteOptions.Empty);
        }

        /// <summary>
        /// Release is used for a lock release operation. The Key, Flags, Value and Session are respected.
        /// </summary>
        /// <param name="p">The key/value pair to store in Consul</param>
        /// <param name="q">Customized write options</param>
        /// <returns>A write result indicating if the release attempt succeeded</returns>
        public WriteResult<bool> Release(KVPair p, WriteOptions q)
        {
            var req = _client.CreateWriteRequest<object, bool>(string.Format("/v1/kv/{0}", p.Key), q);
            if (p.Flags > 0)
            {
                req.Params["flags"] = p.Flags.ToString();
            }
            req.Params["release"] = p.Session;
            return req.Execute();
        }

        /// <summary>
        /// Delete is used to delete a single key.
        /// </summary>
        /// <param name="key">The key name to delete</param>
        /// <returns>A write result indicating if the delete attempt succeeded</returns>
        public WriteResult<bool> Delete(string key)
        {
            return Delete(key, WriteOptions.Empty);
        }

        /// <summary>
        /// Delete is used to delete a single key.
        /// </summary>
        /// <param name="key">The key name to delete</param>
        /// <param name="q">Customized write options</param>
        /// <returns>A write result indicating if the delete attempt succeeded</returns>
        public WriteResult<bool> Delete(string key, WriteOptions q)
        {
            return _client.CreateWriteRequest<object, bool>(HttpMethod.Delete, string.Format("/v1/kv/{0}", key), q)
                        .Execute();
        }

        /// <summary>
        /// DeleteCAS is used for a Delete Check-And-Set operation. The Key and ModifyIndex are respected. Returns true on success or false on failures.
        /// </summary>
        /// <param name="p">The key/value pair to delete</param>
        /// <returns>A write result indicating if the delete attempt succeeded</returns>
        public WriteResult<bool> DeleteCAS(KVPair p)
        {
            return DeleteCAS(p, WriteOptions.Empty);
        }

        /// <summary>
        /// DeleteCAS is used for a Delete Check-And-Set operation. The Key and ModifyIndex are respected. Returns true on success or false on failures.
        /// </summary>
        /// <param name="p">The key/value pair to delete</param>
        /// <param name="q">Customized write options</param>
        /// <returns>A write result indicating if the delete attempt succeeded</returns>
        public WriteResult<bool> DeleteCAS(KVPair p, WriteOptions q)
        {
            var req = _client.CreateWriteRequest<object, bool>(HttpMethod.Delete, string.Format("/v1/kv/{0}", p.Key), q);
            req.Params.Add("cas", p.ModifyIndex.ToString());
            return req.Execute();
        }

        /// <summary>
        /// DeleteTree is used to delete all keys under a prefix
        /// </summary>
        /// <param name="prefix">The key prefix to delete from</param>
        /// <returns>A write result indicating if the recursive delete attempt succeeded</returns>
        public WriteResult<bool> DeleteTree(string prefix)
        {
            return DeleteTree(prefix, WriteOptions.Empty);
        }

        /// <summary>
        /// DeleteTree is used to delete all keys under a prefix
        /// </summary>
        /// <param name="prefix">The key prefix to delete from</param>
        /// <param name="q">Customized write options</param>
        /// <returns>A write result indicating if the recursiv edelete attempt succeeded</returns>
        public WriteResult<bool> DeleteTree(string prefix, WriteOptions q)
        {
            var req = _client.CreateWriteRequest<object, bool>(HttpMethod.Delete, string.Format("/v1/kv/{0}", prefix), q);
            req.Params.Add("recurse", string.Empty);
            return req.Execute();
        }
    }

    /// <summary>
    /// KV is used to return a handle to the K/V apis
    /// </summary>
    public partial class Client
    {
        private KV _kv;

        public KV KV
        {
            get
            {
                if (_kv == null)
                {
                    lock (_lock)
                    {
                        if (_kv == null)
                        {
                            _kv = new KV(this);
                        }
                    }
                }
                return _kv;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: QSignalMapper Class Reference</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

QSignalMapper Class Reference
[QtCore module]

The QSignalMapper class bundles signals from identifiable senders. More...

 #include <QSignalMapper>

Inherits QObject.

List of all members, including inherited members

Qt 3 support members

Public Functions

QSignalMapper ( QObject * parent = 0 )

~QSignalMapper ()

QObject * mapping ( int id ) const

QObject * mapping ( const QString & id ) const

QObject * mapping ( QWidget * widget ) const

QObject * mapping ( QObject * object ) const

void removeMappings ( QObject * sender )

void setMapping ( QObject * sender, int id )

void setMapping ( QObject * sender, const QString & text )

void setMapping ( QObject * sender, QWidget * widget )

void setMapping ( QObject * sender, QObject * object )

29 public functions inherited from QObject

Public Slots

void map ()

void map ( QObject * sender )

1 public slot inherited from QObject

Signals

void mapped ( int i )

void mapped ( const QString & text )

void mapped ( QWidget * widget )

void mapped ( QObject * object )

1 signal inherited from QObject

Additional Inherited Members

1 property inherited from QObject

5 static public members inherited from QObject

7 protected functions inherited from QObject

Detailed Description

The QSignalMapper class bundles signals from identifiable senders.

This class collects a set of parameterless signals, and re-emits them with integer, string or widget parameters corresponding to the object that sent the signal.

The class supports the mapping of particular strings or integers with particular objects using setMapping(). The objects' signals can then be connected to the map() slot which will emit the mapped() signal with the string or integer associated with the original signalling object. Mappings can be removed later using removeMappings().

Example: Suppose we want to create a custom widget that contains a group of buttons (like a tool palette). One approach is to connect each button's <tt>clicked()</tt> signal to its own custom slot; but in this example we want to connect all the buttons to a single slot and parameterize the slot by the button that was clicked.

Here's the definition of a simple custom widget that has a single signal, <tt>clicked()</tt>, which is emitted with the text of the button that was clicked:

 class ButtonWidget : public QWidget
 {
     Q_OBJECT

 public:
     ButtonWidget(QStringList texts, QWidget *parent = 0);

 signals:
     void clicked(const QString &text);

 private:
     QSignalMapper *signalMapper;
 };

The only function that we need to implement is the constructor:

 ButtonWidget::ButtonWidget(QStringList texts, QWidget *parent)
     : QWidget(parent)
 {
     signalMapper = new QSignalMapper(this);

     QGridLayout *gridLayout = new QGridLayout;
     for (int i = 0; i < texts.size(); ++i) {
         QPushButton *button = new QPushButton(texts[i]);
         connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
         signalMapper->setMapping(button, texts[i]);
         gridLayout->addWidget(button, i / 3, i % 3);
     }

     connect(signalMapper, SIGNAL(mapped(const QString &)),
             this, SIGNAL(clicked(const QString &)));

     setLayout(gridLayout);
 }

A list of texts is passed to the constructor. A signal mapper is constructed and for each text in the list a QPushButton is created. We connect each button's <tt>clicked()</tt> signal to the signal mapper's map() slot, and create a mapping in the signal mapper from each button to the button's text. Finally we connect the signal mapper's mapped() signal to the custom widget's <tt>clicked()</tt> signal. When the user clicks a button, the custom widget will emit a single <tt>clicked()</tt> signal whose argument is the text of the button the user clicked.

See also QObject, QButtonGroup, and QActionGroup.

Member Function Documentation

QSignalMapper::QSignalMapper ( QObject * parent = 0 )

Constructs a QSignalMapper with parent parent.

QSignalMapper::~QSignalMapper ()

Destroys the QSignalMapper.

void QSignalMapper::map ()  <tt> [slot]</tt>

This slot emits signals based on which object sends signals to it.

void QSignalMapper::map ( QObject * sender )  <tt> [slot]</tt>

This is an overloaded member function, provided for convenience.

This slot emits signals based on the sender object.

void QSignalMapper::mapped ( int i )  <tt> [signal]</tt>

This signal is emitted when map() is signalled from an object that has an integer mapping set. The object's mapped integer is passed in i.

See also setMapping().

void QSignalMapper::mapped ( const QString & text )  <tt> [signal]</tt>

This is an overloaded member function, provided for convenience.

This signal is emitted when map() is signalled from an object that has a string mapping set. The object's mapped string is passed in text.

See also setMapping().

void QSignalMapper::mapped ( QWidget * widget )  <tt> [signal]</tt>

This is an overloaded member function, provided for convenience.

This signal is emitted when map() is signalled from an object that has a widget mapping set. The object's mapped widget is passed in widget.

See also setMapping().

void QSignalMapper::mapped ( QObject * object )  <tt> [signal]</tt>

This is an overloaded member function, provided for convenience.

This signal is emitted when map() is signalled from an object that has an object mapping set. The object provided by the map is passed in object.

See also setMapping().

QObject * QSignalMapper::mapping ( int id ) const

Returns the sender QObject that is associated with the given id.

See also setMapping().

QObject * QSignalMapper::mapping ( const QString & id ) const

This is an overloaded member function, provided for convenience.

QObject * QSignalMapper::mapping ( QWidget * widget ) const

This is an overloaded member function, provided for convenience.

Returns the sender QObject that is associated with the given widget.

QObject * QSignalMapper::mapping ( QObject * object ) const

This is an overloaded member function, provided for convenience.

Returns the sender QObject that is associated with the given object.

void QSignalMapper::removeMappings ( QObject * sender )

Removes all mappings for sender.

This is done automatically when mapped objects are destroyed.

void QSignalMapper::setMapping ( QObject * sender, int id )

Adds a mapping so that when map() is signalled from the given sender, the signal mapped(id) is emitted.

There may be at most one integer ID for each sender.

See also mapping().

void QSignalMapper::setMapping ( QObject * sender, const QString & text )

This is an overloaded member function, provided for convenience.

Adds a mapping so that when map() is signalled from the given sender, the signal mapped(text ) is emitted.

There may be at most one text for each sender.

void QSignalMapper::setMapping ( QObject * sender, QWidget * widget )

This is an overloaded member function, provided for convenience.

Adds a mapping so that when map() is signalled from the given sender, the signal mapped(widget ) is emitted.

There may be at most one widget for each sender.

void QSignalMapper::setMapping ( QObject * sender, QObject * object )

This is an overloaded member function, provided for convenience.

Adds a mapping so that when map() is signalled from the given sender, the signal mapped(object ) is emitted.

There may be at most one object for each sender.

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
namespace pc{

template<class T, class M>
class MMU : public BusWritter
{
  public:
	MMU(long manageSize, TranslationStrategy<T, M>* strategy, BUS* bus) : BusWritter(bus){
	  memSize = manageSize;
	  transStrategy = strategy;
	  this->bus = bus;
	}
    ~MMU(){
    	delete transStrategy;
    }
    T getAddress(long virtualAddress){
	  T physicalAddress = NULL;
	  try{
		physicalAddress = transStrategy->translateDirection(NULL, virtualAddress);
		if(physicalAddress->getDecimalDir(transStrategy->getDescriptor()) > memSize){
			throw new InvalidAddressException(virtualAddress);
		}
	  }catch(InvalidAddressException& e){
		bus->transportSignal(SEGMENTATION_FAULT);
	  }
	  return physicalAddress;
    }
  private:
    unsigned long long memSize;
    TLB<T>* tlb;
    TranslationStrategy<T, M>* transStrategy;
    BUS* bus;
};

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SubscribeAtBoot</string>
</resources>


text:
package ec2_test

var ErrorDump = `
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error>UnsupportedOperation
<Message>AMIs with an instance-store root device are not supported for the instance type 't1.micro'.</Message>
</Error></Errors><RequestID>0503f4e9-bbd6-483c-b54f-c4ae9f3b30f4</RequestID></Response>
`

// http://goo.gl/Mcm3b
var RunInstancesExample = `
<RunInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <reservationId>r-47a5402e</reservationId>
  <ownerId>999988887777</ownerId>
  <groupSet>
      <item>
          <groupId>sg-67ad940e</groupId>
          <groupName>default</groupName>
      </item>
  </groupSet>
  <instancesSet>
    <item>
      <instanceId>i-2ba64342</instanceId>
      <imageId>ami-60a54009</imageId>
      <instanceState>
        0
        <name>pending</name>
      </instanceState>
      <privateDnsName></privateDnsName>
      <dnsName></dnsName>
      <keyName>example-key-name</keyName>
      <amiLaunchIndex>0</amiLaunchIndex>
      <instanceType>m1.small</instanceType>
      <launchTime>2007-08-07T11:51:50.000Z</launchTime>
      <placement>
        <availabilityZone>us-east-1b</availabilityZone>
      </placement>
      <monitoring>
        <state>enabled</state>
      </monitoring>
      <virtualizationType>paravirtual</virtualizationType>
      <clientToken/>
      <tagSet/>
      <hypervisor>xen</hypervisor>
    </item>
    <item>
      <instanceId>i-2bc64242</instanceId>
      <imageId>ami-60a54009</imageId>
      <instanceState>
        0
        <name>pending</name>
      </instanceState>
      <privateDnsName></privateDnsName>
      <dnsName></dnsName>
      <keyName>example-key-name</keyName>
      <amiLaunchIndex>1</amiLaunchIndex>
      <instanceType>m1.small</instanceType>
      <launchTime>2007-08-07T11:51:50.000Z</launchTime>
      <placement>
         <availabilityZone>us-east-1b</availabilityZone>
      </placement>
      <monitoring>
        <state>enabled</state>
      </monitoring>
      <virtualizationType>paravirtual</virtualizationType>
      <clientToken/>
      <tagSet/>
      <hypervisor>xen</hypervisor>
    </item>
    <item>
      <instanceId>i-2be64332</instanceId>
      <imageId>ami-60a54009</imageId>
      <instanceState>
        0
        <name>pending</name>
      </instanceState>
      <privateDnsName></privateDnsName>
      <dnsName></dnsName>
      <keyName>example-key-name</keyName>
      <amiLaunchIndex>2</amiLaunchIndex>
      <instanceType>m1.small</instanceType>
      <launchTime>2007-08-07T11:51:50.000Z</launchTime>
      <placement>
         <availabilityZone>us-east-1b</availabilityZone>
      </placement>
      <monitoring>
        <state>enabled</state>
      </monitoring>
      <virtualizationType>paravirtual</virtualizationType>
      <clientToken/>
      <tagSet/>
      <hypervisor>xen</hypervisor>
    </item>
  </instancesSet>
</RunInstancesResponse>
`

// http://goo.gl/3BKHj
var TerminateInstancesExample = `
<TerminateInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <instancesSet>
    <item>
      <instanceId>i-3ea74257</instanceId>
      <currentState>
        32
        <name>shutting-down</name>
      </currentState>
      <previousState>
        16
        <name>running</name>
      </previousState>
    </item>
  </instancesSet>
</TerminateInstancesResponse>
`

// http://goo.gl/mLbmw
var DescribeInstancesExample1 = `
<DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>98e3c9a4-848c-4d6d-8e8a-b1bdEXAMPLE</requestId>
  <reservationSet>
    <item>
      <reservationId>r-b27e30d9</reservationId>
      <ownerId>999988887777</ownerId>
      <groupSet>
        <item>
          <groupId>sg-67ad940e</groupId>
          <groupName>default</groupName>
        </item>
      </groupSet>
      <instancesSet>
        <item>
          <instanceId>i-c5cd56af</instanceId>
          <imageId>ami-1a2b3c4d</imageId>
          <instanceState>
            16
            <name>running</name>
          </instanceState>
          <privateDnsName>domU-12-31-39-10-56-34.compute-1.internal</privateDnsName>
          <dnsName>ec2-174-129-165-232.compute-1.amazonaws.com</dnsName>
          <reason/>
          <keyName>GSG_Keypair</keyName>
          <amiLaunchIndex>0</amiLaunchIndex>
          <productCodes/>
          <instanceType>m1.small</instanceType>
          <launchTime>2010-08-17T01:15:18.000Z</launchTime>
          <placement>
            <availabilityZone>us-east-1b</availabilityZone>
            <groupName/>
          </placement>
          <kernelId>aki-94c527fd</kernelId>
          <ramdiskId>ari-96c527ff</ramdiskId>
          <monitoring>
            <state>disabled</state>
          </monitoring>
          <privateIpAddress>10.198.85.190</privateIpAddress>
          <ipAddress>174.129.165.232</ipAddress>
          <architecture>i386</architecture>
          <rootDeviceType>ebs</rootDeviceType>
          <rootDeviceName>/dev/sda1</rootDeviceName>
          <blockDeviceMapping>
            <item>
              <deviceName>/dev/sda1</deviceName>
              <ebs>
                <volumeId>vol-a082c1c9</volumeId>
                <status>attached</status>
                <attachTime>2010-08-17T01:15:21.000Z</attachTime>
                <deleteOnTermination>false</deleteOnTermination>
              </ebs>
            </item>
          </blockDeviceMapping>
          <instanceLifecycle>spot</instanceLifecycle>
          <spotInstanceRequestId>sir-7a688402</spotInstanceRequestId>
          <virtualizationType>paravirtual</virtualizationType>
          <clientToken/>
          <tagSet/>
          <hypervisor>xen</hypervisor>
          <groupSet>
            <item>
              <groupId>sg-67ad940e</groupId>
              <groupName>default</groupName>
            </item>
          </groupSet>
       </item>
      </instancesSet>
      <requesterId>854251627541</requesterId>
    </item>
    <item>
      <reservationId>r-b67e30dd</reservationId>
      <ownerId>999988887777</ownerId>
      <groupSet>
        <item>
          <groupId>sg-67ad940e</groupId>
          <groupName>default</groupName>
        </item>
      </groupSet>
      <instancesSet>
        <item>
          <instanceId>i-d9cd56b3</instanceId>
          <imageId>ami-1a2b3c4d</imageId>
          <instanceState>
            16
            <name>running</name>
          </instanceState>
          <privateDnsName>domU-12-31-39-10-54-E5.compute-1.internal</privateDnsName>
          <dnsName>ec2-184-73-58-78.compute-1.amazonaws.com</dnsName>
          <reason/>
          <keyName>GSG_Keypair</keyName>
          <amiLaunchIndex>0</amiLaunchIndex>
          <productCodes/>
          <instanceType>m1.large</instanceType>
          <launchTime>2010-08-17T01:15:19.000Z</launchTime>
          <placement>
            <availabilityZone>us-east-1b</availabilityZone>
            <groupName/>
          </placement>
          <kernelId>aki-94c527fd</kernelId>
          <ramdiskId>ari-96c527ff</ramdiskId>
          <monitoring>
            <state>disabled</state>
          </monitoring>
          <privateIpAddress>10.198.87.19</privateIpAddress>
          <ipAddress>184.73.58.78</ipAddress>
          <architecture>i386</architecture>
          <rootDeviceType>ebs</rootDeviceType>
          <rootDeviceName>/dev/sda1</rootDeviceName>
          <blockDeviceMapping>
            <item>
              <deviceName>/dev/sda1</deviceName>
              <ebs>
                <volumeId>vol-a282c1cb</volumeId>
                <status>attached</status>
                <attachTime>2010-08-17T01:15:23.000Z</attachTime>
                <deleteOnTermination>false</deleteOnTermination>
              </ebs>
            </item>
          </blockDeviceMapping>
          <instanceLifecycle>spot</instanceLifecycle>
          <spotInstanceRequestId>sir-55a3aa02</spotInstanceRequestId>
          <virtualizationType>paravirtual</virtualizationType>
          <clientToken/>
          <tagSet/>
          <hypervisor>xen</hypervisor>
       </item>
      </instancesSet>
      <requesterId>854251627541</requesterId>
    </item>
  </reservationSet>
</DescribeInstancesResponse>
`

// http://goo.gl/mLbmw
var DescribeInstancesExample2 = `
<DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <reservationSet>
    <item>
      <reservationId>r-bc7e30d7</reservationId>
      <ownerId>999988887777</ownerId>
      <groupSet>
        <item>
          <groupId>sg-67ad940e</groupId>
          <groupName>default</groupName>
        </item>
      </groupSet>
      <instancesSet>
        <item>
          <instanceId>i-c7cd56ad</instanceId>
          <imageId>ami-b232d0db</imageId>
          <instanceState>
            16
            <name>running</name>
          </instanceState>
          <privateDnsName>domU-12-31-39-01-76-06.compute-1.internal</privateDnsName>
          <dnsName>ec2-72-44-52-124.compute-1.amazonaws.com</dnsName>
          <keyName>GSG_Keypair</keyName>
          <amiLaunchIndex>0</amiLaunchIndex>
          <productCodes/>
          <instanceType>m1.small</instanceType>
          <launchTime>2010-08-17T01:15:16.000Z</launchTime>
          <placement>
              <availabilityZone>us-east-1b</availabilityZone>
          </placement>
          <kernelId>aki-94c527fd</kernelId>
          <ramdiskId>ari-96c527ff</ramdiskId>
          <monitoring>
              <state>disabled</state>
          </monitoring>
          <privateIpAddress>10.255.121.240</privateIpAddress>
          <ipAddress>72.44.52.124</ipAddress>
          <architecture>i386</architecture>
          <rootDeviceType>ebs</rootDeviceType>
          <rootDeviceName>/dev/sda1</rootDeviceName>
          <blockDeviceMapping>
              <item>
                 <deviceName>/dev/sda1</deviceName>
                 <ebs>
                    <volumeId>vol-a482c1cd</volumeId>
                    <status>attached</status>
                    <attachTime>2010-08-17T01:15:26.000Z</attachTime>
                    <deleteOnTermination>true</deleteOnTermination>
                </ebs>
             </item>
          </blockDeviceMapping>
          <virtualizationType>paravirtual</virtualizationType>
          <clientToken/>
          <tagSet>
              <item>
                    <key>webserver</key>
                    <value></value>
             </item>
              <item>
                    <key>stack</key>
                    <value>Production</value>
             </item>
          </tagSet>
          <hypervisor>xen</hypervisor>
        </item>
      </instancesSet>
    </item>
  </reservationSet>
</DescribeInstancesResponse>
`

// http://goo.gl/V0U25
var DescribeImagesExample = `
<DescribeImagesResponse xmlns="http://ec2.amazonaws.com/doc/2012-08-15/">
         <requestId>4a4a27a2-2e7c-475d-b35b-ca822EXAMPLE</requestId>
    <imagesSet>
        <item>
            <imageId>ami-a2469acf</imageId>
            <imageLocation>aws-marketplace/example-marketplace-amzn-ami.1</imageLocation>
            <imageState>available</imageState>
            <imageOwnerId>123456789999</imageOwnerId>
            <isPublic>true</isPublic>
            <productCodes>
                <item>
                    <productCode>a1b2c3d4e5f6g7h8i9j10k11</productCode>
                    <type>marketplace</type>
                </item>
            </productCodes>
            <architecture>i386</architecture>
            <imageType>machine</imageType>
            <kernelId>aki-805ea7e9</kernelId>
            <imageOwnerAlias>aws-marketplace</imageOwnerAlias>
            <name>example-marketplace-amzn-ami.1</name>
            <description>Amazon Linux AMI i386 EBS</description>
            <rootDeviceType>ebs</rootDeviceType>
            <rootDeviceName>/dev/sda1</rootDeviceName>
            <blockDeviceMapping>
                <item>
                    <deviceName>/dev/sda1</deviceName>
                    <ebs>
                        <snapshotId>snap-787e9403</snapshotId>
                        <volumeSize>8</volumeSize>
                        <deleteOnTermination>true</deleteOnTermination>
                    </ebs>
                </item>
            </blockDeviceMapping>
            <virtualizationType>paravirtual</virtualizationType>
            <hypervisor>xen</hypervisor>
        </item>
    </imagesSet>
</DescribeImagesResponse>
`

// http://goo.gl/ttcda
var CreateSnapshotExample = `
<CreateSnapshotResponse xmlns="http://ec2.amazonaws.com/doc/2012-10-01/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <snapshotId>snap-78a54011</snapshotId>
  <volumeId>vol-4d826724</volumeId>
  <status>pending</status>
  <startTime>2008-05-07T12:51:50.000Z</startTime>
  <progress>60%</progress>
  <ownerId>111122223333</ownerId>
  <volumeSize>10</volumeSize>
  <description>Daily Backup</description>
</CreateSnapshotResponse>
`

// http://goo.gl/vwU1y
var DeleteSnapshotExample = `
<DeleteSnapshotResponse xmlns="http://ec2.amazonaws.com/doc/2012-10-01/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <return>true</return>
</DeleteSnapshotResponse>
`

// http://goo.gl/nkovs
var DescribeSnapshotsExample = `
<DescribeSnapshotsResponse xmlns="http://ec2.amazonaws.com/doc/2012-10-01/">
   <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
   <snapshotSet>
      <item>
         <snapshotId>snap-1a2b3c4d</snapshotId>
         <volumeId>vol-8875daef</volumeId>
         <status>pending</status>
         <startTime>2010-07-29T04:12:01.000Z</startTime>
         <progress>30%</progress>
         <ownerId>111122223333</ownerId>
         <volumeSize>15</volumeSize>
         <description>Daily Backup</description>
         <tagSet>
            <item>
               <key>Purpose</key>
               <value>demo_db_14_backup</value>
            </item>
         </tagSet>
      </item>
   </snapshotSet>
</DescribeSnapshotsResponse>
`

// http://goo.gl/Eo7Yl
var CreateSecurityGroupExample = `
<CreateSecurityGroupResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
   <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
   <return>true</return>
   <groupId>sg-67ad940e</groupId>
</CreateSecurityGroupResponse>
`

// http://goo.gl/k12Uy
var DescribeSecurityGroupsExample = `
<DescribeSecurityGroupsResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <securityGroupInfo>
    <item>
      <ownerId>999988887777</ownerId>
      <groupName>WebServers</groupName>
      <groupId>sg-67ad940e</groupId>
      <groupDescription>Web Servers</groupDescription>
      <ipPermissions>
        <item>
           <ipProtocol>tcp</ipProtocol>
           <fromPort>80</fromPort>
           <toPort>80</toPort>
           <groups/>
           <ipRanges>
             <item>
               <cidrIp>0.0.0.0/0</cidrIp>
             </item>
           </ipRanges>
        </item>
      </ipPermissions>
    </item>
    <item>
      <ownerId>999988887777</ownerId>
      <groupName>RangedPortsBySource</groupName>
      <groupId>sg-76abc467</groupId>
      <groupDescription>Group A</groupDescription>
      <ipPermissions>
        <item>
           <ipProtocol>tcp</ipProtocol>
           <fromPort>6000</fromPort>
           <toPort>7000</toPort>
           <groups/>
           <ipRanges/>
        </item>
      </ipPermissions>
    </item>
  </securityGroupInfo>
</DescribeSecurityGroupsResponse>
`

// A dump which includes groups within ip permissions.
var DescribeSecurityGroupsDump = `
<?xml version="1.0" encoding="UTF-8"?>
<DescribeSecurityGroupsResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
    <requestId>87b92b57-cc6e-48b2-943f-f6f0e5c9f46c</requestId>
    <securityGroupInfo>
        <item>
            <ownerId>12345</ownerId>
            <groupName>default</groupName>
            <groupDescription>default group</groupDescription>
            <ipPermissions>
                <item>
                    <ipProtocol>icmp</ipProtocol>
                    <fromPort>-1</fromPort>
                    <toPort>-1</toPort>
                    <groups>
                        <item>
                            <userId>12345</userId>
                            <groupName>default</groupName>
                            <groupId>sg-67ad940e</groupId>
                        </item>
                    </groups>
                    <ipRanges/>
                </item>
                <item>
                    <ipProtocol>tcp</ipProtocol>
                    <fromPort>0</fromPort>
                    <toPort>65535</toPort>
                    <groups>
                        <item>
                            <userId>12345</userId>
                            <groupName>other</groupName>
                            <groupId>sg-76abc467</groupId>
                        </item>
                    </groups>
                    <ipRanges/>
                </item>
            </ipPermissions>
        </item>
    </securityGroupInfo>
</DescribeSecurityGroupsResponse>
`

// http://goo.gl/QJJDO
var DeleteSecurityGroupExample = `
<DeleteSecurityGroupResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
   <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
   <return>true</return>
</DeleteSecurityGroupResponse>
`

// http://goo.gl/u2sDJ
var AuthorizeSecurityGroupIngressExample = `
<AuthorizeSecurityGroupIngressResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <return>true</return>
</AuthorizeSecurityGroupIngressResponse>
`

// http://goo.gl/Mz7xr
var RevokeSecurityGroupIngressExample = `
<RevokeSecurityGroupIngressResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <return>true</return>
</RevokeSecurityGroupIngressResponse>
`

// http://goo.gl/Vmkqc
var CreateTagsExample = `
<CreateTagsResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
   <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
   <return>true</return>
</CreateTagsResponse>
`

// http://goo.gl/awKeF
var StartInstancesExample = `
<StartInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <instancesSet>
    <item>
      <instanceId>i-10a64379</instanceId>
      <currentState>
          0
          <name>pending</name>
      </currentState>
      <previousState>
          80
          <name>stopped</name>
      </previousState>
    </item>
  </instancesSet>
</StartInstancesResponse>
`

// http://goo.gl/436dJ
var StopInstancesExample = `
<StopInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <instancesSet>
    <item>
      <instanceId>i-10a64379</instanceId>
      <currentState>
          64
          <name>stopping</name>
      </currentState>
      <previousState>
          16
          <name>running</name>
      </previousState>
    </item>
  </instancesSet>
</StopInstancesResponse>
`

// http://goo.gl/baoUf
var RebootInstancesExample = `
<RebootInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2011-12-15/">
  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>
  <return>true</return>
</RebootInstancesResponse>
`


text:
package catalogue.contentful;

public class Intents {
  private Intents() {
    throw new AssertionError();
  }

  private static final String PACKAGE_NAME = App.get().getPackageName();

  public static final String ACTION_CHANGE_SPACE = PACKAGE_NAME + ".ACTION_CHANGE_SPACE";

  public static final String EXTRA_CATEGORY = "EXTRA_CATEGORY";

  public static final String EXTRA_PRODUCT = "EXTRA_PRODUCT";
}


text:
Ext.require( [ 'Ext.layout.container.*', 'ASPIREdb.view.filter.AndFilterContainer',
              'ASPIREdb.view.filter.OrFilterContainer', 'ASPIREdb.view.filter.FilterPanel' ] );

/**
 * Filtering subjects
 */
Ext.define( 'ASPIREdb.view.filter.SubjectFilterPanel', {
   extend : 'ASPIREdb.view.filter.FilterPanel',
   alias : 'widget.filter_subject',
   title : 'Subject Filter',
   bodyStyle : 'background: #FFDAA3;',
   items : [ {
      xtype : 'filter_and',
      itemId : 'subjectFilterContainer',
      filterItemType : 'ASPIREdb.view.filter.PropertyFilter',
      suggestValuesRemoteFunction : SubjectService.suggestValues,
      propertyStore : {
         autoLoad : false,
         proxy : {
            type : 'dwr',
            dwrFunction : SubjectService.suggestProperties,
            model : 'ASPIREdb.model.Property',
            reader : {
               type : 'json',
               root : 'data',
               totalProperty : 'count'
            }
         }
      }
   } ],

   getFilterConfig : function() {
      var config = new SubjectFilterConfig();
      var subjectFilterContainer = this.getComponent( 'subjectFilterContainer' );
      config.restriction = subjectFilterContainer.getRestrictionExpression();
      return config;
   },

   setFilterConfig : function(config) {

      var subjectFilterContainer = this.down( '#subjectFilterContainer' );
      subjectFilterContainer.setRestrictionExpression( config.restriction );

   },

   handleCloseImageClick : function() {
      this.close();
   },

   initComponent : function() {
      this.callParent();

   }
} );


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vortex.clustergraph;

/**
 *
 * @author Nikolay
 */
public class LinearDensityEstimator {
}


text:
function engine = belprop_fg_inf_engine(fg, varargin)
% BELPROP_FG_INF_ENGINE Make a belief propagation inference engine for factor graphs
% engine = belprop_fg_inf_engine(factor_graph, ...)
%
% The following optional arguments can be specified in the form of name/value pairs:
% [default in brackets]
% e.g., engine = belprop_inf_engine(fg, 'tol', 1e-2, 'max_iter', 10)
%
% max_iter - max. num. iterations [ 2*num_nodes ]
% momentum - weight assigned to old message in convex combination (useful for damping oscillations) [0]
% tol - tolerance used to assess convergence [1e-3]
% maximize - 1 means use max-product, 0 means use sum-product [0]
%
% This uses potential objects, like belprop_inf_engine, and hence is quite slow.

engine = init_fields;
engine = class(engine, 'belprop_fg_inf_engine');

% set params to default values
N = length(fg.G);
engine.max_iter = 2*N;
engine.momentum = 0;
engine.tol = 1e-3;
engine.maximize = 0;

% parse optional arguments
engine = set_params(engine, varargin);

engine.fgraph = fg;

% store results computed by enter_evidence here
engine.marginal_nodes = cell(1, fg.nvars);
engine.evidence = [];

%%%%%%%%%%%%

function engine = init_fields()

engine.fgraph = [];
engine.max_iter = [];
engine.momentum = [];
engine.tol = [];
engine.maximize = [];
engine.marginal_nodes = [];
engine.evidence = [];
engine.niter = [];


text:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>RLL Overview</TITLE>

Runtime Link Library System

RLL and RLM OVERVIEW

Introduction

The Runtime Link Library (RLL) system is designed to satisfy a number of goals:

To allow a number of programs to share common code at runtime.

    This is a similar concept to the SuperBasic "Toolkit" which adds new
    keywords to the language, but extends the idea to other languages that
    need compiling and linking.

To be independent of the programming language used.

    The RLL system was originally developed for use with programs compiled
    using the C68 compilation system. However, the implementation of most of
    the components has been done in a generic fashion so that there is no
    built in limitation that will stop it being used with other languages as well.

To allow new versions of libraries to easily be introduced.

    New versions of the libraries can be introduced without the need to recompile
    programs that use these libraries.

To be efficient.

    The aim is that there should no (or at least very minimal) additional call time
    overhead for accessing routines or data when sing such dynamically bound
    libraries compared to having inline code.

To make the system easy to use for developers..

    It is possible for the average casual developer who wants to know the
    minimum possible about the mechanics of the system while still being able
    to make use of the key features.

To provide complete control

    Those programmers who want to do more than the standard default should
    have complete control over the RLL process. This allows for situations
    in which the programmers want to control the loading and unloading of
    libraries themselves.

The runtime system should be transparent in operation.

    It should not be necessary for the user of programs that have been built
    using the RLL system to have any knowledge of how it works.

Runtime Link Libraries (RLL(s)) are (potentially at least) shareable between jobs.
This saves memory if several jobs are running using the same RLL.
In addition the program files are typically smaller as they now no longer
need to contain the code for routines that are held in RLL libraries.
This reduction in file size can have the useful side effect of reducing
load time from mass media if large programs are run.

The runtime process of loading and using RLLs is managed by the
Runtime Library Manager (RLM). An executable programme wishing
to use a RLL would call the RLM which would resolve any runtime references
and attempt to load any RLL(s) which are not already in the system.
This process is completely transparent to C68 users as it is handled
automatically in the C68 startup module.

The remainder of this document covers all details of the Runtime Link Library system.
It is structured into several sections, and it is only necessary to read those
that are relevant to the type of use that you wish to make of the RLL system.
The sections are:

The RLM User Guide
    that describes how to manage the RLL system. In particular it covers
    the SuperBasic interface to the
    RLM system which is used to manage the loading and use of RLLs at runtime.
    All users should read this section.

The RLL User Guide
    that describes using the Runtime Link Library system from the perspective
    of the application programmer. All programmers who wish their programs to
    use RLL(s) should read this section.

The RLM Programmers Guide
    that describes the low level programming interface to the Runtime Library
    Manager. The average application programmer need not be aware of the
    details of this interface. This information is therefore only relevant
    to system programmers who need to interface to the RLM capabilities.

The RLL Programmers Guide
    that describes the use of Runtime Link Libraries from the perspective
    of the system programmer writing routines for inclusion into RLLs.

The RLL Technical Reference
    that gives details of the data formats used to store RLL related
    information in programs and libraries.

The runtime library system uses the QJUMP shared memory "THING" system
to implement run time libraries. This provides mechanisms for the automatic
removal of a user job should the library thing be removed thus protecting the
system. The RLM itself is an infinitely shareable and ROMable extension linked
into the THING system. For those that want further information on the THING system,
they are adequately documented on QUANTA DISK SPECIALS_0.

Acknowlegements

The key personnel involved in the development and implementation of the
Runtime Link Library concept are:

Tony Tebby
who developed the THING concept which allows for general purpose
    shareable objects to be easily loaded and manipulated. In particular
    thanks must got to Tony for allowing the support code for the THING
    system to be freely distributed.

Lester Wareham
who produced the original proposals for the RLL concept, and developed
    the original implementation of the RLM and Superbasic components of the system.

Dave Walker
who helped develop the RLL concept; enhancing the LD linker to support
    the concept of Runtime Link libraries; enhancing the C68 system to exploit
    the RLL system; and enhancing the RLM system to support full integration
    with LD and the rest of the C68 system

Joachim van der Auwera
Who provided the ideas and much of the software that underlies the
    "modules" part of the RLL system.

Copyright

The RLM component of the RLL system is freely distributable subject
to the following conditions:

The RLM and supporting files are copyright ©1992 L.K.Wareham.
    All rights reserved.

Every effort has been made to ensure that the RLM software operates correctly.
    However no guarantee of any kind is given that the programmes are reliable or
    that the information describing the RLM is accurate. It is up to the user to
    satisfy himself that the RLM is suitable for the use to which it will be put.

The RLM software may be distributed in user group or public domain libraries,
    posted on public access BBS, or distributed fee with commercial software
    provided that:

You do not profit by distributing RLM. You may only make reasonable charges
        for your time, media and postage costs. Any such charges (excluding postage)
        shall not exceed US$6.00.

In the case of distribution with a commercial software package, no charges
        may be made for the RLM component. A commercial package is defined as one
        that requires the user to pay more than US$6.00 for its use.

You may not claim ownership of, or any right to, the RLM software.

You may not place any restriction on the further distribution of the RLM software.

The complete RLM package must be enclosed including this notice with any
    further distribution.

The remainder of the RLL system is copyright ©1992-1997 D.J.Walker.
All rights reserved. Permission is granted for the RLL system to be freely
distributed on the same terms as the rest of the C68 system.


text:
HelloAngular
============

Source code accompanying series of blog posts about AngularJS


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="generator" content="Hugo 0.20.7">
    <meta name="theme" content="Tranquilpeak 0.3.1-BETA">
    <title>Phantomjs</title>
    <meta name="author" content="Paul Burgoine">
    <meta name="keywords" content="">

    <link rel="icon" href="/favicon.png">

      <link rel="alternate" type="application/rss+xml" title="RSS" href="/tags/phantomjs/index.xml">

    <meta name="description" content="Hugo tranquilpeak theme demo">
    <meta property="og:description" content="Hugo tranquilpeak theme demo">
    <meta property="og:type" content="blog">
    <meta property="og:title" content="Phantomjs">
    <meta property="og:url" content="/tags/phantomjs/">
    <meta property="og:site_name" content="Paul Burgoine">
    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Paul Burgoine">
    <meta name="twitter:description" content="Hugo tranquilpeak theme demo">

      <meta property="og:image" content="/images/me.png">

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/jquery.fancybox.css" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/helpers/jquery.fancybox-thumbs.min.css" />

    <link rel="stylesheet" href="/css/style-u6mk0ojoywresbx8iepslrmmhl4stuhrsxuwhkpwrkrx7mryjcaimasnk4pi.min.css" />

    Paul Burgoine

Paul Burgoine

Interested in data, visualisations, machine learning

      Categories

      Tags

      Archives

      About

      Home

      Stack Overflow

      GitHub

      RSS

          Web scraping fantasy premier league data using R

    <time itemprop="datePublished" datetime="2017-06-01T00:00:00Z">

  June 1, 2017

    </time>

    in

      R,

      Web scraping

        For my first project for this blog I decided to combine two of my loves, football and R. Having won my fantasy league this year with a respectable points haul of 2176, finishing in position 36,967 within England, and 94,774 globally I was interested to see which players were scoring me the most points.
 more text

        Continue reading

    © 2017 Paul Burgoine. All Rights Reserved

Paul Burgoine

Interested in data, visualisations, machine learning

        Data Enthusiast

        Manchester, UK

        by

      <form id="algolia-search-form">
        <input type="text" id="algolia-search-input" name="search"
          class="form-control input--large search-input" placeholder="Search" />
      </form>

no post found

Web scraping fantasy premier league data using R

                  Jun 6, 2017

For my first project for this blog I decided to combine two of my loves, football and R. Having won my fantasy league this year with a respectable points haul of 2176, finishing in position 36,967 within England, and 94,774 globally I was interested to see which players were scoring me the most points.
 more text

Posts

                  Jun 6, 2017

         2 posts found


text:
<?php

/**
 * @file
 * Autoloader for Drupal PHPUnit testing.
 *
 * @see phpunit.xml.dist
 */

use Drupal\Component\Assertion\Handle;

/**
 * Finds all valid extension directories recursively within a given directory.
 *
 * @param string $scan_directory
 *   The directory that should be recursively scanned.
 * @return array
 *   An associative array of extension directories found within the scanned
 *   directory, keyed by extension name.
 */
function drupal_phpunit_find_extension_directories($scan_directory) {
  $extensions = array();
  $dirs = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($scan_directory, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS));
  foreach ($dirs as $dir) {
    if (strpos($dir->getPathname(), '.info.yml') !== FALSE) {
      // Cut off ".info.yml" from the filename for use as the extension name. We
      // use getRealPath() so that we can scan extensions represented by
      // directory aliases.
      $extensions[substr($dir->getFilename(), 0, -9)] = $dir->getPathInfo()
        ->getRealPath();
    }
  }
  return $extensions;
}

/**
 * Returns directories under which contributed extensions may exist.
 *
 * @param string $root
 *   (optional) Path to the root of the Drupal installation.
 *
 * @return array
 *   An array of directories under which contributed extensions may exist.
 */
function drupal_phpunit_contrib_extension_directory_roots($root = NULL) {
  if ($root === NULL) {
    $root = dirname(dirname(__DIR__));
  }
  $paths = array(
    $root . '/core/modules',
    $root . '/core/profiles',
    $root . '/modules',
    $root . '/profiles',
  );
  $sites_path = $root . '/sites';
  // Note this also checks sites/../modules and sites/../profiles.
  foreach (scandir($sites_path) as $site) {
    if ($site[0] === '.' || $site === 'simpletest') {
      continue;
    }
    $path = "$sites_path/$site";
    $paths[] = is_dir("$path/modules") ? realpath("$path/modules") : NULL;
    $paths[] = is_dir("$path/profiles") ? realpath("$path/profiles") : NULL;
  }
  return array_filter($paths);
}

/**
 * Registers the namespace for each extension directory with the autoloader.
 *
 * @param array $dirs
 *   An associative array of extension directories, keyed by extension name.
 *
 * @return array
 *   An associative array of extension directories, keyed by their namespace.
 */
function drupal_phpunit_get_extension_namespaces($dirs) {
  $namespaces = array();
  foreach ($dirs as $extension => $dir) {
    if (is_dir($dir . '/src')) {
      // Register the PSR-4 directory for module-provided classes.
      $namespaces['Drupal\\' . $extension . '\\'][] = $dir . '/src';
    }
    if (is_dir($dir . '/tests/src')) {
      // Register the PSR-4 directory for PHPUnit test classes.
      $namespaces['Drupal\\Tests\\' . $extension . '\\'][] = $dir . '/tests/src';
    }
  }
  return $namespaces;
}

// We define the COMPOSER_INSTALL constant, so that PHPUnit knows where to
// autoload from. This is needed for tests run in isolation mode, because
// phpunit.xml.dist is located in a non-default directory relative to the
// PHPUnit executable.
if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
  define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/../../autoload.php');
}

/**
 * Populate class loader with additional namespaces for tests.
 *
 * We run this in a function to avoid setting the class loader to a global
 * that can change. This change can cause unpredictable false positives for
 * phpunit's global state change watcher. The class loader can be retrieved from
 * composer at any time by requiring autoload.php.
 */
function drupal_phpunit_populate_class_loader() {

  /** @var \Composer\Autoload\ClassLoader $loader */
  $loader = require __DIR__ . '/../../autoload.php';

  // Start with classes in known locations.
  $loader->add('Drupal\\Tests', __DIR__);
  $loader->add('Drupal\\KernelTests', __DIR__);
  $loader->add('Drupal\\FunctionalTests', __DIR__);
  $loader->add('Drupal\\FunctionalJavascriptTests', __DIR__);

  if (!isset($GLOBALS['namespaces'])) {
    // Scan for arbitrary extension namespaces from core and contrib.
    $extension_roots = drupal_phpunit_contrib_extension_directory_roots();

    $dirs = array_map('drupal_phpunit_find_extension_directories', $extension_roots);
    $dirs = array_reduce($dirs, 'array_merge', array());
    $GLOBALS['namespaces'] = drupal_phpunit_get_extension_namespaces($dirs);
  }
  foreach ($GLOBALS['namespaces'] as $prefix => $paths) {
    $loader->addPsr4($prefix, $paths);
  }

  return $loader;
};

// Do class loader population.
drupal_phpunit_populate_class_loader();

// Set sane locale settings, to ensure consistent string, dates, times and
// numbers handling.
// @see \Drupal\Core\DrupalKernel::bootEnvironment()
setlocale(LC_ALL, 'C');

// Set the default timezone. While this doesn't cause any tests to fail, PHP
// complains if 'date.timezone' is not set in php.ini. The Australia/Sydney
// timezone is chosen so all tests are run using an edge case scenario (UTC+10
// and DST). This choice is made to prevent timezone related regressions and
// reduce the fragility of the testing system in general.
date_default_timezone_set('Australia/Sydney');

// Runtime assertions. PHPUnit follows the php.ini assert.active setting for
// runtime assertions. By default this setting is on. Here we make a call to
// make PHP 5 and 7 handle assertion failures the same way, but this call does
// not turn runtime assertions on if they weren't on already.
Handle::register();


text:
<?php

declare(strict_types=1);

namespace Soluble\Jasper\Exception;

use Soluble\Japha\Bridge\Exception\JavaException;

class JavaProxiedException extends RuntimeException implements JavaProxiedExceptionInterface
{
    /**
     * @var JavaException
     */
    private $javaException;

    public function __construct(JavaException $javaException, ?string $msg = null, ?int $code = null)
    {
        $this->javaException = $javaException;
        $message             = sprintf(
            '%s[%s]: %s (%s)',
            $msg !== null ? "$msg. " : '',
            $javaException->getJavaClassName(),
            $javaException->getMessage(),
            $javaException->getCause()
        );
        parent::__construct($message, $code ?? $javaException->getCode());
    }

    /**
     * Return java exception as return by the bridge server.
     */
    public function getJavaException(): JavaException
    {
        return $this->javaException;
    }

    /**
     * Return the JVM exception backtrace.
     */
    public function getJvmStackTrace(): string
    {
        return $this->javaException->getStackTrace();
    }
}


text:
package p05_SayHelloExtended.persons;

public class Chinese extends BasePerson implements Person {

	public Chinese(String name) {
		super(name);
	}

	@Override
	public void sayHello() {
		System.out.println("Djydjybydjy");
	}

}


text:
embedded-webviews-aka-browser-controls-vs-native-ui.md

## TL;DR - Embedded WebViews vs Native UI

*   Embedded WebViews have bigger API surface

    Bigger API surface means more opportunities for malicious software/users, from ability
    to decompile application, to ability to read loaded URL, manipulate cache and cookies.

*   Embedded WebViews have seamless UX

    Embedded WebViews usage does not leave application and launches external system browser,
    meaning user stays in the application.

*   Embedded WebViews do not require advanced programming techniques

    Leaving application to perform authentication in external browser means the callback
    (return to the application) from browser must be implemented. The only and proper
    technique for that is called "Deep App Linking" (or just Deep Linking or App Linking).
    This technique is everything, but trivial, because developer needs to register callback
    custom schemes and implement scheme intercepting which is platform specific.

*   Native UI has 'reduced API surface'

    'Reduced API surface' means that in most cases (most meaning **all** - for Android
	CustomTabs and iOS SFSafariWebView) developer is **not** able to:

    *   retrieve URL loaded in the (system, external) browser

    *   manipulate Cookies and Cache

*   Native UI is based on maintained codebase of system browser

    *   Android - Chromium/Chrome browser
    *   iOS - Safari browser

*   Native UI is regularly updated by system updates (browser updates)

*   Native UI utilizes browser identity (password/account) management (built-in or as plugin)

## Native external system browser

*	Pros
	*	security
		*	proven codebase
		*	regular system updates
	*	use of browser features and API
		*	use of system
			*	account store (might be implemented as plugin/extension)
			*	cookie store, so it is able to take advantage of active sessions
			*	chrome which can display important security information about loaded
				page
		* 	plugins/extensions
*	Cons
	*	external process - app logic is leaving app and switching to system browser
		*	custom schemes used
			*	additional coding needed
			*	debugging could be non-trivial
	*	version problems (browser versions)
	*	fragmentation (Android)
		4 versions of Chrome Browser, Opera, Firefox, Samsung browsers that support
		CustomTabs

##

## Details

In 2016-08 (2016-06-22) on Google's develoers' blog Google announced ban for OAuth
implementations that use Embedded WebViews (Browser Controls on Windows platforms) for
security reasons.

https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html

The document is available here:

https://developers.google.com/identity/protocols/OAuth2InstalledApp#request-parameter-redirect_uri

NOTE: 2017-05-20 The document it is changing day by day a lot of information not available 2-3
weeks ago have made it to the doc.

## Remarks

### `redirect_url`

## TL;DR

Few facts for Google:

*   Google generates custom scheme[s] for `redirect_url`

    *   based on app info which is provided to Google in developer console:

        *   Android package name (from AndroidManifest.xml)

            In Visual Studio and Xamarin.Studio go to

            Android App +/ Project Options/Properties +/ Android Application +/ Package name

            and copy the value for Package name (something like `com.xamarin.comicbook`)

        *   iOS Bundle Identifier

            iOS App +/ Open Info.plist +/ Identity +/ Bundle Identifier

            and copy the value for Bundle Identifier (something like `com.xamarin.comicbook`)

### Facebook

https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow

Security
    Server IP Whitelist

    App requests using the app secret must originate from these IP addresses.
    Update Settings IP Whitelist

    App Settings can only be updated from these IP addresses.

    Require App Secret
    Only allow calls from a server and require app secret or app secret proof for all API calls.

Facebook login

    Settings

    Client OAuth Settings
YesNo
Client OAuth Login
Enables the standard OAuth client token flow. Secure your application and prevent abuse by locking down which token redirect URIs are allowed with the options below. Disable globally if not used.

https://developers.facebook.com/docs/facebook-login/security/#surfacearea

Disable Client OAuth Login if your app does not use it. Client OAuth Login is the global on-off switch for using OAuth client token flows. If your app does not use any client OAuth flows, which include Facebook login SDKs, you should disable this flow. Note, though, that you can't request permissions for an access token if you have Client OAuth Login disabled. This setting is found in the Products > Facebook Login > Settings section.

YesNo   Web OAuth Login
Enables web based OAuth client login for building custom login flows.

https://developers.facebook.com/docs/facebook-login/security/#surfacearea

Disable Web OAuth Flow or Specify a Redirect Whitelist. Web OAuth Login settings enables any OAuth client token flows that use the Facebook web login dialog to return tokens to your own website. This setting is in the Products > Facebook Login > Settings section. Disable this setting if you are not building a custom web login flow or using the Facebook Login SDK on the web.

When this setting is enabled you are required to specify a list of OAuth redirect URLs. Specify an exhaustive set of app URLs that are the only valid redirect URLs for your app for returning access tokens and codes from the OAuth flow.

YesNo
Force Web OAuth Reauthentication
When on, prompts people to enter their Facebook password in order to log in on the web.

YesNo
Embedded Browser OAuth Login
Enables browser control redirect uri for OAuth client login.

Disable embedded browser OAuth flow if your app does not use it. Some desktop and mobile native apps authenticate users by doing the OAuth client flow inside an embedded webview. If your app does not do this, then disable the setting in Products > Facebook Login > Settings section.

https://github.com/tschellenbach/Django-facebook/issues/376

### iOS

1. Download and Install the Facebook SDK for iOS

    No need. Xamarin.Auth is used.

2. Add Login Kit to your Xcode Project

    Not needed.

3. Add your Bundle Identifier

Bundle ID
You can change your bundle identifier in the future via the iOS section on the settings page.
com.xamarin.comicbook.iosRemove

4. Enable Single Sign On for Your App

Enable Single Sign On
Enable single sign on for your app by setting Single Sign On to Yes below.
YesNo
Single Sign On
Will launch from iOS Notifications

5. Configure Your info.plist

 Configure Your info.plist
Find the .plist file in the Supporting Files folder in your Xcode Project.
Right-click your .plist file and choose "Open As Source Code".
Copy and paste the following XML snippet into the body of your file ( <dict>...</dict>).

<key>CFBundleURLTypes</key>
<array>
  <dict>
  <key>CFBundleURLSchemes</key>
  <array>
    <string>fb1889013594699403</string>
  </array>
  </dict>
</array>
<key>FacebookAppID</key>
<string>1889013594699403</string>
<key>FacebookDisplayName</key>
<string>Xamarin.Auth.Native.ComicBk</string>

6. Connect App Delegate

## Detailed Recap

To recap and add some information not available in the doc. Some information is scattered in
sample repos on github and in other docs.

The key point of Native UI is security, though Google mentions USability too. Web app (or some call
it Server app) is considered to be secure. Namely it takes more to get to the filesystem of the
server (well maintained) than to some random user smartphone - and to retrieve app id and `client_secret`
(more important).
Web/server apps usually use Authorization Grant flow (2 steps, some call it explicit) and in
2nd step `client_secret` is sent.

Native apps (Installed apps, though some differ mobile and desktop) are considered to be insecure,
because client_secret (and other data) cannot be stored securely (decompiling or anything). User doesn't
even need to lose your smartphone it can be in the hands of users less skilled in security - thus insecure.

Web/Server apps have redirect_url with http[s] scheme, because after login you (as web admin)
would redirect user back to your web app to parse OAuth data and present something after
successful login (might be data from database).

We "faked" server with Xamarin.Auth for long time (check redirect_url from forums for FB
http://facebook.com/blahblah/login_succes.html
I used http[s]://xamarin.com or whatever…

Error: invalid_request

Custom scheme URIs are not allowed for WEB client type.