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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>pymatgen.io.lammps.topology module — pymatgen 2017.11.6 documentation</title>
    <link rel="stylesheet" href="_static/proBlue.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />

Navigation

          index

          modules |

pymatgen 2017.11.6 documentation »

pymatgen.io.lammps.topology module¶

class Topology(atoms, bonds, angles, charges=None, dihedrals=None, imdihedrals=None)[source]¶

Bases: monty.json.MSONable

<col class="field-name" />
<col class="field-body" />

Parameters:

atoms (list) – map atom names to force field(ff) atom name,
[['c', 'c1'],…]

bonds (list) – List of bonds,
[[i,j, bond_type], … ] where i, j are integer(starts from 1)
atom ids in the molecules and bond_type = (ff atomname_i, ff atomname_j)

angles (list) – List of angles,
[[i,j,k, angle_type], … ],
angle_type = (ff atomname_i, ff atomname_j, ff atomname_k)

charges (list) – List of charges, [0.4, 0.7, … ]

dihedrals (list) – List of dihedrals,
[[i,j,k,l, dihedral_type], … ]
dihedral_type = (ff atomname_i, ff atomname_j, ff atomname_k, ff atomname_l)

imdihedrals (list) – List of improper dihedrals,
[['i,j,k,l, dihedral_type], … ]

static from_molecule(molecule, tol=0.1, ff_map='ff_map')[source]¶

Return Topology object from molecule. Charges are also set if the
molecule has 'charge' site property.

<col class="field-name" />
<col class="field-body" />

Parameters:

molecule (Molecule) –

tol (float) – Relative tolerance to test in determining the bonds
in the molecule. Basically, the code checks if the distance
between the sites is less than (1 + tol) * typical bond
distances. Defaults to 0.1, i.e., 10% longer.

ff_map (string) – Ensure this site property is set for each site if
atoms need to be mapped to its forcefield name.
eg: Carbon atom, 'C', on different sites can be mapped to
either 'Ce' or 'Cm' depending on how the forcefield parameters
are set.

Returns:
Topology object

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          modules |

pymatgen 2017.11.6 documentation »

        © Copyright 2011, Pymatgen Development Team.
      Created using Sphinx 1.6.5.

This page uses
Google Analytics to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.


text:
package com.clearbit.client.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.clearbit.ApiClient;
import com.clearbit.ApiException;
import com.clearbit.Configuration;
import com.clearbit.Pair;
import com.clearbit.TypeRef;
import com.clearbit.client.model.Person;

public class PersonApi {
  private final ApiClient apiClient;
  private final String URL = "https://person.clearbit.com/v2/people/find";
  private final String STREAMING_URL = "https://person-stream.clearbit.com/v2/people/find";

  public PersonApi() {
    this(Configuration.getDefaultApiClient());
  }

  public PersonApi(ApiClient apiClient) {
    this.apiClient = apiClient;
  }

  public ApiClient getApiClient() {
    return apiClient;
  }

  /**
   * The Person API lets you retrieve social information associated with an email address,
   * such as a person's name, location and Twitter handle.
   * This is a blocking operation. If the person is not in the Clearbit database,
   * the connection will be held open until the lookup has completed. Typically 3-5 seconds.
   * @param email the person's email address
   * @return Person
   */
  public Person streamingLookup(String email) throws ApiException {
    // verify the required parameters are set
    if (email == null) {
      throw new ApiException(400, "Missing the required parameter 'email' when calling PersonApi.streamingLookup");
    }

    // query params
    List<Pair> params = new ArrayList<Pair>();
    params.add(new Pair("email", email.toString()));

    return doReq(STREAMING_URL, params);
  }

  /**
   * Person API
   * The Person API lets you retrieve social information associated with an email address, such as a person's name, location and Twitter handle.
   * @param email the person's email address
   * @return A cached Person, which may often be null. Registered webhook will receive actual response.
   */
  public Person lookup(String email) throws ApiException {
    return lookup(email, null);
  }

  public Person lookup(String email, String webhookId) throws ApiException {
    return lookup(email,webhookId,null);
  }

  //Include custom webhook url for lookup call
  public Person lookup(String email, String webhookId, String webhookUrl) throws ApiException {
    // verify the required parameter 'email' is set
    if (email == null) {
      throw new ApiException(400, "Missing the required parameter 'email' when calling PersonApi.lookup");
    }

    // query params
    List<Pair> params = new ArrayList<Pair>();
    params.add(new Pair("email", email.toString()));

    if (webhookId != null) {
      params.add(new Pair("webhook_id", webhookId.toString()));
    }

    if (webhookUrl != null) {
      params.add(new Pair("webhook_url", webhookUrl));
    }

    return doReq(URL, params);
  }

  // doReq handles the HTTP request to the API endpoint
  private Person doReq(String uri, List<Pair> queryParams) throws ApiException {
  	Object postBody = null;
  	byte[] postBinaryBody = null;

  	Map<String, String> headerParams = new HashMap<String, String>();
  	Map<String, Object> formParams = new HashMap<String, Object>();

  	String accept = apiClient.selectHeaderAccept(new String[]{});
  	String contentType = apiClient.selectHeaderContentType(new String[]{});
  	String[] authNames = new String[] { "Basic Authentication" };

  	TypeRef<Person> returnType = new TypeRef<Person>() {};
  	return apiClient.invokeAPI(uri, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
  }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  BaseCache.h
//  Pods
//
//  Created by Prabodh Prakash on 06/09/15.
//
//

#import <Foundation/Foundation.h>
#import "Value.h"
#import "Node.h"

#pragma mark protocols

@protocol CacheProtocol <NSObject>

/*!
 This function is used to cache value against a uniquely identifying key.
 @param value Value that needs to be cached

 @param key Key that needs to be used for retrieval

 @return returns a YES, if the data was properly cached else NO.
 */
- (BOOL) cacheValue:(Value*) value forKey:(NSString*)key;

/*!
 This method will retrieve the cached value against key. If the value is not present in memory,
 it will look out in the mirrored and then the fallback cache.

 @param key NSString type for which the cached value needs to be retrieved

 @return Retrieved cached value as Node. It returns nil if no cached value is found.
 */
- (Value*) getValueForKey:(NSString*) key;

/*!
 This method will clear all values from this cache and the mirrored and fallback cache in a cascading manner. This would be a blocking call
 */
- (void) clearCacheAndCascade;

@end

@protocol CacheAlgorithmProtocol <NSObject>

@required

/*!
 @param node Node type that needs to be cached
 */
- (BOOL) cacheNode: (Node*) node;

/*!
 This method will retrieve the cached value against key. If the value is not present in memory,
 it will look out in mirrored or fallback cache in cascading manner.

 @param key String value for which the cached value needs to be retrieved

 @return Retrieved cached value as Node. It returns nil if no cached value is found.
 */
- (Node*) getNodeForKey:(NSString*) key;

/*!
 This method will clear all values from cache
 */
- (void) clearCache;

@end

#pragma mark classes

@interface BaseCache : NSObject <CacheProtocol, CacheAlgorithmProtocol>

/*!
 Holds the fallback cache
 */
@property (nonatomic, strong) BaseCache* fallBackCache;

/*!
 Holds the mirrored cache
 */
@property (nonatomic, strong) BaseCache* mirroredCache;

@end


text:
<?php

/**
 * IPluggableAccessRole interface file.
 *
 * This interface describes a role. This role may have certain parameters to
 * be defined and a business rule that must be applied in order to determine
 * if the access-based control must apply.
 *
 * @author Anastaszor
 */
interface IPluggableAccessRole
{

	const RING_NO_PERMISSION    =    1;
	const RING_AUTHENTICATED    = 1024;
	const RING_CONTENT_PROVIDER = 2048;
	const RING_MODERATOR        = 3072;
	const RING_SUPERMODERATOR   = 4096;
	const RING_ADMINISTRATOR    = 5120;
	const RING_SUPERADMIN       = 6144;

	/**
	 * Gets the name of the role. This should be something that the module has
	 * correctly identified in order to be able to retrieve it later.
	 *
	 * @return string
	 */
	public function getRoleName();

	/**
	 * Gets the level, or type of the item. (0: operation, 1: task, 2: role).
	 * Those values are available at CAuthItem::TYPE_OPERATION,
	 * CAuthItem::TYPE_TASK and CAuthItem::TYPE_ROLE.
	 *
	 * @return integer
	 * @see CAuthItem
	 */
	public function getLevel();

	/**
	 * Gets the permission ring needed to be allowed to perform the action
	 * that are allowed by this role. Those values are available with the RING_*
	 * constants of this interface.
	 *
	 * @return integer.
	 */
	public function getRing();

	/**
	 * Gets the business rule that must be applied when checking if a user
	 * really has access granted by this rule to a specific resource.
	 *
	 * The access to the data values must be done using the variable __data__,
	 * which will be given as an array. The business rule must check for
	 * existance of each key it tries to use from such array.
	 *
	 * The business rule must return a boolean. If no boolean or if null is
	 * returned, the result will be considered false and access through this
	 * role will be denied.
	 *
	 * @return string
	 */
	public function getBusinessRule();

	/**
	 * Gets some default data that may be used into the business rule. Those
	 * data will be accessible into the business rule through the __data__
	 * variable.
	 *
	 * @return mixed[]
	 */
	public function getData();

}


text:
package au.gov.amsa.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;

import net.jcip.annotations.NotThreadSafe;

/**
 * Non-threadsafe implementation of a Ring Buffer. Does not accept nulls.
 *
 * @param <T>
 */
@NotThreadSafe
public class RingBuffer<T> implements Queue<T> {

    private final T[] list;
    private int start;
    private int finish;

    @SuppressWarnings("unchecked")
    private RingBuffer(int size) {
        list = (T[]) new Object[size + 1];
    }

    public static <T> RingBuffer<T> create(int size) {
        return new RingBuffer<T>(size);
    }

    @Override
    public void clear() {
        finish = start;
    }

    @Override
    public Iterator<T> iterator() {
        final int _start = start;
        final int _finish = finish;
        return new Iterator<T>() {
            int i = _start;

            @Override
            public boolean hasNext() {
                return i != _finish;
            }

            @Override
            public T next() {
                T value = list[i];
                i = (i + 1) % list.length;
                return value;
            }
        };
    }

    @Override
    public T peek() {
        if (start == finish)
            return null;
        else
            return list[start];
    }

    public boolean isEmpty() {
        return start == finish;
    }

    public int size() {
        if (start <= finish)
            return finish - start;
        else
            return finish - start + list.length;
    }

    public int maxSize() {
        return list.length - 1;
    }

    @Override
    public boolean contains(Object o) {
        return notImplemented();
    }

    @Override
    public Object[] toArray() {
        return notImplemented();
    }

    @Override
    public <S> S[] toArray(S[] a) {
        return notImplemented();
    }

    @Override
    public boolean remove(Object o) {
        return notImplemented();
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return notImplemented();
    }

    private static <T> T notImplemented() {
        throw new RuntimeException("Not implemented");
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
        for (T t : c)
            add(t);
        return true;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return notImplemented();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return notImplemented();
    }

    @Override
    public boolean add(T t) {
        if (offer(t))
            return true;
        else
            throw new IllegalStateException("Cannot add to queue because is full");
    }

    @Override
    public boolean offer(T t) {
        if (t == null)
            throw new NullPointerException();
        int currentFinish = finish;
        finish = (finish + 1) % list.length;
        if (finish == start) {
            return false;
        } else {
            list[currentFinish] = t;
            return true;
        }
    }

    @Override
    public T remove() {
        T t = poll();
        if (t == null)
            throw new NoSuchElementException();
        else
            return t;
    }

    @Override
    public T poll() {
        if (start == finish) {
            return null;
        } else {
            T value = list[start];
            // don't hold a reference to a popped value
            list[start] = null;
            start = (start + 1) % list.length;
            return value;
        }
    }

    @Override
    public T element() {
        return notImplemented();
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Mark
 * Date: 2015/12/28
 * Time: 0:03
 */

namespace Tests\Models;

use ManaPHP\Data\Db\Model;

class Inventory extends Model
{
    public $inventory_id;
    public $film_id;
    public $store_id;
    public $last_update;
}


text:
package org.chocosolver.solver.constraints.ternary;

import org.chocosolver.choco.checker.DomainBuilder;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.search.strategy.IntStrategyFactory;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.VariableFactory;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Random;

/**
 * <br/>
 *
 * @author Charles Prud'homme
 * @since 17/07/12
 */
public abstract class AbstractTernaryTest {

    protected long brutForceTest(int[][] domains, boolean bounded) {
        long nbSol = 0;
        int vx, vy, vz;
        if (bounded) {
            for (vx = domains[0][0]; vx <= domains[0][1]; vx++) {
                for (vy = domains[1][0]; vy <= domains[1][1]; vy++) {
                    for (vz = domains[2][0]; vz <= domains[2][1]; vz++) {
                        nbSol += validTuple(vx, vy, vz);
                    }
                }
            }
        } else {
            for (int i = 0; i < domains[0].length && (vx = domains[0][i]) >= domains[0][0]; i++) {
                for (int j = 0; j < domains[1].length && (vy = domains[1][j]) >= domains[1][0]; j++) {
                    for (int k = 0; k < domains[2].length && (vz = domains[2][k]) >= domains[2][0]; k++) {
                        nbSol += validTuple(vx, vy, vz);
                    }
                }
            }
        }
        return nbSol;
    }

    protected abstract int validTuple(int vx, int vy, int vz);

    protected abstract Constraint make(IntVar[] vars, Solver solver);

    public Solver modeler(int[][] domains, boolean bounded, long seed) {
        Solver s = new Solver();
        IntVar[] vars = new IntVar[3];
        for (int i = 0; i < 3; i++) {
            if (bounded) {
                vars[i] = VariableFactory.bounded("x_" + i, domains[i][0], domains[i][1], s);
            } else {
                vars[i] = VariableFactory.enumerated("x_" + i, domains[i], s);
            }
        }
        Constraint div = make(vars, s);
        s.post(div);
		if(bounded){
			s.set(IntStrategyFactory.random_bound(vars, seed));
		}else{
			s.set(IntStrategyFactory.random_value(vars, seed));
		}
        return s;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    @Test(groups = "10s")
    public void test1() {
        boolean bounded; // true if domains are bounded, false if they are enumerated
        Random rand = new Random(0);
        for (int k = 0; k < 20000; k++) {
            long seed = System.currentTimeMillis();
            rand.setSeed(seed);
            bounded = rand.nextBoolean();
            int size = 5; // domain size
            int range = 15; // value range
            int[][] domains;
            if (bounded) {
                domains = DomainBuilder.buildFullDomains(3, size, range, rand);
            } else {
                domains = DomainBuilder.buildFullDomains2(3, size, range, rand, rand.nextDouble(), rand.nextBoolean());
            }
            // total number of solutions: brut force algorithm
            long base = brutForceTest(domains, bounded);
            Solver s = modeler(domains, bounded, seed);
//            SearchMonitorFactory.log(s, false, false);
            try {
                s.findAllSolutions();
            } catch (AssertionError ae) {
                System.err.printf("seed: %d\n", seed);
                throw ae;
            }
            long cp = s.getMeasures().getSolutionCount();
            Assert.assertEquals(cp, base, "found: " + cp + " solutions, while " + base + " are expected (" + seed + ")");
        }
    }
}


text:
"""
Author: Armon Dadgar
Description:
    This test checks the behavior of dy_dispatch_module and makes sure it is sane.

Expected Output:
    You should see 'Steps (i/4)' where i is 1..4
"""

# We should alway have HAS_DYLINK = True
if not HAS_DYLINK:
  print "We don't have Dylink available!"

# Switch our behavior on the callfunc
if callfunc == "initialize":
  print "Step (1/4)"

  # Set the next module to be ourself
  callargs = ["test_dylink_dispatch"]

  # Set the callfunc to "check" now
  callfunc = "check"

# This checks that the dispatch worked
elif callfunc == "check":
  print "Step (2/4)"

# This tests that exit is being propogated
elif callfunc == "exit":
  # Update the callfunc again
  callfunc = "check_exit"

  print "Step (3/4)"

# Check the exit propogates
elif callfunc == "check_exit":
  print "Step (4/4)"

# Catch any weird behavior
else:
  print "Error! Unknown callfunc!"

# Always do a dispatch
did_run = dy_dispatch_module()

# If the callfunc doesn't have "check" in it, then did_run should be true.
# This is because the module directly after dylink should always evaluate
# itself again.
if "check" not in callfunc and not did_run:
  print "Did not perform a recursive evaluation!"


text:
using Warden.Core;

namespace Warden.Watchers
{
    /// <summary>
    /// Holds the information about the watcher check result.
    /// This interface is implemented by the specific watchers which allows to pass the custom data.
    /// It's being used by most of the watcher hooks.
    /// </summary>
    public interface IWatcherCheckResult : IValidatable, IWatcherCheck
    {
        /// <summary>
        /// Custom description of the performed watcher check.
        /// </summary>
        string Description { get; }
    }

    public class WatcherCheckResult : WatcherCheck, IWatcherCheckResult
    {
        public string Description { get; }
        public bool IsValid { get; }

        protected WatcherCheckResult(IWatcher watcher, bool isValid, string description) : base(watcher)
        {
            Description = description;
            IsValid = isValid;
        }

        /// <summary>
        /// Factory method for creating a new instance of the IWatcherCheckResult.
        /// </summary>
        /// <param name="watcher">Instance of IWatcher.</param>
        /// <param name="isValid">Flag determining whether the performed check was valid.</param>
        /// <param name="description">Custom description of the performed check.</param>
        /// <returns>Instance of IWatcherCheckResult.</returns>
        public static IWatcherCheckResult Create(IWatcher watcher, bool isValid, string description = "")
            => new WatcherCheckResult(watcher, isValid, description);
    }
}


text:
using System.Reflection;
using Dynamix.Metadata;
using Dynamix.Utils;

namespace Dynamix.Builder
{
    class NestedInterfaceBuilder : InterfaceBuilderBase
    {
        private NestedInterface Interface
        {
            get { return InterfaceBase as NestedInterface; }
        }

        internal NestedInterfaceBuilder(NestedInterface dynamicInterface)
            : base(dynamicInterface)
        {

        }

        protected override System.Reflection.Emit.TypeBuilder DefineType()
        {
            return Interface.Parent.Builder.DefineNestedType(Interface);
        }

        internal override TypeAttributes TypeAttributes
        {
            get
            {
                return TypeAttributes.Interface | TypeAttributes.Abstract |
                       Interface.AccessModifier.GetNestedTypeAccessAttributes();
            }
        }
    }
}


text:
#pragma once
#include <aws/application-autoscaling/ApplicationAutoScaling_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace ApplicationAutoScaling
{
namespace Model
{

  /**
   *
Represents a step adjustment for a StepScalingPolicyConfiguration.
   * Describes an adjustment based on the difference between the value of the
   * aggregated CloudWatch metric and the breach threshold that you've defined for
   * the alarm.

For the following examples, suppose that you have an alarm
   * with a breach threshold of 50:

To trigger the adjustment when
   * the metric is greater than or equal to 50 and less than 60, specify a lower
   * bound of 0 and an upper bound of 10.

To trigger the adjustment
   * when the metric is greater than 40 and less than or equal to 50, specify a lower
   * bound of -10 and an upper bound of 0.

There are a few rules
   * for the step adjustments for your step policy:

The ranges of
   * your step adjustments can't overlap or have a gap.

At most one
   * step adjustment can have a null lower bound. If one step adjustment has a
   * negative lower bound, then there must be a step adjustment with a null lower
   * bound.

At most one step adjustment can have a null upper
   * bound. If one step adjustment has a positive upper bound, then there must be a
   * step adjustment with a null upper bound.

The upper and lower
   * bound can't be null in the same step adjustment.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_APPLICATIONAUTOSCALING_API StepAdjustment
  {
  public:
    StepAdjustment();
    StepAdjustment(const Aws::Utils::Json::JsonValue& jsonValue);
    StepAdjustment& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The lower bound for the difference between the alarm threshold and the
     * CloudWatch metric. If the metric value is above the breach threshold, the lower
     * bound is inclusive (the metric must be greater than or equal to the threshold
     * plus the lower bound). Otherwise, it is exclusive (the metric must be greater
     * than the threshold plus the lower bound). A null value indicates negative
     * infinity.

     */
    inline double GetMetricIntervalLowerBound() const{ return m_metricIntervalLowerBound; }

    /**
     *
The lower bound for the difference between the alarm threshold and the
     * CloudWatch metric. If the metric value is above the breach threshold, the lower
     * bound is inclusive (the metric must be greater than or equal to the threshold
     * plus the lower bound). Otherwise, it is exclusive (the metric must be greater
     * than the threshold plus the lower bound). A null value indicates negative
     * infinity.

     */
    inline void SetMetricIntervalLowerBound(double value) { m_metricIntervalLowerBoundHasBeenSet = true; m_metricIntervalLowerBound = value; }

    /**
     *
The lower bound for the difference between the alarm threshold and the
     * CloudWatch metric. If the metric value is above the breach threshold, the lower
     * bound is inclusive (the metric must be greater than or equal to the threshold
     * plus the lower bound). Otherwise, it is exclusive (the metric must be greater
     * than the threshold plus the lower bound). A null value indicates negative
     * infinity.

     */
    inline StepAdjustment& WithMetricIntervalLowerBound(double value) { SetMetricIntervalLowerBound(value); return *this;}

    /**
     *
The upper bound for the difference between the alarm threshold and the
     * CloudWatch metric. If the metric value is above the breach threshold, the upper
     * bound is exclusive (the metric must be less than the threshold plus the upper
     * bound). Otherwise, it is inclusive (the metric must be less than or equal to the
     * threshold plus the upper bound). A null value indicates positive infinity.

     *
The upper bound must be greater than the lower bound.

     */
    inline double GetMetricIntervalUpperBound() const{ return m_metricIntervalUpperBound; }

    /**
     *
The upper bound for the difference between the alarm threshold and the
     * CloudWatch metric. If the metric value is above the breach threshold, the upper
     * bound is exclusive (the metric must be less than the threshold plus the upper
     * bound). Otherwise, it is inclusive (the metric must be less than or equal to the
     * threshold plus the upper bound). A null value indicates positive infinity.

     *
The upper bound must be greater than the lower bound.

     */
    inline void SetMetricIntervalUpperBound(double value) { m_metricIntervalUpperBoundHasBeenSet = true; m_metricIntervalUpperBound = value; }

    /**
     *
The upper bound for the difference between the alarm threshold and the
     * CloudWatch metric. If the metric value is above the breach threshold, the upper
     * bound is exclusive (the metric must be less than the threshold plus the upper
     * bound). Otherwise, it is inclusive (the metric must be less than or equal to the
     * threshold plus the upper bound). A null value indicates positive infinity.

     *
The upper bound must be greater than the lower bound.

     */
    inline StepAdjustment& WithMetricIntervalUpperBound(double value) { SetMetricIntervalUpperBound(value); return *this;}

    /**
     *
The amount by which to scale, based on the specified adjustment type. A
     * positive value adds to the current scalable dimension while a negative number
     * removes from the current scalable dimension.

     */
    inline int GetScalingAdjustment() const{ return m_scalingAdjustment; }

    /**
     *
The amount by which to scale, based on the specified adjustment type. A
     * positive value adds to the current scalable dimension while a negative number
     * removes from the current scalable dimension.

     */
    inline void SetScalingAdjustment(int value) { m_scalingAdjustmentHasBeenSet = true; m_scalingAdjustment = value; }

    /**
     *
The amount by which to scale, based on the specified adjustment type. A
     * positive value adds to the current scalable dimension while a negative number
     * removes from the current scalable dimension.

     */
    inline StepAdjustment& WithScalingAdjustment(int value) { SetScalingAdjustment(value); return *this;}

  private:
    double m_metricIntervalLowerBound;
    bool m_metricIntervalLowerBoundHasBeenSet;
    double m_metricIntervalUpperBound;
    bool m_metricIntervalUpperBoundHasBeenSet;
    int m_scalingAdjustment;
    bool m_scalingAdjustmentHasBeenSet;
  };

} // namespace Model
} // namespace ApplicationAutoScaling
} // namespace Aws


text:
<?php

namespace app\components\object_block;

use yii\base\Widget;

class ObjectBlock extends Widget
{

  public $model;
  private $house_url;

  public function init()
  {
    if ($this->model->type === 'residential') $this->house_url = 'residential-house-view';
    if ($this->model->type === 'apartment_house') $this->house_url = 'apartment-house-view';
    if ($this->model->type === 'non_residential') $this->house_url = 'non-residential-house-view';

    parent::init();
  }

  public function run()
  {

    if ($this->model->type === 'apartment' || $this->model->type === 'office')
      return $this->render('space', [
        'model' => $this->model,
      ]);

    if ($this->model->type === 'land')
      return $this->render('land', [
        'model' => $this->model,
      ]);

    if (
      $this->model->type === 'non_residential'
      || $this->model->type === 'apartment_house'
      || $this->model->type === 'residential'
    )
      return $this->render('house', [
        'model' => $this->model,
        'house_url' => $this->house_url,
      ]);

  }
}


text:
import { Suggestion as DefaultSuggestion } from 'azk/generator/suggestions/node';

export class Suggestion extends DefaultSuggestion {
  constructor(...args) {
    super(...args);

    var name    = 'node';
    var version = '0.10';
    // Readable name for this suggestion
    this.name = `${name}-${version}`;

    // Which rules they suggestion is valid
    this.ruleNamesList = [`${name}-${version}`];

    // Initial Azkfile.js suggestion
    this.suggestion = this.extend({}, this.suggestion, {
      __type: `${name} ${version}`,
      image : { docker: `azukiapp/${name}:${version}` },
    });
  }
}


text:
package com.google.devtools.depan.maven.eclipse;

import com.google.devtools.depan.eclipse.visualization.ogl.GLEntity;
import com.google.devtools.depan.eclipse.visualization.ogl.ShapeFactory;
import com.google.devtools.depan.maven.graph.ArtifactElement;
import com.google.devtools.depan.maven.graph.MavenElementDispatcher;
import com.google.devtools.depan.maven.graph.PropertyElement;
import com.google.devtools.depan.model.Element;
import com.google.devtools.depan.model.ElementTransformer;

/**
 * Provides the shapes that are drawn on the canvas.
 *
 * @author Lee Carver
 */
public class MavenShapeTransformer
    extends MavenElementDispatcher<GLEntity>
    implements ElementTransformer<GLEntity> {
  /**
   * An instance of this class used by other classes.
   */
  private static final MavenShapeTransformer INSTANCE =
      new MavenShapeTransformer();

  /**
   * Returns the singleton instance of this class.
   *
   * @return The singleton instance of this class.
   */
  public static MavenShapeTransformer getInstance() {
    return INSTANCE;
  }

  private MavenShapeTransformer() {
    // prevent instantiation by others
  }

  /**
   * Returns the {@link GLEntity} (shape) for the given element.
   *
   * @param element The element whose associated shape is requested.
   * @return {@link GLEntity} object associated with {@link ArtifactElement}s.
   */
  @Override
  public GLEntity match(ArtifactElement element) {
    return ShapeFactory.createRoundedRectangle();
  }

  /**
   * Returns the {@link GLEntity} (shape) for the given element.
   *
   * @param element The element whose associated shape is requested.
   * @return {@link GLEntity} object associated with {@link ArtifactElement}s.
   */
  @Override
  public GLEntity match(PropertyElement element) {
    return ShapeFactory.createEllipse();
  }

  /**
   * Returns the {@link GLEntity} (shape) for the given element.
   *
   * @param element The element whose associated shape is requested.
   * @return {@link GLEntity} object associated with given {@link Element}.
   */
  @Override
  public GLEntity transform(Element element) {
    return match(element);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Web.Hosting;

namespace BryanPorter.Web.VirtualFS
{
    public class CombinedPreferentialData
        : IVFSData
    {
        private readonly IVFSData m_virtualData;
        private readonly IVFSData m_physicalData;
        private readonly FileSystemPrecedence m_precedence;

        public CombinedPreferentialData(IVFSData virtualData, IVFSData physicalData, FileSystemPrecedence precedence)
        {
            m_virtualData = virtualData;
            m_physicalData = physicalData;

            m_virtualData.ParentRepository = this;
            m_physicalData.ParentRepository = this;

            m_precedence = precedence;
        }

        private static void OrderAssignment<T>(Func<T> first, Func<T> second, Func<T> physical, Func<T> virt, FileSystemPrecedence precedence)
        {
            if (precedence == FileSystemPrecedence.Virtual)
            {
                first = virt;
                second = physical;
            }
            else
            {
                first = physical;
                second = virt;
            }
        }

        private static T ExecuteInOrder<T>(Func<T> phys, Func<T> virt, FileSystemPrecedence precedence, Func<T, bool> predicate)
        {
            Func<T> first = null, second = null;

            OrderAssignment(first, second, phys, virt, precedence);

            var firstResult = first();

            if (predicate(firstResult))
                return firstResult;

            var secondResult = second();

            if (predicate(secondResult))
                return secondResult;

            Debug.Assert(false, "Unreachable code... reached. Snap!");
            throw new InvalidOperationException();
        }

        private static T ExecuteInOrder<T>(Func<T> phys, Func<T> virt, FileSystemPrecedence precedence, Func<T, T, T> processor)
        {
            Func<T> first = null, second = null;
            OrderAssignment(first, second, phys, virt, precedence);

            var firstResult = first();
            var secondResult = second();

            return processor(firstResult, secondResult);
        }

        public bool FileExists(string virtualPath)
        {
            Func<bool> physicalExists = () => (m_physicalData != null && m_physicalData.FileExists(virtualPath));
            Func<bool> virtualExists = () => (m_virtualData != null && m_virtualData.FileExists(virtualPath));

            return ExecuteInOrder(physicalExists, virtualExists, m_precedence, (b) => b);
        }

        public bool DirectoryExists(string virtualPath)
        {
            Func<bool> physicalExists = () => (m_physicalData != null && m_physicalData.DirectoryExists(virtualPath));
            Func<bool> virtualExists = () => (m_virtualData != null && m_virtualData.DirectoryExists(virtualPath));

            return ExecuteInOrder(physicalExists, virtualExists, m_precedence, (b) => b);
        }

        private static IEnumerable<T> GetThings<T>(string virtualPath, Func<IEnumerable<T>> phys, Func<IEnumerable<T>> virt, FileSystemPrecedence precedence)
            where T : VirtualFileBase
        {
            return ExecuteInOrder(phys, virt, precedence, (fresult, sresult) => { return fresult.Union(sresult, new VirtualFileComparer<T>()); });
        }

        public IEnumerable<VirtualFileBase> GetChildren(string virtualPath)
        {
            Func<IEnumerable<VirtualFileBase>> phys = () => (m_physicalData != null ? m_physicalData.GetChildren(virtualPath) : null);
            Func<IEnumerable<VirtualFileBase>> virt = () => (m_virtualData != null ? m_virtualData.GetChildren(virtualPath) : null);

            // Programmers are lazy. :)
            return GetThings<VirtualFileBase>(virtualPath, phys, virt, m_precedence);
        }

        public IEnumerable<VirtualFileSystemFile> GetFiles(string virtualPath)
        {
            Func<IEnumerable<VirtualFileSystemFile>> phys = () => (m_physicalData != null ? m_physicalData.GetFiles(virtualPath) : null);
            Func<IEnumerable<VirtualFileSystemFile>> virt = () => (m_virtualData != null ? m_virtualData.GetFiles(virtualPath) : null);

            return GetThings<VirtualFileSystemFile>(virtualPath, phys, virt, m_precedence);
        }

        public IEnumerable<VirtualFileSystemDirectory> GetDirectories(string virtualPath)
        {
            Func<IEnumerable<VirtualFileSystemDirectory>> phys = () => { return (m_physicalData != null ? m_physicalData.GetDirectories(virtualPath) : null); };
            Func<IEnumerable<VirtualFileSystemDirectory>> virt = () => { return (m_virtualData != null ? m_virtualData.GetDirectories(virtualPath) : null); };

            return GetThings<VirtualFileSystemDirectory>(virtualPath, phys, virt, m_precedence);
        }

        public byte[] GetFileContents(string virtualPath)
        {
            Func<byte[]> phys = () => { return (m_physicalData != null ? m_physicalData.GetFileContents(virtualPath) : null); };
            Func<byte[]> virt = () => { return (m_virtualData != null ? m_virtualData.GetFileContents(virtualPath) : null); };

            return ExecuteInOrder(phys, virt, m_precedence, (result) => { if (result == null) { return false; } return true; });
        }

        public VirtualFileSystemDirectory GetDirectory(string virtualPath)
        {
            Func<VirtualFileSystemDirectory> phys = () => { return (m_physicalData != null ? m_physicalData.GetDirectory(virtualPath) : null); };
            Func<VirtualFileSystemDirectory> virt = () => { return (m_virtualData != null ? m_virtualData.GetDirectory(virtualPath) : null); };

            return ExecuteInOrder(phys, virt, m_precedence, (result) => { if (result == null) { return false; } return true; });
        }

        public VirtualFileSystemFile GetFile(string virtualPath)
        {
            Func<VirtualFileSystemFile> phys = () => { return (m_physicalData != null ? m_physicalData.GetFile(virtualPath) : null); };
            Func<VirtualFileSystemFile> virt = () => { return (m_virtualData != null ? m_virtualData.GetFile(virtualPath) : null); };

            return ExecuteInOrder(phys, virt, m_precedence, (result) => { if (result == null) { return false; } return true; });
        }

        public IVFSData ParentRepository
        {
            get { return this; }
            set { }
        }

        private class VirtualFileComparer<T>
            : IEqualityComparer<T> where T : VirtualFileBase
        {
            public bool Equals(T x, T y)
            {
                return x.Name == y.Name;
            }

            public int GetHashCode(T obj)
            {
                return obj.GetHashCode();
            }
        }
    }
}


text:
require "rails_helper"

RSpec.feature "Project managers can edit existing projects" do
  let(:user) { FactoryGirl.create(:user) }
  let(:project) { FactoryGirl.create(:project, name: "Sublime Text 3") }

  before do
    login_as(user)
    assign_role!(user, :manager, project)

    visit "/"
    click_link "Sublime Text 3"
    click_link "Edit Project"
  end

  scenario "with valid attributes" do
    fill_in "project[name]", with: "Sublime Text 4 beta"
    click_button "Update Project"

    expect(page).to have_content "Project has been updated."
    expect(page).to have_content "Sublime Text 4 beta"
  end

  scenario "when providing invalid attributes" do
    fill_in "project[name]", with: ""
    click_button "Update Project"

    expect(page).to have_content "Project has not been updated."
  end
end


text:
This step must be done after [having copied the dataset to your Azure subscription](GetTheData.md)

The database is available as a blob in your Azure storage account, at /lvdata/crmsqldb. It is a .bacpac file.

In order to create a database from that bacpac file, there are several steps:
- create an empty sql database and its server
- from the server, import the bacpac as a new sql database in the server
- drop the first database that you don't need anymore

do the following:

go to [http://portal.azure.com](http://portal.azure.com)

Choose, New, Data + Storage, SQL Database

![](sqldatabase/1.png)

then, you can fill the wizzard with the following values (replace values in *italic* by your own values, some of them like the cluster name must be globally unique).

- Name: *mydream34afac*
- Server:
	- Create a new server:
		- Server Name: *mydreamsrv34*
		- Server admin login: *john*
		- Password: *TauTheaux001!*
		- Confirm password: *TauTheaux001!*
		- Location: North Europe
		- Create V12 server (Lates update): Yes *(NB, if you get an error, you can try with No)*
		- Allow azure services to access services: checked
	- Select source: Blank database
	- Pricing Tier: *Standard S3*
	- Optional Configuration: (leave default)
	- Resource Group: (leave default)
	- Subscription: *(choose the ubscription or leave default value)*

![](sqldatabase/2.png)

Find the server in the portal, and choose the import option:

Browse All, SQL Servers, *mydreamsrv34*, Import Database

![](sqldatabase/3.png)

Import Database:

- Storage: (Find the .bacpac blob in the blob storage account)
![](sqldatabase/4.png)
- Pricing Tier: *S0* (you can change afterwards if you need a faster database)
- DATABASE NAME: *mydream34*
- Server admin login: *john*
- Password: *TauTheaux001!*

![](sqldatabase/5.png)

select the **first** database you created, and delete it (don't delete the server nor the database you just imported):

![](sqldatabase/6.png)

Add your client IP address to the firewall, as well as other IP ranges you may need:

![](sqldatabase/7.png)

Then you can access the database from any SQL Server client tool. For instance, you can download a free version of SQL Server Management Studio in SQL Server Express product. The link is available from the portal:

![](sqldatabase/8.png)

If you don't have a Windows client, you can create a Windows VM in Azure.

Once installed, you can connect

![](sqldatabase/9.png)

![](sqldatabase/10.png)

NB: while doing this, you may see that the database is still importing its data from the bacpac file.

To know, you can check wether the number or records in each table is still raising, you can also see resource utilization, and check your notifications.

![](sqldatabase/11.png)

After the import is complete, you should get those numbers:

![](sqldatabase/12.png)

the script is

```
select 'Client', count(*) from Client
union all
select 'Segmentation', count(*) from Segmentation
union all
select 'Transactions', count(*) from Transactions
union all
select 'Voice', count(*) from Voice
```


text:
package eu.monnetproject.lemon.liam.impl;

import eu.monnetproject.lemon.LemonFactory;
import eu.monnetproject.lemon.impl.LemonSerializerImpl;
import eu.monnetproject.lemon.liam.*;
import eu.monnetproject.lemon.model.LexicalEntry;
import eu.monnetproject.lemon.model.LexicalForm;
import eu.monnetproject.lemon.model.MorphPattern;
import eu.monnetproject.lemon.model.MorphTransform;
import eu.monnetproject.lemon.model.Property;
import eu.monnetproject.lemon.model.PropertyValue;
import eu.monnetproject.lemon.model.Prototype;
import eu.monnetproject.lemon.model.Text;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author John McCrae
 */
public class MorphologyEngineImpl implements MorphologyEngine {

    private LexicalForm asForm(String value, Prototype prototype) {
        final LexicalForm form = new VirtualForm();
        form.setWrittenRep(new Text(value, null));
        for (Map.Entry<Property, Collection<PropertyValue>> props : prototype.getPropertys().entrySet()) {
            for (PropertyValue pv : props.getValue()) {
                form.addProperty(props.getKey(), pv);
            }
        }
        return form;
    }

    private LexicalForm applyRule(TransformProtoype transform, LexicalForm form) throws MorphologyApplicationException {
        for (String rule : transform.getTransform().getRules()) {
            if (rule.contains("/")) {
                final String[] split = rule.split("/");
                if (split.length != 2) {
                    throw new MorphologyApplicationException("Rule contains more than one /");
                }
                final String[] lrhs = realizeRegexes(split[0], split[1]);
                final String lhs = lrhs[0];
                if (form.getWrittenRep().value.matches(lhs)) {
                    final String rhs = lrhs[1];
                    return asForm(form.getWrittenRep().value.replaceAll("^" + lhs + "$", rhs), transform.getPrototype());
                } else {
                    //log.warning(form.getWrittenRep().value + " does not match " + lhs);
                }
            }
        }
        for (String rule : transform.getTransform().getRules()) {
            if (!rule.contains("/")) {
                if (rule.indexOf("~") < 0) {
                    throw new MorphologyApplicationException("RHS does not contain a ~");
                }
                final String rhs = rule.replaceAll("~", "\\$1");
                return asForm(form.getWrittenRep().value.replaceAll("^(.*)$", rhs), transform.getPrototype());
            }
        }
        throw new MorphologyApplicationException("Could not apply a rule");
    }

    private boolean canApplyRule(TransformProtoype transform, LexicalForm form) throws MorphologyApplicationException {
        for (String rule : transform.getTransform().getRules()) {
            if (rule.contains("/")) {
                final String[] split = rule.split("/");
                if (split.length != 2) {
                    throw new MorphologyApplicationException("Rule contains more than one /");
                }
                final String[] lrhs = realizeRegexes(split[0], split[1]);
                final String lhs = lrhs[0];
                if (form.getWrittenRep().value.matches(lhs)) {
                    return true;
                }
            } else {
                return true;
            }
        }
        return false;
    }

    private String[] realizeRegexes(String lhs, String rhs) {
        if (lhs.indexOf("~") < 0) {
            throw new MorphologyApplicationException("LHS does not contain a ~");
        }
        if (rhs.indexOf("~") < 0) {
            throw new MorphologyApplicationException("RHS does not contain a ~");
        }
        int leftBracks = 1;
        for (int i = 0; i < lhs.indexOf("~"); i++) {
            if (lhs.charAt(i) == '(' && lhs.charAt(i + 1) != '?') {
                leftBracks++;
            }
        }
        int highestIdx = 0;
        final Matcher matcher = Pattern.compile("\\$(\\d+)").matcher(rhs);
        while (matcher.find()) {
            int idx = Integer.parseInt(matcher.group(1));
            if (idx > highestIdx) {
                highestIdx = idx;
            }
        }
        for (int i = leftBracks; i <= highestIdx; i++) {
            rhs = rhs.replaceAll("\\$"+i, "\\$"+(i+1));
        }
        rhs = rhs.replaceAll("~", "\\$" + leftBracks);
        lhs = lhs.replaceAll("~", "(.*?)");
        return new String[] { lhs,rhs };
    }

    private TransformProtoype findGenerator(MorphPattern mp, Map<Property, Collection<PropertyValue>> map) {
        for (MorphTransform transform : mp.getTransforms()) {
            PROTOS:
            for (Prototype generation : transform.getGenerates()) {
                for (Map.Entry<Property, Collection<PropertyValue>> propEntry : map.entrySet()) {
                    final Collection<PropertyValue> propVal = generation.getProperty(propEntry.getKey());
                    for (PropertyValue pv : propEntry.getValue()) {
                        if (!propVal.contains(pv)) {
                            continue PROTOS;
                        }
                    }
                }
                return new TransformProtoype(transform, generation);
            }
        }
        return null;
    }

    private LexicalForm findForm(LexicalEntry entry, MorphTransform transform) {
        if (transform.getOnStem() == null) {
            return entry.getCanonicalForm();
        }
        FORMS:
        for (LexicalForm form : entry.getForms()) {
            for (Map.Entry<Property, Collection<PropertyValue>> propEntry : transform.getOnStem().getPropertys().entrySet()) {
                final Collection<PropertyValue> propVal = form.getProperty(propEntry.getKey());
                for (PropertyValue pv : propEntry.getValue()) {
                    if (!propVal.contains(pv)) {
                        continue FORMS;
                    }
                }
            }
            return form;
        }
        return null;
    }

    public LexicalForm generate(LexicalEntry entry, MorphPattern mp, Map<Property, Collection<PropertyValue>> map) {
        // Find a suitable generator
        final TransformProtoype transform = findGenerator(mp, map);
        // Try compound generation
        if (transform == null) {
            LexicalForm result = compoundGeneration(entry, mp, map);
            if (result != null) {
                return result;
            }
        }
        if (transform == null) {
            throw new MorphologyApplicationException("No suitable transform for given prop values");
        }
        // Find stem
        LexicalForm form = findForm(entry, transform.getTransform());
        if (form == null) {
            throw new MorphologyApplicationException("No suitable form for given prop value");
        }
        // Apply to stem
        final LexicalForm result = applyRule(transform, form);
        if (result == null) {
            throw new MorphologyApplicationException("Could not find suitable rule to apply");
        } else {
            return result;
        }
    }

    private LexicalForm compoundGeneration(LexicalEntry entry, MorphPattern mp, Map<Property, Collection<PropertyValue>> map) {
        for (MorphTransform transform : mp.getTransforms()) {
            LexicalForm form = findForm(entry, transform);
            if (form != null) {
                for (Prototype generation : transform.getGenerates()) {
                    for (Map.Entry<Property, Collection<PropertyValue>> props : generation.getPropertys().entrySet()) {
                        for (PropertyValue pv : props.getValue()) {
                            if (map.containsKey(props.getKey()) && map.get(props.getKey()).contains(pv)) {
                                final LexicalForm form2 = compoundGeneration(entry, mp, map, new TransformProtoype(transform, generation), form);
                                if (satisfies(form2, map)) {
                                    return form2;
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private boolean satisfies(LexicalForm form, Map<Property, Collection<PropertyValue>> map) {
        if (form == null) {
            return false;
        }
        for (Map.Entry<Property, Collection<PropertyValue>> props : map.entrySet()) {
            if (form.getProperty(props.getKey()) == null || !form.getProperty(props.getKey()).containsAll(props.getValue())) {
                return false;
            }
        }
        return true;
    }

    private LexicalForm compoundGeneration(LexicalEntry entry, MorphPattern mp, Map<Property, Collection<PropertyValue>> map, TransformProtoype transform, LexicalForm form) {
        if(!canApplyRule(transform, form))  {
            return null;
        }
        final LexicalForm newForm = applyRule(transform, form);
        if (newForm != null) {
            for (Map.Entry<Property, Collection<PropertyValue>> props : form.getPropertys().entrySet()) {
                for (PropertyValue pv : props.getValue()) {
                    newForm.addProperty(props.getKey(), pv);
                }
            }
            if (satisfies(newForm, map)) {
                return newForm;
            }

            for (MorphTransform next : transform.getTransform().getNextTransforms()) {
                for (Prototype generation : next.getGenerates()) {
                    for (Map.Entry<Property, Collection<PropertyValue>> props : generation.getPropertys().entrySet()) {
                        for (PropertyValue pv : props.getValue()) {
                            if (map.get(props.getKey()).contains(pv)) {
                                final LexicalForm form2 = compoundGeneration(entry, mp, map, new TransformProtoype(next, generation), newForm);
                                if (satisfies(form2, map)) {
                                    return form2;
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private static class TransformProtoype {

        private final MorphTransform transform;
        private final Prototype prototype;

        public TransformProtoype(MorphTransform transform, Prototype prototype) {
            this.transform = transform;
            this.prototype = prototype;
        }

        public Prototype getPrototype() {
            return prototype;
        }

        public MorphTransform getTransform() {
            return transform;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final TransformProtoype other = (TransformProtoype) obj;
            if (this.transform != other.transform && (this.transform == null || !this.transform.equals(other.transform))) {
                return false;
            }
            if (this.prototype != other.prototype && (this.prototype == null || !this.prototype.equals(other.prototype))) {
                return false;
            }
            return true;
        }

        @Override
        public int hashCode() {
            int hash = 3;
            hash = 79 * hash + (this.transform != null ? this.transform.hashCode() : 0);
            hash = 79 * hash + (this.prototype != null ? this.prototype.hashCode() : 0);
            return hash;
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>My awesome project · Len Kiefer</title>
        <meta name="description" content="Description of my awesome project.">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="generator" content="Hugo 0.27.1" />
        <meta name="robots" content="index,follow">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="/dist/styles.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,600,700,300&subset=latin,cyrillic-ext,latin-ext,cyrillic">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                                Len Kiefer

        Blog

        Topics

        Projects

        About

        Contact

My awesome project

Description of my awesome project.

About project

Aenean ipsum justo, semper eu nisl ut, pretium tincidunt sem. Praesent et diam sit amet lacus lobortis dictum a id lacus. Quisque hendrerit sit amet turpis eu varius. Ut id lorem ac felis ultrices tincidunt. Pellentesque consequat arcu ac fringilla imperdiet. Phasellus pellentesque, sapien non pulvinar blandit, sapien ante aliquet felis, vel porttitor sapien ante in lacus. Fusce non urna aliquet, malesuada nibh vel, luctus urna. Phasellus ut lacus molestie, varius purus quis, malesuada lorem.

Install

go get -u -v github.com/spf13/hugo

Docs

https://godoc.org/github.com/spf13/hugo

                Twitter

                Facebook

                Google+

               LinkedIn

                        Len Kiefer

                    © Len Kiefer 2017 / Powered by Hugo

                    Ghostwriter theme By JollyGoodThemes
                    / Ported to Hugo By jbub (modified by Len Kiefer)


text:
namespace content {

class PowerSaveBlockerImpl::Delegate
    : public base::RefCountedThreadSafe<PowerSaveBlockerImpl::Delegate> {
 public:
  Delegate(PowerSaveBlockerType type, const std::string& reason)
      : type_(type),
        reason_(reason),
        block_id_(0) {}

  void ApplyBlock() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!chromeos::DBusThreadManager::IsInitialized()) {
      LOG(WARNING) << "DBusThreadManager not initialized";
      return;
    }

    chromeos::PowerPolicyController* controller =
        chromeos::DBusThreadManager::Get()->GetPowerPolicyController();
    switch (type_) {
      case kPowerSaveBlockPreventAppSuspension:
        block_id_ = controller->AddSuspendBlock(reason_);
        break;
      case kPowerSaveBlockPreventDisplaySleep:
        block_id_ = controller->AddScreenBlock(reason_);
        break;
      default:
        NOTREACHED() << "Unhandled block type " << type_;
    }
  }

  void RemoveBlock() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (!chromeos::DBusThreadManager::IsInitialized()) {
      LOG(WARNING) << "DBusThreadManager not initialized";
      return;
    }
    chromeos::DBusThreadManager::Get()->GetPowerPolicyController()->
        RemoveBlock(block_id_);
  }

 private:
  friend class base::RefCountedThreadSafe<Delegate>;
  virtual ~Delegate() {}

  PowerSaveBlockerType type_;
  std::string reason_;

  // ID corresponding to the block request in PowerPolicyController.
  int block_id_;

  DISALLOW_COPY_AND_ASSIGN(Delegate);
};

PowerSaveBlockerImpl::PowerSaveBlockerImpl(PowerSaveBlockerType type,
                                           const std::string& reason)
    : delegate_(new Delegate(type, reason)) {
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                          base::Bind(&Delegate::ApplyBlock, delegate_));
}

PowerSaveBlockerImpl::~PowerSaveBlockerImpl() {
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                          base::Bind(&Delegate::RemoveBlock, delegate_));
}

}  // namespace content


text:
<!DOCTYPE html>

    <title>Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="jquery.mobile-1.0.css" type="text/css" />

Jacqui's Shop

        <form method="get">

                Name:
                <input id="name" placeholder="Your Name">

                Quantity:
                <input id="quant" type="range" value="5" min="1" max="10" />

                <input type="submit" data-inline="true" value="Submit"/>

        </form>


text:
package gov.sandia.cognition.statistics;

import gov.sandia.cognition.util.CloneableSerializable;
import gov.sandia.cognition.util.NamedValue;

/**
 * Allows access to a parameter within a closed-form distribution, given by
 * the high-level String value.  For example, we can access the variance
 * of a UnivariateGaussian by attaching a DistributionParameter to "variance".
 * @param <ParameterType> Type of Parameter.
 * @param <ConditionalType>
 * Type of parameterized distribution that generates observations.
 * @author Kevin R. Dixon
 * @since 3.0
 */
public interface DistributionParameter<ParameterType,ConditionalType extends Distribution<?>>
    extends NamedValue<ParameterType>,
    CloneableSerializable
{

    /**
     * Gets the conditional distribution associated with the parameter.
     * @return
     * Conditional distribution associated with the parameter.
     */
    public ConditionalType getConditionalDistribution();

    /**
     * Sets the value of the parameter.
     * @param value
     * Parameter to set.
     */
    public void setValue(
        final ParameterType value );

}


text:
import { Component, OnInit } from '@angular/core';
import {  Router, ActivatedRoute } from '@angular/router';
import { CustomerApi, Customer } from 'client';

@Component({
    selector: 'search-result',
    template: require('./result.template.html'),
    styles: [require('./result.style.scss')],
    //directives: [...ROUTER_DIRECTIVES],
    providers: [CustomerApi]
})
export class SearchResult implements OnInit {
    constructor(private capi: CustomerApi, private router: Router, private route: ActivatedRoute) {
    }

    ngOnInit() {

    }

}


text:
<!DOCTYPE html>
<html>
	<head>
		<title>heya-async test runner</title>
		<!-- The next file is needed for Function.prototype.bind(),
		which is missing in PhantomJS (and old IE). -->
		<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/1.2.4/es5-shim.min.js"></script>
		<script src="http://requirejs.org/docs/release/2.1.5/minified/require.js"></script>
		<script>
			(function(){
				var paths = {
					domReady: "https://raw.github.com/requirejs/domReady/latest/domReady"
				};
				/*@cc_on
				if(@_jscript_version < 9){
					paths["../mini"]  = "../legacy";
					paths["dcl/mini"] = "dcl/legacy";
				}
				@*/
				require.config({
					baseUrl: ".",
					packages: [
						{name: "heya-unit",
						location: "../node_modules/heya-unit"},
						{name: "heya-ice",
						location: "../node_modules/heya-unit/node_modules/heya-ice"},
						{name: "heya-unify",
						location: "../node_modules/heya-unit/node_modules/heya-unify"}
					],
					paths: paths
				});
			})();
			require(["require", "./tests", "domReady!"], function(require){
				var test = require("./tests");
			});
		</script>
	</head>
	<body>
	</body>
</html>


text:
package com.nbdeg.unityplanner;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import com.nbdeg.unityplanner.data.Assignment;
import com.nbdeg.unityplanner.utils.Database;
import com.nbdeg.unityplanner.utils.ListAssignmentAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * A simple {@link Fragment} subclass.
 */
public class DashboardFragment extends Fragment {

    SimpleDateFormat formatter = new SimpleDateFormat("EEE, MMM d", java.util.Locale.getDefault());
    RecyclerView recyTodayView;
    RecyclerView recyTomorrowView;

    ListAssignmentAdapter tomorrowAdapter;
    ListAssignmentAdapter todayAdapter;

    TextView noTodayAssignments;
    TextView noTomorrowAssignments;

    private Paint p = new Paint();

    public DashboardFragment() {
        // Required empty public constructor
    }

    @Override
    public void onResume() {
        super.onResume();
        NavigationView navigationView = (NavigationView)getActivity().findViewById(R.id.nav_view);
        navigationView.setCheckedItem(R.id.nav_home);

        getActivity().setTitle("Dashboard");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_dashboard, container, false);

        final TextView todayTitle = (TextView) view.findViewById(R.id.dashboard_today_title);
        final TextView tomorrowTitle = (TextView) view.findViewById(R.id.dashboard_tomorrow_title);
        recyTodayView = (RecyclerView) view.findViewById(R.id.dashboard_today_list);
        recyTomorrowView = (RecyclerView) view.findViewById(R.id.dashboard_tomorrow_list);
        final ImageView todayAdd = (ImageView) view.findViewById(R.id.dashboard_today_add);
        final ImageView tomorrowAdd = (ImageView) view.findViewById(R.id.dashboard_tomorrow_add);

        noTodayAssignments = (TextView) view.findViewById(R.id.dashboard_today_none);
        noTomorrowAssignments = (TextView) view.findViewById(R.id.dashboard_tomorrow_none);

        todayTitle.setText("Due Today - " + formatter.format(new Date()));

        final Calendar tomorrowCal = Calendar.getInstance();
        tomorrowCal.add(Calendar.DATE, 1);
        tomorrowCal.set(Calendar.HOUR_OF_DAY, 23);
        tomorrowCal.set(Calendar.MINUTE, 59);
        tomorrowTitle.setText("Due Tomorrow - " + formatter.format(tomorrowCal.getTime()));

        final Calendar todayCal = Calendar.getInstance();
        todayCal.set(Calendar.HOUR_OF_DAY, 23);
        todayCal.set(Calendar.MINUTE, 59);

        final ArrayList<Assignment> todayAssignments = new ArrayList<>();
        final ArrayList<Assignment> tomorrowAssignments = new ArrayList<>();

        recyTodayView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyTomorrowView.setLayoutManager(new LinearLayoutManager(getContext()));

        Database.dueAssignmentDb.orderByChild("dueDate").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                    Assignment assignment = userSnapshot.getValue(Assignment.class);

                    if (assignment.getDueDate() < todayCal.getTimeInMillis()) {
                        todayAssignments.add(assignment);
                    } else if (assignment.getDueDate() < tomorrowCal.getTimeInMillis()) {
                        tomorrowAssignments.add(assignment);
                    }
                }

                if (!todayAssignments.isEmpty()) {
                    noTodayAssignments.setVisibility(View.GONE);
                    recyTodayView.setVisibility(View.VISIBLE);

                    todayAdapter = new ListAssignmentAdapter(todayAssignments);
                    recyTodayView.setAdapter(todayAdapter);
                }

                if (!tomorrowAssignments.isEmpty()) {
                    noTomorrowAssignments.setVisibility(View.GONE);
                    recyTomorrowView.setVisibility(View.VISIBLE);

                    tomorrowAdapter = new ListAssignmentAdapter(tomorrowAssignments);
                    recyTomorrowView.setAdapter(tomorrowAdapter);
                }

                initSwipes();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        todayAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CreateAssignment.class);
                intent.putExtra("date", todayCal.getTimeInMillis());
                startActivity(intent);
            }
        });

        tomorrowAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CreateAssignment.class);
                intent.putExtra("date", tomorrowCal.getTimeInMillis());
                startActivity(intent);
            }
        });

        return view;
    }

    private void initSwipes(){
        ItemTouchHelper.SimpleCallback todayTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();

                todayAdapter.removeAssignment(position, getContext());

                if (todayAdapter.getItemCount() == 0) {
                    noTodayAssignments.setVisibility(View.VISIBLE);
                    recyTodayView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

                Bitmap icon;
                if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {

                    View itemView = viewHolder.itemView;
                    float height = (float) itemView.getBottom() - (float) itemView.getTop();
                    float width = height / 3;

                    if (viewHolder.getAdapterPosition() != -1) {
                        Assignment assignment = todayAdapter.getItem(viewHolder.getAdapterPosition());

                        if (dX > 0) {
                            p.setColor(assignment.getDueCourse().getColor());
                            RectF background = new RectF((float) itemView.getLeft(), (float) itemView.getTop(), dX, (float) itemView.getBottom());
                            c.drawRect(background, p);
                            icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_check_white);
                            RectF icon_dest = new RectF((float) itemView.getLeft() + width, (float) itemView.getTop() + width, (float) itemView.getLeft() + 2 * width, (float) itemView.getBottom() - width);
                            c.drawBitmap(icon, null, icon_dest, p);
                        }
                    }
                }
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        };

        ItemTouchHelper.SimpleCallback tomorrowTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();

                tomorrowAdapter.removeAssignment(position, getContext());
                if (tomorrowAdapter.getItemCount() == 0) {
                    noTomorrowAssignments.setVisibility(View.VISIBLE);
                    recyTomorrowView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

                Bitmap icon;
                if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {

                    View itemView = viewHolder.itemView;
                    float height = (float) itemView.getBottom() - (float) itemView.getTop();
                    float width = height / 3;

                    if (viewHolder.getAdapterPosition() != -1) {
                        Assignment assignment = tomorrowAdapter.getItem(viewHolder.getAdapterPosition());

                        if (dX > 0) {
                            p.setColor(assignment.getDueCourse().getColor());
                            RectF background = new RectF((float) itemView.getLeft(), (float) itemView.getTop(), dX, (float) itemView.getBottom());
                            c.drawRect(background, p);
                            icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_check_white);
                            RectF icon_dest = new RectF((float) itemView.getLeft() + width, (float) itemView.getTop() + width, (float) itemView.getLeft() + 2 * width, (float) itemView.getBottom() - width);
                            c.drawBitmap(icon, null, icon_dest, p);
                        }
                    }
                }
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        };

        new ItemTouchHelper(todayTouchCallback).attachToRecyclerView(recyTodayView);
        new ItemTouchHelper(tomorrowTouchCallback).attachToRecyclerView(recyTomorrowView);
    }
}


text:
package fr.univnantes.lina.uima.tkregex.model.automata;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import fr.univnantes.lina.uima.tkregex.model.matchers.AnnotationMatcher;
import fr.univnantes.lina.uima.tkregex.model.matchers.LabelledAnnotation;
import org.apache.uima.cas.text.AnnotationFS;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;

public class Automaton implements Cloneable {

	private State initState;
	private TreeSet<State> acceptingStates;
	private TreeSet<State> states;

	Automaton(State initState,
			Set<State> acceptingStates, Set<State> states) {
		this();
		this.initState = initState;
		if(!states.contains(initState))
			throw new IllegalStateException("The states set must contains the init state.");
		if(!states.containsAll(acceptingStates))
			throw new IllegalStateException("The states set must contains all the accepting states.");
		this.acceptingStates = new TreeSet<State>(acceptingStates);
		this.states = new TreeSet<State>(states);
	}

	Automaton() {
		super();
		this.acceptingStates = new TreeSet<State>();
		this.states = new TreeSet<State>();
	}

	boolean addAllState(Collection<? extends State> arg0) {
		return acceptingStates.addAll(arg0);
	}

	public Set<State> getAcceptingStates() {
		return ImmutableSet.copyOf(acceptingStates);
	}

	public Set<State> getStates() {
		return ImmutableSet.copyOf(states);
	}

	void setInitState(State initState) {
		this.initState = initState;
	}

//	public void setName(String name) {
//		this.name = name;
//	}

	@Override
	public String toString() {
		String nullName = "unnamed " + System.identityHashCode(this);
//		return "Automaton " + (this.name == null ? nullName : this.name) + toFullString();
		return "Automaton " + nullName;
	}

	public String toFullString() {
		String str = "";
		for(State s: this.states) {
			str+="\n";
			str+=s.toString();
			if(this.initState.equals(s))
				str+=" INITIAL";
			if(this.acceptingStates.contains(s))
				str+=" ACCEPTING";
			str+=s.transitionsToString();
		}
		return str;
	}

//	public String getName() {
//		return name;
//	}

	public State getInitState() {
		return initState;
	}

	void addAcceptingState(State s) {
		this.acceptingStates.add(s);
	}

	public Automaton deepClone() {
		Automaton automataClone = new Automaton();
		Map<State, State> clones = Maps.newHashMap();

		// clone states
		for(State s: this.states) {
			State clone = new State();
			clones.put(s, clone);
		}

		// clone transitions
		for(State s: this.states) {
			State clone = clones.get(s);
			for(Transition t:s.getTransitions()) {
				State toState = clones.get(t.getToState());
				Transition nt;
				if(t.isEpsilon()) {
					nt = new EpsilonTransition();
				} else {
					nt = new Transition();
					nt.setMatcher(t.getMatcher());
				}
				nt.setFromState(clone);
				nt.setToState(toState);
				clone.addTransition(nt);
			}
		}

		automataClone.initState = clones.get(this.initState);

		for(State state:this.states)
			automataClone.states.add(clones.get(state));

		for(State acceptingState:this.acceptingStates) {
			State state = clones.get(acceptingState);
			automataClone.acceptingStates.add(state);
		}

		return automataClone;
	}

	private Map<State, Boolean> acceptingStatesCache = Maps.newTreeMap();

	public boolean isAccepting(State state) {
		Boolean accept = acceptingStatesCache.get(state);
		if(accept == null ) {
			accept = computeAcceptingState(state);
			acceptingStatesCache.put(state,accept);
		}
		return accept;
	}

	private boolean computeAcceptingState(State s) {
		List<State> epsilonClosure = s.getEpsilonClosure();
		for(State st: epsilonClosure) {
			if(this.acceptingStates.contains(st))
				return true;
		}
		return false;
	}

	public boolean matchesEmptySequence() {
		return isAccepting(this.initState);
	}

}


text:
var map;
function loadMap(bounds) { // bounds is optional
  // Create a map in the "map" div, set the view to a given place and zoom
  map = L.map('map', { zoomControl: true, scrollWheelZoom: false });
  map.on('focus', function() { map.scrollWheelZoom.enable(); });
  map.on('blur', function() { map.scrollWheelZoom.disable(); });
  if(bounds === undefined){
    map.setView([36.778259, -119.417931], 3);
  }else{
    map.fitBounds(bounds);
  }

  mapLink = 'OpenStreetMap';
  map.zoomControl.setPosition('bottomright');
    // add an OpenStreetMap tile layer
      L.tileLayer(
        'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}{retina}.png', {
          attribution: '© OpenStreetMap contributors, © CartoDB',
          worldCopyJump: true,
          retina: '@2x',
          detectRetina: false
        }).addTo(map);
  // -------------------------------- //

  // MAPZEN autocomplete search and save to db
  mapzen();

  // Get Point BBox and Place Coordinates from db and load on map
  var resource_id = $.urlParam('resource_id');
  getAndLoadGeoPoint(resource_id);
  getAndLoadGeoBox(resource_id);
  getAndLoadGeoPlace(resource_id);

  //LEAFLET DRAW PLUGIN
  leafletDraw();
};

$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}


text:
package com.dtodorov.androlib.services;

public interface IPermissionService {
    void obtainPermission(String permission, String explanation);
    void obtainPermissionIfNotGranted(String permission, String explanation);

    Status getPermissionStatus(String permission);
    boolean isPermissionGranted(String permission);

    public enum Status {
        Granted,
        Denied
    }
}


text:
package io.reactivex.internal.operators.flowable;

import org.reactivestreams.*;

import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Predicate;
import io.reactivex.internal.fuseable.FuseToFlowable;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
import io.reactivex.plugins.RxJavaPlugins;

public final class FlowableAllSingle<T> extends Single<Boolean> implements FuseToFlowable<Boolean> {

    final Flowable<T> source;

    final Predicate<? super T> predicate;

    public FlowableAllSingle(Flowable<T> source, Predicate<? super T> predicate) {
        this.source = source;
        this.predicate = predicate;
    }

    @Override
    protected void subscribeActual(SingleObserver<? super Boolean> observer) {
        source.subscribe(new AllSubscriber<T>(observer, predicate));
    }

    @Override
    public Flowable<Boolean> fuseToFlowable() {
        return RxJavaPlugins.onAssembly(new FlowableAll<T>(source, predicate));
    }

    static final class AllSubscriber<T> implements FlowableSubscriber<T>, Disposable {

        final SingleObserver<? super Boolean> downstream;

        final Predicate<? super T> predicate;

        Subscription upstream;

        boolean done;

        AllSubscriber(SingleObserver<? super Boolean> actual, Predicate<? super T> predicate) {
            this.downstream = actual;
            this.predicate = predicate;
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validate(this.upstream, s)) {
                this.upstream = s;
                downstream.onSubscribe(this);
                s.request(Long.MAX_VALUE);
            }
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }
            boolean b;
            try {
                b = predicate.test(t);
            } catch (Throwable e) {
                Exceptions.throwIfFatal(e);
                upstream.cancel();
                upstream = SubscriptionHelper.CANCELLED;
                onError(e);
                return;
            }
            if (!b) {
                done = true;
                upstream.cancel();
                upstream = SubscriptionHelper.CANCELLED;
                downstream.onSuccess(false);
            }
        }

        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            done = true;
            upstream = SubscriptionHelper.CANCELLED;
            downstream.onError(t);
        }

        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            upstream = SubscriptionHelper.CANCELLED;

            downstream.onSuccess(true);
        }

        @Override
        public void dispose() {
            upstream.cancel();
            upstream = SubscriptionHelper.CANCELLED;
        }

        @Override
        public boolean isDisposed() {
            return upstream == SubscriptionHelper.CANCELLED;
        }
    }
}


text:
@implementation MGTagTextField

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.placeholder = @"多个标签用逗号或换行隔开";
        [self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
        self.height = MGTagH;
        self.font = MGTagFont;
    }
    return self;
}

// 也能在这个方法中监听键盘输入,如"换行"
- (void)insertText:(NSString *)text
{
    [super insertText:text];
//    MGLog(@"-%d-", [text isEqualToString:@"\n"]);
}

- (void)deleteBackward
{
    // 一旦block有值就调用
    !self.deleteBlock ? : self.deleteBlock();

    [super deleteBackward];

//    MGLogFunc;
}

@end