text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Street Fighter Wiki</title>
    <link rel="stylesheet" href="styles/styles.css">

Início

Noticias

Ficha Técnica

Sobre

Street Fighter

Sumário

O jogo

História

Jogos da série

Street Fighter

Street Fighter II

Street Fighter III

Street Fighter Alpha

O jogo

Street Fighter é uma popular série de jogos de luta na qual o jogador controla lutadores de diversas partes do mundo, cada qual com seus golpes especiais. A série é propriedade da empresa de jogos Capcom e teve seu primeiro jogo lançado em agosto de 1987. Algumas séries são integradas à SF, como     por exemplo Final Fight e Slam Masters.

História

O primeiro jogo de luta foi Heavyweight Champ, lançado pela SEGA para os arcades em 1976. O próximo só apareceria vários anos depois, em 1984, com o jogo Karate Champ da DataEast. Este é considerado o primeiro jogo de luta para dois jogadores, apresentando dois controles. Seguindo seus passos, a     Konami lançou Yie-Ar Kung Fu, em 1985 com gráficos impressionantes (para a época) e cheio de detalhes nos cenários. Vendo o sucesso de ambos os games, a Capcom decidiu lançar seu próprio jogo que tivesse características de ambos os jogos. Assim nasceu Street Fighter

Jogos da Série

Street Fighter

Street Fighter fez pouco impacto em seu lançamento. Porém seus controles eram inovadores, com 1 joystick e 2 botões hidráulicos, que dependendo da força davam potência diferente ao golpe. Como geralmente se batia com muita força, foram trocados pelos 6 botões que se tornaram tradição na série. O     game acompanhava Ryu ou Ken , duelando com dez lutadores de 5 países. O game introduziu os golpes especiais da Punho Ondulante, que ficariam com Ryu e Ken pelo resto da série. Sagat, ainda sem a cicatriz no peito, é o chefe final do jogo. Os demais personagens são Eagle, Lee, Joe, Gen, Geki, Retsu,     Adon, Mike e Birdie.

Street Fighter II

O jogo também inovou a forçar o protagonista viajar por diferentes países através de cenários locais, como os elefantes na fase do Dhalsim, elementos japoneses nos estágios de E. Honda e Ryu (mostrando cenários tipicamente orientais) e inclusive a selva amazônica brasileira na fase relativa ao     Blanka.

Street Fighter III

Street Fighter III fora lançado em 1997. Não teve tanto sucesso quanto o II. Um dos motivos atribuídos foi pelo advento de jogos de luta em 3D como Tekken, e a ausência de muitos personagens famosos do jogo anterior.

Street Fighter Alpha

Street Fighter Alpha é uma subsérie, com três games e uma compilação por hora.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>edu.ucla.wise.admin.view</title>
<meta name="date" content="2014-05-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

edu.ucla.wise.admin.view

Classes

SurveyHealthInformation

SurveyInformation

ToolView

redpajama_set_name: RedPajamaGithub


text:
package org.spiffyui.spsample.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * This is the hosted mode documentation panel
 *
 */
public class HostedModePanel extends HTMLPanel
{
    private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);

    /**
     * Creates a new panel
     */
    public HostedModePanel()
    {
        super("div", STRINGS.HostedModePanel_html());

        getElement().setId("hostedModePanel");

        RootPanel.get("mainContent").add(this);

        setVisible(false);

        Index.addToc(this);
    }
}


text:
package io.unravelling.ferguson.model;

/**
 * Model for a queue.
 * @author Tiago Veiga Lazaro
 * @version 1.0.0
 * @since 1.0.0
 */
public class Queue extends Destination {

  /**
   * Defines if the queue works in exclusive mode (only one consumer).
   */
  private boolean isExclusive;

  /**
   * Indicates if the queue is routed.
   */
  private boolean isRouted;

  /**
   * Number of receivers in this queue.
   */
  private int receiverCount;

  /**
   * Max number of attempts of redelivery in case of failure.
   */
  private int maxRedelivery;

  /**
   * Defines if the queue works in exclusive mode (only one consumer).
   */
  public boolean isExclusive() {
    return isExclusive;
  }

  public void setExclusive(boolean exclusive) {
    isExclusive = exclusive;
  }

  /**
   * Indicates if the queue is routed.
   */
  public boolean isRouted() {
    return isRouted;
  }

  public void setRouted(boolean routed) {
    isRouted = routed;
  }

  /**
   * Number of receivers in this queue.
   */
  public int getReceiverCount() {
    return receiverCount;
  }

  public void setReceiverCount(int receiverCount) {
    this.receiverCount = receiverCount;
  }

  /**
   * Max number of attempts of redelivery in case of failure.
   */
  public int getMaxRedelivery() {
    return maxRedelivery;
  }

  public void setMaxRedelivery(int maxRedelivery) {
    this.maxRedelivery = maxRedelivery;
  }
}


text:
require 'test_helper'

class ForkThisTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, ForkThis
  end
end


text:
using System;
using System.Collections.Generic;
using SimplCommerce.Module.Core.Models;

namespace SimplCommerce.Module.Catalog.Models
{
    public class Product : Content
    {
        public string ShortDescription { get; set; }

        public string Description { get; set; }

        public string Specification { get; set; }

        public decimal Price { get; set; }

        public decimal? OldPrice { get; set; }

        public decimal? SpecialPrice { get; set; }

        public DateTimeOffset? SpecialPriceStart { get; set; }

        public DateTimeOffset? SpecialPriceEnd { get; set; }

        public bool HasOptions { get; set; }

        public bool IsVisibleIndividually { get; set; }

        public bool IsFeatured { get; set; }

        public bool IsCallForPricing { get; set; }

        public bool IsAllowToOrder { get; set; }

        public int? StockQuantity { get; set; }

        public string Sku { get; set; }

        public string NormalizedName { get; set; }

        public int DisplayOrder { get; set; }

        public long? VendorId { get; set; }

        public Media ThumbnailImage { get; set; }

        public IList<ProductMedia> Medias { get; protected set; } = new List<ProductMedia>();

        public IList<ProductLink> ProductLinks { get; protected set; } = new List<ProductLink>();

        public IList<ProductLink> LinkedProductLinks { get; protected set; } = new List<ProductLink>();

        public IList<ProductAttributeValue> AttributeValues { get; protected set; } = new List<ProductAttributeValue>();

        public IList<ProductOptionValue> OptionValues { get; protected set; } = new List<ProductOptionValue>();

        public IList<ProductCategory> Categories { get; protected set; } = new List<ProductCategory>();

        public int ReviewsCount { get; set; }

        public double? RatingAverage { get; set; }

        public long? BrandId { get; set; }

        public Brand Brand { get; set; }

        public void AddCategory(ProductCategory category)
        {
            category.Product = this;
            Categories.Add(category);
        }

        public void AddMedia(ProductMedia media)
        {
            media.Product = this;
            Medias.Add(media);
        }

        public void RemoveMedia(ProductMedia media)
        {
            media.Product = null;
            Medias.Remove(media);
        }

        public void AddAttributeValue(ProductAttributeValue attributeValue)
        {
            attributeValue.Product = this;
            AttributeValues.Add(attributeValue);
        }

        public void AddOptionValue(ProductOptionValue optionValue)
        {
            optionValue.Product = this;
            OptionValues.Add(optionValue);
        }

        public void AddProductLinks(ProductLink productLink)
        {
            productLink.Product = this;
            ProductLinks.Add(productLink);
        }

        public virtual IList<ProductOptionCombination> OptionCombinations { get; protected set; } = new List<ProductOptionCombination>();

        public void AddOptionCombination(ProductOptionCombination combination)
        {
            combination.Product = this;
            OptionCombinations.Add(combination);
        }

        public Product Clone()
        {
            var product = new Product();
            product.Name = Name;
            product.MetaTitle = MetaTitle;
            product.MetaKeywords = MetaKeywords;
            product.MetaDescription = MetaDescription;
            product.ShortDescription = ShortDescription;
            product.Description = Description;
            product.Specification = Specification;
            product.IsPublished = true;
            product.PublishedOn = DateTimeOffset.Now;
            product.Price = Price;
            product.OldPrice = OldPrice;
            product.IsAllowToOrder = IsAllowToOrder;
            product.IsCallForPricing = IsCallForPricing;
            product.StockQuantity = StockQuantity;
            product.BrandId = BrandId;
            product.VendorId = VendorId;

            foreach (var attribute in AttributeValues)
            {
                product.AddAttributeValue(new ProductAttributeValue
                {
                    AttributeId = attribute.AttributeId,
                    Value = attribute.Value
                });
            }

            foreach (var category in Categories)
            {
                product.AddCategory(new ProductCategory
                {
                    CategoryId = category.CategoryId
                });
            }

            return product;
        }
    }
}


text:
- Foundation+PMUtils was built for iOS and requires a minimum iOS target of iOS 7.

#### Podfile

```ruby
pod "PMUtils/Foundation+PMUtils"
```

## Communication

- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/PMUtils). (Tag 'PMUtils')
- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/PMUtils).
- If you **found a bug**, open an issue.
- If you **have a feature request**, open an issue.
- If you **want to contribute**, submit a pull request.

## Author

- [Peter Meyers](mailto:petermeyers1@gmail.com)

## License

All PMUtils specs are available under the MIT license. See the LICENSE file for more info.


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * This file is part of the PWAK (PHP Web Application Kit) framework.
 *
 * PWAK is a php framework initially developed for the
 * {@link http://onlogistics.googlecode.com Onlogistics} ERP/Supply Chain
 * management web application.
 * It provides components and tools for developers to build complex web
 * applications faster and in a more reliable way.
 *
 * PHP version 5.1.0+
 *
 * LICENSE: This source file is subject to the MIT license that is available
 * through the world-wide-web at the following URI:
 * http://opensource.org/licenses/mit-license.php
 *
 * @package   PWAK
 * @author    ATEOR dev team <dev@ateor.com>
 * @copyright 2003-2008 ATEOR <contact@ateor.com>
 * @license   http://opensource.org/licenses/mit-license.php MIT License
 * @version   SVN: $Id$
 * @link      http://pwak.googlecode.com
 * @since     File available since release 0.1.0
 * @filesource
 */

if (!defined('PREFERENCES_TABLE_NAME')) {
    define('PREFERENCES_TABLE_NAME', 'FW_Preferences');
}

// }}}

/**
 * Classe de gestion des préférences de l'application.
 *
 * Cette classe permet de définir un nombre illimité de Preferences pour une
 * application tout en gérant le type de donnée, les types gérés sont:
 * - string,
 * - integer,
 * - double (aka float),
 * - array (les tableaux sont stockés serialisés et encodés en base64).
 *
 * L'interface est relativement simple, voici un exemple complet:
 * <code>
 * // ajoute (ou modifie) une préférence de type float
 * Preferences::set('tva_rate', 18.6);
 * // ajoute (ou modifie) une préférence de type array
 * Preferences::set('colors', array('blue', 'green', 'red'));
 *
 * // récupèrer les preferences
 * echo Preference::get('tva_rate');   // affiche 18.6
 * print_r(Preference::get('colors')); // affiche array('blue', 'green', 'red')
 *
 * // supprimer une préférence, ne sera supprimée que lors de l'appel à save()
 * Preferences::delete('tva_rate');
 *
 * // sauvegarder les préférences
 * Preferences::save();
 * </code>
 *
 * @license http://opensource.org/licenses/mit-license.php MIT License
 * @package    Framework
 * @copyright  2002-2006 ATEOR - All rights reserved
 * @since      version 2.0.1
 * @todo       Réfléchir à comment lier ça avec les utilisateurs, mais cela
 *             demande d'avoir déjà réfléchi à ce qu'on va faire pour la
 *             gestion des utilisateurs au sein du framework.
 * @todo       Vérifier la gestion des erreurs, s'assurer que toutes les
 *             éventuelles erreurs sont bien remontées.
 */
class Preferences
{
    // properties {{{

    /**
     * Tableau des préférences
     *
     * @var    array $prefs
     * @access protected
     */
    protected static $prefs = array();

    /**
     * Tableau des préférences qui doivent être supprimées en bdd.
     *
     * @var    array $deletedPrefs
     * @access protected
     */
    protected static $deletedPrefs = array();

    /**
     * Mapping des types et de la colonne de la table correspondante
     *
     * @var    array $typeMap
     * @access protected
     */
    protected static $typeMap = array(
        'string'  => 'string_value',
        'boolean' => 'bool_value',
        'integer' => 'int_value',
        'double'  => 'float_value',
        'array'   => 'array_value',
        'text'    => 'text_value'
    );

    /**
     * Flag permettant de savoir si les préférences ont été chargées.
     *
     * @var    bool  $preferencesLoaded
     * @access protected
     */
    protected static $preferencesLoaded = false;

    // }}}
    // Preferences::set() {{{

    /**
     * Défini une Preference, attention si une préférence de ce nom existe déjà
     * elle est modifiée avec la nouvelle valeur.
     *
     * @static
     * @access public
     * @param  string $name
     * @param  string $value
     * @return void
     */
    public static function set($name, $value) {
        self::load();
        $update = isset(self::$prefs[$name]);
        $type = gettype($value);
        if ($type == 'object') {
            trigger_error(
                'Unsupported type "' . $type . '" for key "' . $name . '"',
                E_USER_WARNING
            );
            return;
        }
        if ($type == 'array') {
            // cas particulier des tableaux, il faut passer un tableau
            // (évidemment) qui ne contienne pas d'objets
            $func = create_function('$v', 'return is_object($v);');
            if (!is_array($value) || count(array_filter($value, $func)) > 0) {
                trigger_error(
                    'Wrong value type for an array preference',
                    E_USER_WARNING
                );
                return;
            }
            $value = base64_encode(serialize($value));
        }
        if ($type == 'boolean') {
            $value = $value?'1':'0';
        }
        if ($type == 'string' && strlen($value) > 255) {
            $type = 'text';
        }
        self::$prefs[$name] = array($type, $value, $update, true);
    }

    // }}}
    // Preferences::get() {{{

    /**
     * Récupère une Preference.
     * Si default est renseigné et que la Preference n'existe pas c'est cette
     * valeur qui est retournée.
     *
     * @static
     * @access public
     * @param  string $name
     * @param  mixed  $default
     * @return mixed integer, boolean, double, string or array
     */
    public static function get($name, $default = null) {
        self::load();
        if (!isset(self::$prefs[$name])) {
            return $default;
        }
        $value = self::$prefs[$name][1];
        if (self::$prefs[$name][0] == 'array') {
            // cas particulier des tableaux, il faut deserializer les données
            $value = unserialize(base64_decode($value));
        }
        return $value;
    }

    // }}}
    // Preferences::delete() {{{

    /**
     * Supprime une Preference.
     * Note: la préférences n'est supprimée en base de données que lors de
     * l'appel à la méthode save().
     *
     * @static
     * @access public
     * @param  string $name
     * @return void
     */
    public static function delete($name) {
        self::load();
        if (!isset(self::$prefs[$name])) {
            return;
        }
        if (!in_array($name, self::$deletedPrefs)) {
            self::$deletedPrefs[] = $name;
        }
        unset(self::$prefs[$name]);
    }

    // }}}
    // Preferences::save() {{{

    /**
     * Sauvegarde les préférences en base de données et supprime réellement
     * celles qui doivent être supprimées (cad celles qui ont été supprimées
     * avec la méthode delete()).
     *
     * @static
     * @access public
     * @return void
     */
    public static function save() {
        $insertSQL = "INSERT INTO " . PREFERENCES_TABLE_NAME
                   . " (dbid, name, type, %s) VALUES (%s, %s, '%s', %s)";
        $updateSQL = "UPDATE " . PREFERENCES_TABLE_NAME
                   . " SET type='%s', %s=%s WHERE name=%s%s"; // AND dbid%s
        $deleteSQL = "DELETE FROM " . PREFERENCES_TABLE_NAME
                   . " WHERE name='%s'%s"; //  AND dbid%s
        $dbid = defined('DATABASE_ID')?DATABASE_ID:'NULL';
        $dbidstr = ($dbid == 'NULL')?'':' AND dbid='.$dbid;

        foreach (self::$prefs as $name=>$data) {
            list($type, $value, $update, $modified) = $data;
            $name  = Database::connection()->qstr($name);
            $value = Database::connection()->qstr($value);
            if (!$modified) {
                continue;
            }
            $col = self::$typeMap[$type];
            if ($update) {
                $sql = sprintf($updateSQL, $type, $col, $value, $name, $dbidstr);
            } else {
                $sql = sprintf($insertSQL, $col, $dbid, $name, $type, $value);
            }
            Database::connection()->execute($sql);
        }
        // supprime les préférences qui doivent l'être
        while ($name = array_shift(self::$deletedPrefs)) {
            Database::connection()->execute(sprintf($deleteSQL, $name, $dbidstr));
        }
    }

    // }}}
    // Preferences::load() {{{

    /**
     * Charge les préférences à partir de la base de données si ce n'est pas
     * déjà fait.
     *
     * @static
     * @access protected
     * @return void
     */
    protected static function load() {
        if (self::$preferencesLoaded) {
            return;
        }
        $sql = 'SELECT * FROM FW_Preferences';
        if (defined('DATABASE_ID') && !Object::isPublicEntity('FW_Preferences')) {
            $sql .= ' WHERE dbid IS NULL OR dbid=' . DATABASE_ID;
        }
        $rs = Database::connection()->execute($sql);
        if ($rs) {
            while (!$rs->EOF) {
                $type = $rs->fields['type'];
                $name = $rs->fields['name'];
                $col  = self::$typeMap[$type];
                $value = $rs->fields[$col];
                self::$prefs[$name] = array($type, $value, true, false);
                $rs->moveNext();
            }
            $rs->close();
        }
        self::$preferencesLoaded = true;
    }

    // }}}
    // Preferences::getAll() {{{

    /**
     * Récupère les Preferences.
     *
     * @static
     * @access public
     * @return mixed
     */
    public static function getAll() {
        self::load();
        $return = array();
        foreach(self::$prefs as $name=>$data) {
            $value = $data[1];
            if (self::$prefs[$name][0] == 'array') {
                // cas particulier des tableaux, il faut deserializer les données
                $value = unserialize(base64_decode($value));
            }
            $return[$name] = $value;
        }
        return $return;
    }
    // }}}
}

/**
 * PreferencesByUser.
 *
 * Outil de gestion des préférences d'une application, avec une granularite
 * plus fine que Preferences: granularite du user.
 *
 * @license http://opensource.org/licenses/mit-license.php MIT License
 * @package Framework
 */
class PreferencesByUser extends Preferences
{
    // PreferencesByUser::getRealName() {{{

    /**
     * Utilitaire pour appeler les autres methodes de facon transparente
     *
     * @static
     * @access public
     * @param  string $name
     * @param  integer $userId
     * @return string
     */
    public static function getRealName($name, $userId=0) {
        $userId = (!$userId)?Auth::getUserId():$userId;
        return $name . '_' . $userId;
    }

    // }}}
    // PreferencesByUser::set() {{{

    /**
     * Définit une Preference, attention si une préférence de ce nom existe déjà
     * pour le meme user, elle est modifiee
     *
     * @static
     * @access public
     * @param  string $name
     * @param  string $value
     * @param  integer $userId
     * @return void
     */
    public static function set($name, $value, $userId=0) {
        $name = PreferencesByUser::getRealName($name, $userId);
        parent::set($name, $value);
    }

    // }}}
    // PreferencesByUser::get() {{{

    /**
     * Récupère une Preference.
     * Si default est renseigné et que la Preference n'existe pas c'est cette
     * valeur qui est retournée.
     *
     * @static
     * @access public
     * @param  string $name
     * @param  mixed  $default
     * @param  integer $userId
     * @return mixed integer, boolean, double, string or array
     */
    public static function get($name, $default=false, $userId=0) {
        $name = PreferencesByUser::getRealName($name, $userId);
        return parent::get($name, $default);
    }

    // }}}
    // PreferencesByUser::delete() {{{

    /**
     * Supprime une Preference.
     * Note: la préférence n'est supprimée en base de données que lors de
     * l'appel à la méthode save().
     *
     * @static
     * @access public
     * @param  string $name
     * @param  integer $userId
     * @return void
     */
    public static function delete($name, $userId=0) {
        $name = PreferencesByUser::getRealName($name, $userId);
        parent::delete($name);
    }

    // }}}
}

?>


text:
namespace Microsoft.Azure.Batch.Protocol.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Batch;
    using Microsoft.Azure.Batch.Protocol;
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Contains information about an application in an Azure Batch account.
    /// </summary>
    public partial class ApplicationSummary
    {
        /// <summary>
        /// Initializes a new instance of the ApplicationSummary class.
        /// </summary>
        public ApplicationSummary()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ApplicationSummary class.
        /// </summary>
        /// <param name="id">A string that uniquely identifies the application
        /// within the account.</param>
        /// <param name="displayName">The display name for the
        /// application.</param>
        /// <param name="versions">The list of available versions of the
        /// application.</param>
        public ApplicationSummary(string id, string displayName, IList<string> versions)
        {
            Id = id;
            DisplayName = displayName;
            Versions = versions;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets a string that uniquely identifies the application
        /// within the account.
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the display name for the application.
        /// </summary>
        [JsonProperty(PropertyName = "displayName")]
        public string DisplayName { get; set; }

        /// <summary>
        /// Gets or sets the list of available versions of the application.
        /// </summary>
        [JsonProperty(PropertyName = "versions")]
        public IList<string> Versions { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Id == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Id");
            }
            if (DisplayName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "DisplayName");
            }
            if (Versions == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Versions");
            }
        }
    }
}


text:
package com.deleidos.rtws.commons.monitor.process;

import com.deleidos.rtws.commons.monitor.core.ProcessMonitor;
import com.deleidos.rtws.commons.net.listener.process.MongoDbProcess;

public class MongoDbConfigServerMonitor extends ProcessMonitor {

	private static final MongoDbProcess process = MongoDbProcess.newInstance();

	private MongoDbInfo info = null;

	private class MongoDbInfo {
		String hostname = "127.0.0.1";
		int port = 27019;
	}

	public MongoDbConfigServerMonitor(String name) {
		super(name);

		this.info = new MongoDbInfo();

		// Give the MongoDB server some time to start
		// and set monitoring interval.
		setStartupPeriod(1000 * 60 * 3);
		setMonitorInterval(1000 * 30);
	}

	@Override
	protected void monitor() {
		switch (process.getStatus()) {
		case Running:
			if (!process.testConnection(this.info.hostname, this.info.port)) {
				addError("Failed MongoDB Config Server connection test.");
				break;
			}
			setStatus(MonitorStatus.OK);
			break;
		case Stopped:
			addError("MongoDB Config Server is not running.");
			break;
		default:
			addError("MongoDB Config Server status is currently unknown.");
			break;
		}
	}

}


text:
<!DOCTYPE html>

    <title>  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

 Docs (68% documented)

View on GitHub

         Reference

          Reference

            Classes

                SpreadsheetView

            Protocols

                SpreadsheetViewDataSource

                SpreadsheetViewDelegate

Full configurable spreadsheet view user interfaces for iOS applications. With this framework, you can easily create complex layouts like schedule, Gantt chart, timetable as if you are using Excel.

Features

[x] Fixed column and row headers

[x] Merge cells

[x] Circular infinite scrolling automatically

[x] Customize gridlines and borders for each cell

[x] Customize inter cell spacing vertically and horizontally

[x] Fast scrolling, memory efficient

[x] UICollectionView like API

[x] Well unit tested

Find the above displayed examples in the Examples folder.

Requirements

SpreadsheetView is written in Swift 3. Compatible with iOS 8.0+

Installation

CocoaPods

SpreadsheetView is available through CocoaPods. To install
it, simply add the following line to your Podfile:

pod 'SpreadsheetView'

Carthage

For Carthage, add the following to your Cartfile:

github "kishikawakatsumi/SpreadsheetView"

Getting Started

The minimum requirement is connecting a data source to return the number of columns/rows, and each column width/row height.

import UIKit
import SpreadsheetView

class ViewController: UIViewController, SpreadsheetViewDataSource {
    @IBOutlet weak var spreadsheetView: SpreadsheetView!

    override func viewDidLoad() {
        super.viewDidLoad()
        spreadsheetView.dataSource = self
    }

    func numberOfColumns(in spreadsheetView: SpreadsheetView) -> Int {
        return 200
    }

    func numberOfRows(in spreadsheetView: SpreadsheetView) -> Int {
        return 400
    }

    func spreadsheetView(_ spreadsheetView: SpreadsheetView, widthForColumn column: Int) -> CGFloat {
      return 80
    }

    func spreadsheetView(_ spreadsheetView: SpreadsheetView, heightForRow row: Int) -> CGFloat {
      return 40
    }
}

Usage

Freeze column and row headers

Freezing a column or row behaves as a fixed column/row header.

Column Header

func frozenColumns(in spreadsheetView: SpreadsheetView) -> Int {
    return 2
}

Row Header

func frozenRows(in spreadsheetView: SpreadsheetView) -> Int {
    return 2
}

both

func frozenColumns(in spreadsheetView: SpreadsheetView) -> Int {
    return 2
}

func frozenRows(in spreadsheetView: SpreadsheetView) -> Int {
    return 2
}

Merge cells

Multiple cells can be merged and then they are treated as one cell. It is used for grouping cells.

func mergedCells(in spreadsheetView: SpreadsheetView) -> [CellRange] {
    return [CellRange(from: (row: 1, column: 1), to: (row: 3, column: 2)),
            CellRange(from: (row: 3, column: 3), to: (row: 8, column: 3)),
            CellRange(from: (row: 4, column: 0), to: (row: 7, column: 2)),
            CellRange(from: (row: 2, column: 4), to: (row: 5, column: 8)),
            CellRange(from: (row: 9, column: 0), to: (row: 10, column: 5)),
            CellRange(from: (row: 11, column: 2), to: (row: 12, column: 4))]
}

Circular Scrolling

Your table acquires infinite scroll just set circularScrolling property.

Enable horizontal circular scrolling

spreadsheetView.circularScrolling = CircularScrolling.Configuration.horizontally

Enable vertical circular scrolling

spreadsheetView.circularScrolling = CircularScrolling.Configuration.vertically

Both

spreadsheetView.circularScrolling = CircularScrolling.Configuration.both

If circular scrolling is enabled, you can set additional parameters that the option not to repeat column/row header and to extend column/row header to the left/top edges. CircularScrolling.Configuration is a builder pattern,  can easily select the appropriate combination by chaining properties.

e.g.

spreadsheetView.circularScrolling =
    CircularScrolling.Configuration.horizontally.columnHeaderNotRepeated

spreadsheetView.circularScrolling =
    CircularScrolling.Configuration.both.columnHeaderStartsFirstRow

Customize gridlines, borders and cell spacing

You can customize the appearance of grid lines and borders of the cell. You can specify whether a cell has a grid line or border. Grid lines and borders can be displayed on the left, right, top, or bottom, or around all four sides of the cell.

The difference between gridlines and borders is that the gridlines are drawn at the center of the inter-cell spacing, but the borders are drawn to fit around the cell.

Cell spacing

spreadsheetView.intercellSpacing = CGSize(width: 1, height: 1)

Gridlines

SpreadsheetView‘s gridStyle property is applied to the entire table.

spreadsheetView.gridStyle = .solid(width: 1, color: .lightGray)

You can set different gridStyle for each cell and each side of the cell. If you set cell’s gridStyle property todefault, SpreadsheetView’sgridStyle property will be applied. Specify none means the grid will not be drawn.

cell.gridlines.top = .solid(width: 1, color: .blue)
cell.gridlines.left = .solid(width: 1, color: .blue)
cell.gridlines.bottom = .none
cell.gridlines.right = .none

Border

You can set different borderStyle for each cell as well.

cell.borders.top = .solid(width: 1, color: .red)
cell.borders.left = .solid(width: 1, color: .red)
cell.borders.bottom = .solid(width: 1, color: .red)
cell.borders.right = .solid(width: 1, color: .red)

Author

Kishikawa Katsumi, kishikawakatsumi@mac.com

License

SpreadsheetView is available under the MIT license. See the LICENSE file for more info.

© 2017 kishikawakatsumi. All rights reserved. (Last updated: 2017-10-14)

Generated by jazzy ♪♫ v0.8.4, a Realm project.


text:
/*
 * Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.IdentityManagement.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.IdentityManagement.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// DeactivateMFADevice Request Marshaller
    /// </summary>
    public class DeactivateMFADeviceRequestMarshaller : IMarshaller<IRequest, DeactivateMFADeviceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
    {
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IRequest Marshall(AmazonWebServiceRequest input)
        {
            return this.Marshall((DeactivateMFADeviceRequest)input);
        }

        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(DeactivateMFADeviceRequest publicRequest)
        {
            IRequest request = new DefaultRequest(publicRequest, "Amazon.IdentityManagement");
            request.Parameters.Add("Action", "DeactivateMFADevice");
            request.Parameters.Add("Version", "2010-05-08");

            if(publicRequest != null)
            {
                if(publicRequest.IsSetSerialNumber())
                {
                    request.Parameters.Add("SerialNumber", StringUtils.FromString(publicRequest.SerialNumber));
                }
                if(publicRequest.IsSetUserName())
                {
                    request.Parameters.Add("UserName", StringUtils.FromString(publicRequest.UserName));
                }
            }
            return request;
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

    <title>Editing feature layers | Esri Leaflet</title>

    <meta name="description" content="This sample uses <a href="https://github.com/Leaflet/Leaflet.draw">Leaflet Draw</a> to help edit the geometry of features in a hosted feature service.">

  <meta name="description" content="Esri Leaflet">
  <meta name="viewport" content="width=device-width">

  <link href='//fonts.googleapis.com/css?family=Vollkorn:400italic,700italic,400,700' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="//brick.a.ssl.fastly.net/Source+Code+Pro:300">
  <link href='//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic' rel='stylesheet' type='text/css'>

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

  <link rel="stylesheet" href="//cdn.jsdelivr.net/leaflet/0.7.7/leaflet.css" />

      Esri Leaflet

        Examples
        API Reference
        Download
        View on GitHub

Basemaps

    Showing an ArcGIS basemap
    Basemap with labels
    Switching basemaps
    Retina Basemap

Feature Layers

    Simple FeatureLayer
    Styling points
    Styling lines
    Styling polygons
    Custom popups
    Querying features #1
    Querying features #2
    Spatial Queries
    Simplifying complex features
    Zoom to all features #1
    Zoom to all features #2
    Labeling Features
    Clustering points
    Styling clusters
    Points as a heatmap
    Styling heatmaps
    Time enabled services
    Layer "snapshots"
    Editing

Tile Layers

    Tiles from a Map Service #1
    Tiles from a Map Service #2
    Non-mercator tiles

Dynamic Map Layer

    Simple DynamicMapLayer
    Identifying Features
    Finding Features
    Custom popups
    Time Ranges
    Reprojecting on the fly

Image Map Layer

    Simple ImageMapLayer
    Infrared Imagery using BandIDs
    Rendering Rule
    Identify Imagery
    Mosaic Rule
    Custom popups

Authentication

    ArcGIS Online OAuth
    Premium ArcGIS Online content
    ArcGIS Server username/password

Geocoding

    Geocoding control
    Searching map service
    Searching feature layers
    Center the initial map state
    Reverse geocoding

Other Plugins

    Geoprocessing plugin
    Renderers plugin

Misc.

    Getting service metadata
    Parsing Feature Collections

Editing feature layers

This sample uses Leaflet Draw to help edit the geometry of features in a hosted feature service.

<link rel="stylesheet" href="https://rawgit.com/Leaflet/Leaflet.draw/master/dist/leaflet.draw.css">

    Let's edit!

  <form action='#' id='form'>

      Pedestrian District Name

      <input id='PEDDISTRIC' type="text" value='' name='PEDDISTRIC'>

      Transportation Plan Id

      <input id='TRANPLANID' type='text' value='' name='TRANPLANID' disabled='disabled'>

  </form>

<html>
<head>
  <meta charset=utf-8 />
  <title>Editing feature layers</title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

  <!-- Load Leaflet from CDN-->
  <link rel="stylesheet" href="//cdn.jsdelivr.net/leaflet/0.7.3/leaflet.css" />
  <script src="//cdn.jsdelivr.net/leaflet/0.7.3/leaflet.js"></script>

  <!-- Load Esri Leaflet from CDN -->
  <script src="//cdn.jsdelivr.net/leaflet.esri/1.0.3/esri-leaflet.js"></script>

  <style>
    body { margin:0; padding:0; }
    #map { position: absolute; top:0; bottom:0; right:0; left:0; }
  </style>
</head>
<body>

<!-- Leaflet Draw -->
<script src="https://rawgit.com/Leaflet/Leaflet.draw/master/dist/leaflet.draw-src.js"></script>
<link rel="stylesheet" href="https://rawgit.com/Leaflet/Leaflet.draw/master/dist/leaflet.draw.css">

<style>
  #info-pane {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 10;
    padding: 1em;
    background: white;
    text-align: right;
  }

  #form {
    display: none;
  }
</style>

<div id='map'></div>
<div id='info-pane' class='leaflet-bar'>
  <label id='greeting'>
    Let's edit!
  </label>
  <form action='#' id='form'>
    <label for='PEDDISTRIC'>
      Pedestrian District Name<br>
      <input id='PEDDISTRIC' type="text" value='' name='PEDDISTRIC'><br>
    </label>
    <label for='TRANPLANID'>
      Transportation Plan Id<br>
      <input id='TRANPLANID' type='text' value='' name='TRANPLANID' disabled='disabled'>
    </label>
  </form>
</div>
<script>
  // create the map
  var map = L.map('map').setView([45.512, -122.619], 12);
  L.esri.basemapLayer('Streets').addTo(map);

  // add our feature layer to the map
  var pedestrianDistricts = L.esri.featureLayer({
    url: 'http://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/PDX_Pedestrian_Districts/FeatureServer/0'
  }).addTo(map);

  // variable to track the layer being edited
  var currentlyEditing;
  var currentlyDeleting = false;

  // create a feature group for Leaflet Draw to hook into for delete functionality
  var drawnItems = L.featureGroup();
  map.addLayer(drawnItems);

  // track if we should disable custom editing as a result of other actions (create/delete)
  var disableEditing = false;

  // start editing a given layer
  function startEditing(layer) {
    document.getElementById("PEDDISTRIC").value = layer.feature.properties.PEDDISTRIC;
    // read only
    document.getElementById("TRANPLANID").value = layer.feature.properties.TRANPLANID;
    if (!disableEditing) {
      layer.editing.enable();
      currentlyEditing = layer;
    }
  }

  // stop editing a given layer
  function stopEditing() {
    // if a layer is being edited, finish up and disable editing on it afterward.
    if (currentlyEditing) {
      handleEdit(currentlyEditing);
      currentlyEditing.editing.disable();
    }
    currentlyEditing = undefined;
  }

  function handleEdit(layer) {
    // convert the layer to GeoJSON and build a new updated GeoJSON object for that feature
    layer.feature.properties.PEDDISTRIC = document.getElementById("PEDDISTRIC").value;
    pedestrianDistricts.updateFeature({
      type: 'Feature',
      id: layer.feature.id,
      geometry: layer.toGeoJSON().geometry,
      properties: layer.feature.properties
    }, function(error, response) {
      console.log(error, response);
      displayGreeting();
    });
  }

  function displayAttributes() {
    document.getElementById("greeting").innerHTML = null;
    document.getElementById("form").style.display = 'block';
  }

  function displayGreeting() {
    document.getElementById("greeting").innerHTML = "Lets edit!";
    document.getElementById("form").style.display = 'none';
  }

  // when the map is clicked, stop editing
  map.on('click', function(e) {
    stopEditing();
  });

  // when a pedestrian district is clicked, stop editing the current feature and edit the clicked feature
  pedestrianDistricts.on('click', function(e) {
    stopEditing();
    startEditing(e.layer);
    if (!currentlyDeleting) {
      displayAttributes();
    }
  });

  // when pedestrian districts start loading (because of pan/zoom) stop editing
  pedestrianDistricts.on('loading', function() {
    stopEditing();
  });

  // when new features are loaded clear our current guides and feature groups
  // then load the current features into the guides and feature group
  pedestrianDistricts.on('load', function() {
    // wipe the current layers available for deltion and clear the current guide layers.
    drawnItems.clearLayers();

    // for each feature push the layer representing that feature into the guides and deletion group
    pedestrianDistricts.eachFeature(function(layer) {
      drawnItems.addLayer(layer);
    });
  });

  // create a new Leaflet Draw control
  var drawControl = new L.Control.Draw({
    edit: {
      featureGroup: drawnItems, // allow editing/deleting of features in this group
      edit: false // disable the edit tool (since we are doing editing ourselves)
    },
    draw: {
      circle: false, // disable circles
      marker: false, // disable polylines
      polyline: false, // disable polylines
      polygon: {
        allowIntersection: false, // polygons cannot intersect thenselves
        drawError: {
          color: 'red', // color the shape will turn when intersects
          message: '<strong>Oh snap!<strong> you can\'t draw that!' // message that will show when intersect
        },
      }
    }
  });

  // add our drawing controls to the map
  map.addControl(drawControl);

  // when we start using creation tools disable our custom editing
  map.on('draw:createstart', function() {
    disableEditing = true;
  });

  // when we start using deletion tools, hide attributes and disable custom editing
  map.on('draw:deletestart', function() {
    disableEditing = true;
    currentlyDeleting = true;
  });

  // listen to the draw created event
  map.on('draw:created', function(e) {
    // add the feature as GeoJSON (feature will be converted to ArcGIS JSON internally)
    pedestrianDistricts.addFeature(e.layer.toGeoJSON(), function(error, response) {
      console.log(error, response);
    });
    disableEditing = false;
  });

  // listen to the draw deleted event
  map.on('draw:deleted', function(e) {
    var delArray = [];
    e.layers.eachLayer(function(layer) {
      var id = layer.feature.id;
      delArray.push(id);
    });
    pedestrianDistricts.deleteFeatures(delArray, function(error, response) {
      console.log(error, response);
    });
    disableEditing = false;
    currentlyDeleting = false;
  });
</script>

</body>
</html>

Edit this sample on GitHub

Esri Leaflet is a project from the Esri PDX R&D Center and the Esri Community


text:
cp /opt/podiobooks/supervisord.conf /opt/podiobooks/data/supervisord.conf
cp /etc/nginx/uwsgi_params /opt/podiobooks/data/uwsgi_params

# Clone the Podiobooks Git Repo
git clone --depth=1 https://github.com/podiobooks/podiobooks.git /opt/podiobooks/data/podiobooks

# Link the config files for dev, we can change to staging/prod later by moving symlink
ln -s /opt/podiobooks/data/podiobooks/devscripts/docker/podiobooks-nginx.conf /opt/podiobooks/data/podiobooks-nginx.conf
ln -s /opt/podiobooks/data/podiobooks/devscripts/docker/podiobooks-uwsgi.xml /opt/podiobooks/data/podiobooks-uwsgi.xml

# Install VirtualEnv
cd /opt/podiobooks/data/podiobooks
./devscripts/docker/setup_docker_env.sh
. .env/bin/activate

# Initialize the Django DB
python manage.py migrate --noinput --settings=podiobooks.settings_docker

# Create Initial Superuser - Make sure you change PW
echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass'); exit()" | python manage.py shell --settings=podiobooks.settings_docker

# Collect the Static Files & do other updates
python manage.py collectstatic --noinput --settings=podiobooks.settings_docker
python manage.py collectmedia --settings=podiobooks.settings_docker
python manage.py mub_minify --settings=podiobooks.settings_docker
python manage.py localize_title_covers --settings=podiobooks.settings_docker

# Make sure permissions are correct
chown -R podiobooks.podiobooks /opt/podiobooks/data/podiobooks

# Set up an SSH Key for future use during backups
cd /opt/podiobooks/data
mkdir .ssh
chmod 700 .ssh
cd .ssh
ssh-keygen -t rsa -b 4096 -q -N "" -f id_rsa
cat id_rsa.pub
cd ..
chown -R podiobooks.podiobooks .ssh
echo "Create a new GitHub SSH Key for podiobooks with the Public Key above"


text:
from unittest import TestCase
from django.contrib.auth.models import User
from django.db import models
from reducer.models import Link, Owner

class LinkModelTest(TestCase):

        def test_url_hash(self):
            link = Link._meta.get_field_by_name('url_hash')[0]
            self.assertEquals(link.__class__, models.CharField)
            self.assertEquals(link.max_length, 255)
            self.assertTrue(link.null)
            self.assertTrue(link.blank)
            self.assertTrue(link.unique)

        def test_user(self):
            link = Link._meta.get_field_by_name('user')[0]
            self.assertEquals(link.__class__, models.ForeignKey)

        def test_url(self):
            link = Link._meta.get_field_by_name('url')[0]
            self.assertEquals(link.__class__, models.URLField)

        def test_dt_created(self):
            link = Link._meta.get_field_by_name('dt_created')[0]
            self.assertEquals(link.__class__, models.DateTimeField)
            self.assertTrue(link.auto_now_add)

class OwnerModelTest(TestCase):
    def test_link(self):
        owner = Owner._meta.get_field_by_name('link')[0]
        self.assertEquals(owner.__class__, models.ForeignKey)

    def test_owners(self):
        owner = Owner._meta.get_field_by_name('link')[0]
        self.assertEquals(owner.__class__, models.ForeignKey)

class UseruModelTest(TestCase):
    def test_username(self):
        user = User._meta.get_field_by_name('username')[0]
        self.assertEquals(user.max_length, 30)
        self.assertTrue(user.unique)


text:
<?php

class Model_Session extends Model_Table {
	public $entity_code='session';
    public $table_alias='se';
    public $debug=false;
    private $seesion_name;
    private $session_path;
    function init(){
        parent::init();
        $this->addField("session_id");
        $this->addField("data")->datatype("text");
        $this->addField("timestamp")->datatype("text");
    }
    function open($path, $session_name){
        $this->session_name = $session_name;
        $this->session_path = $path;
        return true;
    }
    function close(){
        $this->update(array("timestamp" => time()));
        return true;
    }
    function read($sid){
        $this->getBySid($sid);
        return $this->get("data");
    }
    function write($sid, $data){
        $this->getBySid($sid);
        $this->update(array("data" => $data, "timestamp" => time()));
        return true;
    }
    function destroy($sid){
        $this->getBySid($sid);
        $this->delete();
    }
    function gc($maxlifetime){
        $maxlifetime = (int) $maxlifetime;
        $this->dsql("gc")->where("timestamp + $maxlifetime < " . time())->do_delete();
    }
    //
    function getBySid($sid){
        if (!($d=$this->getBy("session_id", $this->session_name . ":" . $sid))){
            $this->update(array("session_id" => $this->session_name . ":" . $sid, "timestamp" => time()));
        } else {
            $this->loadData($d["id"]);
        }
        $this->sid = $sid;
    }
}


text:
# HavenOndemand Library for Android. V2.0

----
## Overview
HavenOndemand library for Android is a lightweight Java based API, which helps you easily access over 60 APIs from HPE HavenOnDemand platform.

The library contains 2 packages:

HODClient package for sending HTTP GET/POST requests to HavenOnDemand APIs.

HODResponseParser package for parsing JSON responses from HavenOnDemand APIs.

HODClient library requires a minimum Android API level 10.

----
## Integrate HavenOnDemand into an Android project
Open your app build.gradle and add the dependency as follows:

        dependencies {
     		 // add hodclient and hodresponseparser dependencies
            compile 'com.havenondemand:hodclient:2.0'
            compile 'com.havenondemand:hodresponseparser:2.0'
        }

----
## HODClient API References
**Constructor**

    HODClient(String apiKey, IHODClientCallback callback)

*Description:*

* Constructor. Creates and initializes an HODClient object.

*Parameters:*

* apiKey: your developer apikey.
* callback: class that implements the IHODClientCallback interface.

*Example code:*
##

    import com.hod.api.hodclient.HODClient;
    import com.hod.api.hodclient.IHODClientCallback;

    public class MyActivity extends Activity implements IHODClientCallback
    {
        HODClient hodClient = new HODClient("your-api-key", this);

	    @Override
        public void requestCompletedWithJobID(String response){ }

	    @Override
        public void requestCompletedWithContent(String response){ }

        @Override
        public void onErrorOccurred(String errorMessage){ }
    }

----
**Function GetRequest**

    void GetRequest(Map<String,Object> params, String hodApp, REQ_MODE mode)

*Description:*

* Sends a HTTP GET request to call a Haven OnDemand API.

*Parameters:*

* params: a HashMap object containing key/value pair parameters to be sent to a Haven OnDemand API, where the keys are the parameters of that API.

>Note:

>In the case of a parameter type is an array<>, the value must be defined as a List\<String\> object.
>E.g.:
##
    Map<String, Object> params = new HashMap<String, Object>();
    List<String> urls = new ArrayList<String>();
    urls.add("http://www.cnn.com");
    urls.add("http://www.bbc.com");
    params.put("url", urls);
    params.put("unique_entities", "true");
    List<String> entities = new ArrayList<String>();
    entities.add("people_eng");
    entities.add("places_eng");
    params.put("entity_type", entities);

* hodApp: a string to identify a Haven OnDemand API. E.g. "extractentities". Current supported apps are listed in the HODApps class.
* mode [REQ_MODE.SYNC | REQ_MODE.ASYNC]: specifies API call as Asynchronous or Synchronous.

*Response:*

* If the mode is "ASYNC", response will be returned via the requestCompletedWithJobID(String response) callback function.
* If the mode is "SYNC", response will be returned via the requestCompletedWithContent(String response) callback function.
* If there is an error occurred, the error message will be sent via the onErrorOccurred(String errorMessage) callback function.

*Example code:*
##
    // Call the Entity Extraction API to find people and places from CNN website

    String hodApp = HODApps.ENTITY_EXTRACTION;
    Map<String,Object> params =  new HashMap<String,Object>();
    params.put("url", "http://www.cnn.com");
    List<String> entities = new ArrayList<String>();
    entities.add("people_eng");
    entities.add("places_eng");
    params.put("entity_type", entities);
    hodClient.GetRequest(params, hodApp, HODClient.REQ_MODE.SYNC);

----
**Function PostRequest**

    void PostRequest(Map<String,Object> params, String hodApp, REQ_MODE mode)

*Description:*

* Sends a HTTP POST request to call a Haven OnDemand API.

*Parameters:*

* params: a HashMap object containing key/value pair parameters to be sent to a Haven OnDemand API, where the keys are the parameters of that API.

>Note:

>In the case of a parameter type is an array<>, the value must be defined as a List\<String\> object.
>E.g.:
##
    Map<String, Object> params = new HashMap<String, Object>();
    List<String> urls = new ArrayList<String>();
    urls.add("http://www.cnn.com");
    urls.add("http://www.bbc.com");
    params.put("url", urls);
    params.put("unique_entities", "true");
    List<String> entities = new ArrayList<String>();
    entities.add("people_eng");
    entities.add("places_eng");
    params.put("entity_type", entities);

* hodApp: a string to identify a Haven OnDemand API. E.g. "ocrdocument". Current supported apps are listed in the IODApps class.
* mode [REQ_MODE.SYNC | REQ_MODE.ASYNC]: specifies API call as Asynchronous or Synchronous.

*Response:*

* If the mode is "ASYNC", response will be returned via the requestCompletedWithJobID(String response) callback function.
* If the mode is "SYNC", response will be returned via the requestCompletedWithContent(String response) callback function.
* If there is an error occurred, the error message will be sent via the onErrorOccurred(String errorMessage) callback function.

*Example code:*
##
    // Call the OCR Document API to scan text from an image file

    String hodApp = HODApps.OCR_DOCUMENT;
    Map<String,Object> params =  new HashMap<String,Object>();
    params.put("file", "full/path/filename.jpg");
    params.put("mode", "document_photo");
    hodClient.PostRequest(params, hodApp, HODClient.REQ_MODE.ASYNC);

----
**Function GetJobResult**

    void GetJobResult(String jobID)

*Description:*

* Sends a request to Haven OnDemand to retrieve content identified by the jobID.

*Parameter:*

* jobID: the job ID returned from a Haven OnDemand API upon an asynchronous call.

*Response:*

* Response will be returned via the requestCompletedWithContent(String response)

*Example code:*
##
    // Parse a JSON string contained a jobID and call the function to get the actual content from Haven OnDemand server

    @Override
    public void requestCompletedWithJobID(String response)
    {
        try {
            JSONObject mainObject = new JSONObject(response);
            if (!mainObject.isNull("jobID")) {
                jobID = mainObject.getString("jobID");
                hodClient.GetJobResult(jobID);
            }
        } catch (Exception ex) { }
    }

----
**Function GetJobStatus**

    void GetJobStatus(String jobID)

*Description:*

* Sends a request to Haven OnDemand to retrieve status of a job identified by a job ID. If the job is completed, the response will be the result of that job. Otherwise, the response will contain the current status of the job.

*Parameter:*

* jobID: the job ID returned from a Haven OnDemand API upon an asynchronous call.

*Response:*

* Response will be returned via the requestCompletedWithContent(String response)

*Example code:*
##
    // Parse a JSON string contained a jobID and call the function to get the actual content from Haven OnDemand server

    @Override
    public void requestCompletedWithJobID(String response)
    {
        try {
            JSONObject mainObject = new JSONObject(response);
            if (!mainObject.isNull("jobID")) {
                jobID = mainObject.getString("jobID");
                hodClient.GetJobStatus(jobID);
            }
        } catch (Exception ex) { }
    }

----
## API callback functions
In your class, you will need to inherit the IHODClientCallback interface and implement callback functions to receive responses from the server

    public class MyClass implements IHODClientCallback {

        @Override
        public void requestCompletedWithJobID(String response) {}

        @Override
        public void requestCompletedWithContent(String response) {}

        @Override
        public void onErrorOccurred(string errorMessage){}

    }
#
When you call the GetRequest() or PostRequest() with the ASYNC mode, the response will be returned to this callback function. The response is a JSON string containing the jobID.

    @Override
    public void requestCompletedWithJobID(String response)
    {

    }
#
When you call the GetRequest() or PostRequest() with the SYNC mode or call the GetJobResult() or GwtJobStatus() function, the response will be returned to this callback function. The response is a JSON string containing the actual result of the service.

    @Override
    public void requestCompletedWithContent(String response)
    {

    }
#
If there is an error occurred, the error message will be returned to this callback function.

    @Override
    public void onErrorOccurred(string errorMessage)
    {

    }

----
## HODResponseParser API References
**Constructor**

    HODResponseParser()

*Description:*

* Constructor. Creates and initializes an HODResponseParser object.

*Parameters:*

* None

*Example code:*
##

    import hod.response.parser.HODErrorCode;
    import hod.response.parser.HODErrorObject;
    import hod.response.parser.HODResponseParser;

    public class MyActivity extends Activity
    {
        HODResponseParser hodParser = new HODResponseParser();

    }

----
**Function ParseJobID**

    String ParseJobID(String response)

*Description:*

* Parses a jobID from a json string returned from an asynchronous API call.

*Parameters:*

* response: a json string returned from an asynchronous API call.

*Return value:*

* The jobID or an empty string if not found.

*Example code:*
##
    // Parse the jobID from within HODClient callback function
    void requestCompletedWithJobID(string response)
    {
        String jobID = hodParser.ParseJobID(response);
        if (jobID != "")
            hodClient.GetJobResult(jobID);
    }

----
**Function ParseSpeechRecognitionResponse**

    SpeechRecognitionResponse ParseSpeechRecognitionResponse(String jsonStr)

*Description:*

* Parses a json response from Haven OnDemand Speech Recognition API and returns a SpeechRegconitionResponse object.

> Note: See the full list of standard parser functions from the Standard response parser functions section at the end of this document.

*Parameters:*

* jsonStr: a json string returned from a synchronous API call or from the GetJobResult() or GetJobStatus() function.

*Return value:*

* An object containing API's response values. If there is an error or if the job is not completed (callback from a GetJobStatus call), the returned object is null and the error or job status can be accessed by calling the GetLastError() function.

*Example code:*
##
    // Parse the Sentiment Analysis response from within HODClient callback function
    void requestCompletedWithContent(string response)
    {
        SentimentAnalysisResponse resp = hodParser.ParseSentimentAnalysisResponse(response);

        if (resp != null) {
            String positive = "";
            for (SentimentAnalysisResponse.Entity ent : resp.positive) {
                if (ent.original_text != null)
                    positive += "Statement: " + ent.original_text + "\n";
                if (ent.sentiment != null)
                    positive += "Sentiment: " + ent.sentiment + "\n";
                if (ent.topic != null)
                    positive += "Topic: " + ent.topic + "\n";
                if (ent.score != null)
                    positive += "Score: " + ent.score.toString() + "\n";
            }
            String negative = "";
            for (SentimentAnalysisResponse.Entity ent : resp.negative) {
                if (ent.original_text != null)
                    negative += "Statement: " + ent.original_text + "\n";
                if (ent.sentiment != null)
                    negative += "Sentiment: " + ent.sentiment + "\n";
                if (ent.topic != null)
                    negative += "Topic: " + ent.topic + "\n";
                if (ent.score != null)
                    negative += "Score: " + ent.score.toString() + "\n";
            }
            String sentiment = positive;
            sentiment += negative;
            sentiment += "Aggregate: \n" + resp.aggregate.sentiment + "\n";
            sentiment += resp.aggregate.score + "\n---";
            //print sentiment result
        } else { // check status or handle error
            List<HODErrorObject> errors = hodParser.GetLastError();
            String errorMsg = "";
            for (HODErrorObject err: errors) {
                if (err.error == HODErrorCode.QUEUED) {
                    // sleep for a few seconds then check the job status again
                    hodClient.GetJobStatus(err.jobID);
                    return;
                } else if (err.error == HODErrorCode.IN_PROGRESS) {
                    // sleep for for a while then check the job status again
                    hodClient.GetJobStatus(err.jobID);
                    return;
                } else {
                    errorMsg += String.format("Error code: %d\nError Reason: %s\n", err.error, err.reason);
                    if (err.detail != null)
                        errorMsg += "Error detail: " + err.detail + "\n";
                }
                // print error message.
            }
        }
    }
----
**Function ParseCustomResponse**

    Object ParseCustomResponse(Class<?> T, String jsonStr)

*Description:*

* Parses a json string and returns a custom object type based on the T class.

*Parameters:*

* \<T\>: a custom class object.
* jsonStr: a json string returned from a synchronous API call or from the GetJobResult() or GetJobStatus() function.

*Return value:*

* An object containing API's response values. If there is an error or if the job is not completed (callback from a GetJobStatus call), the returned object is null and the error or job status can be accessed by calling the GetLastError() function.

*Example code:*
##
    // Parse the Query Text Index response from within HODClient callback function
    public class MyTextIndexResponse {
        public List<Document> documents;
        public class Document {
            public String reference;
            public String index;
            public List<String> store_name;
            public List<String> operation_time;
            public List<String> store_location;
            public List<String> contact_number;
            public List<String> product_category;
        }
    }
    void requestCompletedWithContent(string response)
    {
        MyTextIndexResponse resp = (MyTextIndexResponse) hodParser.ParseCustomResponse(MyTextIndexResponse.class, response);
        if (resp != null) {
            for (MyTextIndexResponse.Document doc : resp.documents) {
                // access document field ...
                // e.g. doc.reference
            }
        } else { // check status or handle error
            List<HODErrorObject> errors = parser.GetLastError();
            String errorMsg = "";
            for (HODErrorObject err: errors) {
                if (err.error == HODErrorCode.QUEUED) {
                    // sleep for a few seconds then check the job status again
                    hodClient.GetJobStatus(err.jobID);
                    return;
                } else if (err.error == HODErrorCode.IN_PROGRESS) {
                    // sleep for for a while then check the job status again
                    hodClient.GetJobStatus(err.jobID);
                    return;
                } else {
                    errorMsg += String.format("Error code: %d\nError Reason: %s\n", err.error, err.reason);
                    if (err.detail != null)
                        errorMsg += "Error detail: " + err.detail + "\n";
                }
                // print error message.
            }
        }
    }
----
**Function GetLastError**

    List<HODErrorObject> GetLastError()

*Description:*

* Get the latest error(s) if any happened during parsing the json string or HOD error returned from HOD server. > Note: The job "queued" or "in progress" status is also considered as an error situation. See the example below for how to detect and handle error status.

*Parameters:*

* None.

*Return value:*

* An list object contains HODErrorObject

*Example code:*

```
List<HODErrorObject> errors = parser.GetLastError();
String errorMsg = "";
for (HODErrorObject err : errors) {
    if (err.error == HODErrorCode.QUEUED) {
        hodClient.GetJobStatus(err.jobID);
        return;
    } else if (err.error == HODErrorCode.IN_PROGRESS) {
        hodClient.GetJobStatus(err.jobID);
        return;
    } else {
        errorMsg += String.format("Error code: %d\nError Reason: %s\n", err.error, err.reason);
        if (err.detail != null)
            errorMsg += "Error detail: " + err.detail + "\n";
    }
    // print errorMsg
}
```
----

## Demo code 1:

**Call the Entity Extraction API to extract people and places from cnn.com website with a synchronous GET request**

    import com.hod.api.hodclient.IHODClientCallback;
    import com.hod.api.hodclient.HODApps;
    import com.hod.api.hodclient.HODClient;
    import hod.response.parser.HODErrorCode;
    import hod.response.parser.HODErrorObject;
    import hod.response.parser.HODResponseParser;

    public class MyActivity extends Activity implements IHODClientCallback {

        HODClient hodClient;
	    HODResponseParser hodParser;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            hodClient = new HODClient("your-apikey", this);
            hodParser = new HODResponseParser();

            useHODClient();
        }

        private void useHODClient() {
            String hodApp = HODApps.ENTITY_EXTRACTION;
            params.put("url", "http://www.cnn.com");
            List<String> entities = new ArrayList<String>();
            entities.add("people_eng");
            entities.add("places_eng");
            params.put("entity_type", entities);
            params.put("unique_entities", "true");

            hodClient.GetRequest(params, hodApp, HODClient.REQ_MODE.SYNC);
        }

        // define a custom response class
        public class EntityExtractionResponse {
            public List<Entity> entities;

            public class AdditionalInformation
            {
                public List<String> person_profession;
                public String person_date_of_birth;
                public String wikipedia_eng;
                public Long place_population;
                public String place_country_code;
                public Double place_elevation;
            }
            public class Entity
            {
                public String normalized_text;
                public String type;
                public AdditionalInformation additional_information;
            }
        }

        // implement callback functions
        @Override
        public void requestCompletedWithContent(String response) {
            EntityExtractionResponse resp = (EntityExtractionResponse) hodParser.ParseCustomResponse(EntityExtractionResponse.class, response);
            if (resp != null) {
                String values = "";
                for (EntityExtractionResponse.Entity ent : resp.entities) {
                    values += ent.type + "\n";
                    values += ent.normalized_text + "\n";
                    if (ent.type.equals("places_eng")) {
                        values += ent.additional_information.place_country_code + "\n";
                        values += ent.additional_information.place_elevation + "\n";
                        values += ent.additional_information.place_population + "\n";
                    } else if (ent.type.equals("people_eng")) {
                        values += ent.additional_information.person_date_of_birth + "\n";
                        values += ent.additional_information.person_profession + "\n";
                        values += ent.additional_information.wikipedia_eng + "\n";
                    }
                }
                // print the values
            } else {
                List<HODErrorObject> errors = parser.GetLastError();
                String errorMsg = "";
                for (HODErrorObject err : errors) {
                    errorMsg += String.format("Error code: %d\nError Reason: %s\n", err.error, err.reason);
                    if (err.detail != null)
                        errorMsg += "Error detail: " + err.detail + "\n";
                    // handle error message
                }
            }
        }

        @Override
        public void onErrorOccurred(String errorMessage) {
            // handle error if any
        }
    }

----

## Demo code 2:

**Call the OCR Document API to recognize text from an image with an asynchronous POST request**

    import com.hod.api.hodclient.IHODClientCallback;
    import com.hod.api.hodclient.HODApps;
    import com.hod.api.hodclient.HODClient;
    import hod.response.parser.HODErrorCode;
    import hod.response.parser.HODErrorObject;
    import hod.response.parser.HODResponseParser;
    import hod.response.parser.OCRDocumentResponse;

    public class MyActivity extends Activity implements IHODClientCallback {

        HODClient hodClient;
	    HODResponseParser hodParser;
	    String hodApp = "";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            hodClient = new HODClient("your-apikey", this);
            hodParser = new HODResponseParser();
            useHODClient();
        }

        private void useHODClient() {
            hodApp = HODApps.OCR_DOCUMENT;
            Map<String, Object> params = new HashMap<String, Object>();

            params.put("file", "path/and/filename");
            params.put("mode", "document_photo");

            hodClient.PostRequest(params, hodApp, HODClient.REQ_MODE.ASYNC);
        }

        // implement delegated functions

        /**************************************************************************************
        * An async request will result in a response with a jobID. We parse the response to get
        * the jobID and send a request for the actual content identified by the jobID.
        **************************************************************************************/
        @Override
        public void requestCompletedWithJobID(String response) {
            String jobID = parser.ParseJobID(response);
            if (jobID.length() > 0)
                hodClient.GetJobStatus(jobID);
        }

        @Override
        public void requestCompletedWithContent(String response) {
            OCRDocumentResponse resp = hodParser.ParseOCRDocumentResponse(response);
            if (resp != null) {
                String text = "";
                for (OCRDocumentResponse.TextBlock block : resp.text_block) {
                    text += block.text + "\n";
                }
                // print recognized text.
            } else {
                List<HODErrorObject> errors = parser.GetLastError();
                String errorMsg = "";
                for (HODErrorObject err: errors) {
                    if (err.error == HODErrorCode.QUEUED) {
                        // sleep for a few seconds then check the job status again
                        hodClient.GetJobStatus(err.jobID);
                        return;
                    } else if (err.error == HODErrorCode.IN_PROGRESS) {
                        // sleep for for a while then check the job status again
                        hodClient.GetJobStatus(err.jobID);
                        return;
                    } else {
                        errorMsg += String.format("Error code: %d\nError Reason: %s\n", err.error, err.reason);
                        if (err.detail != null)
                            errorMsg += "Error detail: " + err.detail + "\n";
                    }
                    // print error message.
                }
            }
        }

        @Override
        public void onErrorOccurred(String errorMessage) {
            // handle error if any
        }
    }
---
## Standard response parser functions
```
ParseSpeechRecognitionResponse(String jsonStr)
ParseCancelConnectorScheduleResponse(String jsonStr)
ParseConnectorHistoryResponse(String jsonStr)
ParseConnectorStatusResponse(String jsonStr)
ParseCreateConnectorResponse(String jsonStr)
ParseDeleteConnectorResponse(String jsonStr)
ParseRetrieveConnectorConfigurationFileResponse(String jsonStr)
ParseRetrieveConnectorConfigurationAttrResponse(String jsonStr)
ParseStartConnectorResponse(String jsonStr)
ParseStopConnectorResponse(String jsonStr)
ParseUpdateConnectorResponse(String jsonStr)
ParseExpandContainerResponse(String jsonStr)
ParseStoreObjectResponse(String jsonStr)
ParseViewDocumentResponse(String jsonStr)
ParseGetCommonNeighborsResponse(String jsonStr)
ParseGetNeighborsResponse(String jsonStr)
ParseGetNodesResponse(String jsonStr)
ParseGetShortestPathResponse(String jsonStr)
ParseGetSubgraphResponse(String jsonStr)
ParseSuggestLinksResponse(String jsonStr)
ParseSummarizeGraphResponse(String jsonStr)
ParseOCRDocumentResponse(String jsonStr)
ParseRecognizeBarcodesResponse(String jsonStr)
ParseRecognizeImagesResponse(String jsonStr)
ParseDetectFacesResponse(String jsonStr)
ParsePredictResponse(String jsonStr)
ParseRecommendResponse(String jsonStr)
ParseTrainPredictorResponse(String jsonStr)
ParseCreateQueryProfileResponse(String jsonStr)
ParseDeleteQueryProfileResponse(String jsonStr)
ParseRetrieveQueryProfileResponse(String jsonStr)
ParseUpdateQueryProfileResponse(String jsonStr)
ParseFindRelatedConceptsResponse(String jsonStr)
ParseAutoCompleteResponse(String jsonStr)
ParseExtractConceptsResponse(String jsonStr)
ParseExpandTermsResponse(String jsonStr)
ParseHighlightTextResponse(String jsonStr)
ParseIdentifyLanguageResponse(String jsonStr)
ParseTokenizeTextResponse(String jsonStr)
ParseSentimentAnalysisResponse(String jsonStr)
ParseAddToTextIndexResponse(String jsonStr)
ParseCreateTextIndexResponse(String jsonStr)
ParseDeleteTextIndexResponse(String jsonStr)
ParseDeleteFromTextIndexResponse(String jsonStr)
ParseIndexStatusResponse(String jsonStr)
ParseListResourcesResponse(String jsonStr)
ParseRestoreTextIndexResponse(String jsonStr)
```
----
## Supported standard response classes
```
RecognizeSpeechResponse
CancelConnectorResponse
ConnectorHistoryResponse
ConnectorStatusResponse
CreateConnectorResponse
DeleteConnectorResponse
RetrieveConnectorConfigurationAttributeResponse
RetrieveConnectorConfigurationFileResponse
StartConnectorResponse
StopConnectorResponse
UpdateConnectorResponse
ExpandContainerResponse
StoreObjectResponse
ViewDocumentResponse
GetCommonNeighborsResponse
GetNeighborsResponse
GetNodesResponse
GetShortestPathResponse
GetSubgraphResponse
SuggestLinksResponse
SummarizeGraphResponse
OCRDocumentResponse
BarcodeRecognitionResponse
FaceDetectionResponse
ImageRecognitionResponse
PredictResponse
RecommendResponse
TrainPredictionResponse
CreateQueryProfileResponse
DeleteQueryProfileResponse
RetrieveQueryProfileResponse
UpdateQueryProfileResponse
FindRelatedConceptsResponse
AutoCompleteResponse
ConceptExtractionResponse
ExpandTermsResponse
HighlightTextResponse
LanguageIdentificationResponse
SentimentAnalysisResponse
TextTokenizationResponse
AddToTextIndexResponse
CreateTextIndexResponse
DeleteTextIndexResponse
DeleteFromTextIndexResponse
IndexStatusResponse
ListResourcesResponse
RestoreTextIndexResponse
```
---
## License
Licensed under the MIT License.

HODClient library uses the Apache httpmime-4.3.2 and httpcore-4.3.2 libraries. For your convenience, the library project included the httpmime-4.3.2.jar and httpcore-4.3.jar files. The dependent components are licensed under the Apache License 2.0. Please see the files called LICENSE.txt and NOTICE.txt for more information.


text:
package geomys

// MapProjection -- a method to transfrom a globe's surface into a plane.
type MapProjection interface {
	// Spheroid -- returns the spheroid of the map projection.
	Spheroid() Spheroid
	// Params -- returns the parameters of the map projection.
	Params() map[string]float64
	// Project -- transforms a geographic point from
	// the spheroid into a location on the plane.
	Project(Point) [2]float64
}


text:
require 'spec_helper'

describe service('zookeeper') do
  it { should be_enabled   }
  it { should be_running   }
end

describe port(2181) do
  it { should be_listening }
end

describe file('/var/lib/zookeeper/myid') do
  it { should be_file }
  its(:content) { should match /1/ }
end


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2018 Ryo Suzuki
//	Copyright (c) 2016-2018 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/Platform.hpp>
# if defined(SIV3D_TARGET_MACOS) || defined(SIV3D_TARGET_LINUX)

# include <Siv3D/RasterizerState.hpp>

namespace s3d
{
	class GLRasterizerState
	{
	private:

		RasterizerState m_currentState = RasterizerState::Default2D;

	public:

		GLRasterizerState();

		void set(const RasterizerState& state);
	};
}

# endif


text:
package com.iisquare.elasticsearch.wltea.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.iisquare.elasticsearch.wltea.dao.DictDao;
import com.iisquare.elasticsearch.wltea.util.DPUtil;
import com.iisquare.elasticsearch.wltea.util.MongoUtil;
import com.iisquare.elasticsearch.wltea.util.ValidateUtil;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class DictService extends ServiceBase {

	public DictDao dictDao;

	public DictService() {
		dictDao = new DictDao();
	}

	public String getIdName() {
		return dictDao.idName;
	}

	/**
	 * 通过JSON命令处理词典
	 *
	 * @param cmd {
	 * 		dicName : { // 词典名称
	 * 			insert : [{ // 添加
	 * 				text : "内容,不能为空",
	 *				identity : "自定义标示(分类_ID),null时自定转为空字符串"
	 *			}],
	 *			update : [{ // 修改
	 *				from : { // 至少要设置一个查询条件
	 *					text : "不设置该key时,不作为查询条件",
	 *					identity : "不设置该key时,不作为查询条件"
	 *				},
	 *				to : {
	 *					text : "内容,不能为空",
	 *					identity : "自定义标示(分类_ID),null时自定转为空字符串"
	 *				}
	 *			}],
	 *			delete : [{ // 删除
	 *				text : "不设置该key时,不作为查询条件",
	 *				identity : "不设置该key时,不作为查询条件"
	 *			}]
	 *		}
	 *	}
	 */
	@SuppressWarnings("unchecked")
	public LinkedHashMap<String, Object> runCommand(String dictSerial, LinkedHashMap<?, ?> cmd) {
		String[] dicts = new String[] { "quantifier", "stopword", "synonym", "word" };
		String[] cruds = new String[] { "insert", "update", "delete" };
		boolean status = true;
		LinkedHashMap<String, Object> map = new LinkedHashMap<>();
		map.put("status", status);
		int time = DPUtil.getCurrentSeconds();
		for (String dict : dicts) {
			Object object = cmd.get(dict);
			if (DPUtil.empty(object) || !(object instanceof LinkedHashMap)) continue;
			if (!dictDao.selectTable(dict, dictSerial)) continue;
			Map<?, ?> cmdCrud = (Map<?, ?>) object;
			for (String crud : cruds) {
				object = cmdCrud.get(crud);
				if (DPUtil.empty(object) || !(object instanceof ArrayList)) continue;
				ArrayList<LinkedHashMap<?, ?>> crudArray = (ArrayList<LinkedHashMap<?, ?>> ) object;
				Iterator<LinkedHashMap<?, ?>> iter = crudArray.iterator();
				LinkedHashMap<String, Object> crudMap = new LinkedHashMap<>();
				switch (crud) {
				case "insert": // {"word":{"insert":[{"text":"中文","identity":"test"},{"text":"分词","identity":"test"}]}}
					List<DBObject> docs = new ArrayList<>();
					ArrayList<Object> texts = new ArrayList<>();
					while (iter.hasNext()) {
						LinkedHashMap<?, ?> crudItem = iter.next();
						Object text = crudItem.get("text");
						Object identity = crudItem.get("identity");
						if (DPUtil.empty(text))
							continue;
						if (null == identity)
							identity = "";
						texts.add(text);
						BasicDBObject doc = new BasicDBObject()
								.append("text", text)
								.append("identity", identity)
								.append("time_create", time)
								.append("time_update", time);
						docs.add(doc);
					}
					ArrayList<Map<?, ?>> textMapList = dictDao.getList(null,
							new BasicDBObject("text", new BasicDBObject("$in",
									texts)), null, 1, 0, 0);
					for (Map<?, ?> textMap : textMapList) {
						int size = docs.size();
						for (int i = size - 1; i >= 0; i--) {
							if (!docs.get(i).get("text")
									.equals(textMap.get("text")))
								continue;
							docs.remove(i);
						}
					}
					int insertSize = docs.size();
					if (0 != insertSize && dictDao.insert(docs) == null) {
						status = false;
						crudMap.put(crud, null);
					} else {
						crudMap.put(crud, insertSize);
					}
					break;
				case "update": // {"word":{"update":[{"from":{"text":"分词"},"to":{"text":"词语","identity":"test"}}]}}
					ArrayList<Integer> effectList = new ArrayList<>();
					while (iter.hasNext()) {
						LinkedHashMap<?, ?> crudItem = iter.next();
						object = crudItem.get("from");
						if (DPUtil.empty(object) || !(object instanceof LinkedHashMap)) {
							effectList.add(null);
							continue;
						}
						LinkedHashMap<?, ?> updateFrom = (LinkedHashMap<?, ?>) object;
						object = crudItem.get("to");
						if (DPUtil.empty(object) || !(object instanceof LinkedHashMap<?, ?>)) {
							effectList.add(null);
							continue;
						}
						LinkedHashMap<?, ?> updateTo = (LinkedHashMap<?, ?>) object;
						Object text = updateFrom.get("text");
						Object identity = updateFrom.get("identity");
						if (null == text && null == identity) {
							effectList.add(null);
							continue;
						}
						DBObject updateQuery = new BasicDBObject();
						if (null != text)
							updateQuery.put("text", text);
						if (null != identity)
							updateQuery.put("identity", identity);
						text = updateTo.get("text");
						identity = updateTo.get("identity");
						if (null == text && null == identity) {
							effectList.add(null);
							continue;
						}
						DBObject updateDoc = new BasicDBObject("time_update",
								time);
						if (null != text)
							updateDoc.put("text", text);
						if (null != identity)
							updateDoc.put("identity", identity);
						int result = dictDao.update(updateQuery, updateDoc);
						if (result >= 0) {
							effectList.add(result);
						} else {
							status = false;
							effectList.add(null);
						}
					}
					crudMap.put(crud, effectList);
					break;
				case "delete": // {"word":{"delete":[{"text":"分词"},{"text":"词语","identity":"test"}]}}
					BasicDBList dbList = new BasicDBList();
					while (iter.hasNext()) {
						LinkedHashMap<?, ?> crudItem = iter.next();
						Object text = crudItem.get("text");
						Object identity = crudItem.get("identity");
						if (null == text && null == identity) {
							continue;
						}
						DBObject doc = new BasicDBObject();
						if (null != text)
							doc.put("text", text);
						if (null != identity)
							doc.put("identity", identity);
						dbList.add(doc);
					}
					int deleteSize = dbList.size();
					if (0 != deleteSize) {
						deleteSize = dictDao.delete(new BasicDBObject("$or",
								dbList));
						if (deleteSize < 0) {
							status = false;
							crudMap.put(crud, null);
							break;
						}
					}
					crudMap.put(crud, deleteSize);
					break;
				default:
				}
				map.put(dict, crudMap);
			}
		}
		if (!status)
			map.put("status", status);
		return map;
	}

	public LinkedHashMap<String, Object> search(String dictSerial,
			Map<String, Object> args) {
		LinkedHashMap<String, Object> returnMap = getListTemplate();
		BasicDBObject query = new BasicDBObject();
		Object type = args.get("type");
		if (DPUtil.empty(type) || !dictDao.selectTable(type.toString(), dictSerial)) return null;
		Object text = args.get("text");
		if (!DPUtil.empty(text)) {
			query.append("text", Pattern.compile("^.*" + text + ".*$"));
		}
		Object identity = args.get("identity");
		if (null != identity) {
			query.append("identity", identity);
		}
		int page = ValidateUtil.filterInteger(args.get("page"), true, 1, null,
				1);
		int pageSize = ValidateUtil.filterInteger(args.get("pageSize"), true,
				0, 500, 0);
		long count = dictDao.getCount(query);
		if (count > 0) {
			returnMap.put("rows", dictDao.getList(null, query,
					new BasicDBObject("time_update", -1), page, pageSize, 0));
		}
		returnMap.put("page", page);
		returnMap.put("pageSize", pageSize);
		returnMap.put("total", count);
		if (pageSize > 0)
			returnMap
					.put("totalPage",
							Math.ceil(Double.valueOf(count)
									/ Double.valueOf(pageSize)));
		return returnMap;
	}

	public Object insert(Object type, String dictSerial, BasicDBObject doc) {
		if (DPUtil.empty(type)
				|| !dictDao.selectTable(type.toString(), dictSerial))
			return null;
		return dictDao.insert(doc);
	}

	public List<DBObject> insert(Object type, String dictSerial,
			List<DBObject> docs) {
		if (DPUtil.empty(type)
				|| !dictDao.selectTable(type.toString(), dictSerial))
			return null;
		return dictDao.insert(docs);
	}

	public long exist(Object type, String dictSerial, Object[] texts) {
		if (DPUtil.empty(type)
				|| !dictDao.selectTable(type.toString(), dictSerial))
			return -1;
		return dictDao.getCount(new BasicDBObject("text", new BasicDBObject(
				"$in", MongoUtil.arrayToList(texts))));
	}

	public int updateById(Object type, String dictSerial, Object id,
			Object text, Object identity) {
		if (DPUtil.empty(id) || DPUtil.empty(type)
				|| !dictDao.selectTable(type.toString(), dictSerial))
			return -1;
		DBObject doc = dictDao.getById(null, id);
		if (null == doc)
			return -2;
		doc.put("text", text);
		if (null != identity)
			doc.put("identity", identity);
		doc.put("time_update", DPUtil.getCurrentSeconds());
		return dictDao.updateById(doc, id);
	}

	public int deleteById(Object type, String dictSerial, Object id) {
		if (DPUtil.empty(id) || DPUtil.empty(type)
				|| !dictDao.selectTable(type.toString(), dictSerial))
			return -1;
		return dictDao.deleteById(id);
	}

	public int deleteByIds(Object type, String dictSerial, Object... ids) {
		if (DPUtil.empty(ids) || DPUtil.empty(type)
				|| !dictDao.selectTable(type.toString(), dictSerial))
			return -1;
		return dictDao.deleteByIds(ids);
	}
}


text:
module("deprecated", { teardown: moduleTeardown });

if ( jQuery.fn.size ) {
	test("size()", function() {
		expect(1);
		equal( jQuery("#qunit-fixture p").size(), 6, "Get Number of Elements Found" );
	});
}


text:
<?php
if( ! defined( 'WP_UNINSTALL_PLUGIN' ) )
    exit();

global $wpdb;
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'woocommerce_coinco%';");
?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SM2Core.Entities {
	public interface DerivedValue {
		List<Skill> Skills { get; set; }
		List<Attribute> Attributes { get; set; }
	}
}


text:
package org.wso2.carbon.identity.user.store.configuration.listener;

import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.identity.core.model.IdentityEventListenerConfig;
import org.wso2.carbon.identity.core.util.IdentityCoreConstants;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.listener.UserOperationEventListener;

/**
 * Abstract implementation of {@link UserStoreConfigListener}.
 */
public abstract class AbstractUserStoreConfigListener implements UserStoreConfigListener {

    public boolean isEnable() {
        IdentityEventListenerConfig identityEventListenerConfig = IdentityUtil.readEventListenerProperty
                (UserOperationEventListener.class.getName(), this.getClass().getName());

        if (identityEventListenerConfig == null) {
            return true;
        }

        if (StringUtils.isNotBlank(identityEventListenerConfig.getEnable())) {
            return Boolean.parseBoolean(identityEventListenerConfig.getEnable());
        } else {
            return true;
        }
    }

    public int getOrderId() {
        IdentityEventListenerConfig identityEventListenerConfig = IdentityUtil.readEventListenerProperty
                (UserOperationEventListener.class.getName(), this.getClass().getName());
        if (identityEventListenerConfig == null) {
            return IdentityCoreConstants.EVENT_LISTENER_ORDER_ID;
        }
        return identityEventListenerConfig.getOrder();
    }

    @Override
    public void onUserStoreNamePreUpdate(int tenantId, String currentUserStoreName, String newUserStoreName)
            throws UserStoreException {
        /* Method not implemented */
    }

    @Override
    public void onUserStoreNamePostUpdate(int tenantId, String currentUserStoreName, String newUserStoreName)
            throws UserStoreException {
        /* Method not implemented */
    }

    @Override
    public void onUserStorePreDelete(int tenantId, String userStoreName) throws UserStoreException {
        /* Method not implemented */
    }

    @Override
    public void onUserStorePostDelete(int tenantId, String userStoreName) throws UserStoreException {
        /* Method not implemented */
    }

    @Override
    public void onUserStorePreAdd(int tenantId, String userStoreName) throws UserStoreException {

        /* Method not implemented. */
    }
}


text:
title: "Parallel Android Tests with Spoon"
excerpt: "Learn how to run your UI tests on multiple devices simultaneously"
comments: true
related: true
header:
    image: /assets/images/parallel_run_android_thumbnail.png
    overlay_image: /assets/images/parallel_run_android.jpg
    overlay_filter: 0.25
date: 2017-09-15
toc: true
toc_label: "Parallel Android Tests with Spoon"
tags:
  - android
---
{% include toc title="Parallel Android Tests with Spoon" icon="file-text" %}
## Why Spoon?
It's a well known fact that Mobile Apps are the next big thing and no one argues their testing is really important nowadays. There are couple of open source tools allowing to run your functional mobile tests across multiple platforms in parallel to ensure the app runs as expected on different sets of OS versions, screen sizes and hardware configurations. But what if your application's supposed to run only on one of those set?

{% include figure image_path="/assets/images/sharding.gif" alt="Parallel test run on different Android devices" caption="Parallel test run on different Android devices" %}

Let's imaging hypothetical situation. There is a team out there who's developing FireTV application. For the moment there is only one versions of FireTV devices on the market. Test developers from the team implemented 100 functional UI tests. They've got 10 TV devices for testing purposes. Now, if they ran their tests with native instruments (i.e. UiAutomator and JUnit), they would get hundred of tests running on each of the 10 devices in parallel, which is basically waste of resources. Hence to get the most benefits from their amount of devices they would need to **shard*** those 100 tests to all of their devices. That way each of the them will get 10 tests and total time of execution might be decreased by a factor of 10 (in ideal case).

**Sharding*** is splitting the test suite into multiple threads, so they can be easily run as a group under the same Instrumentation instance and on the same device.
{: .notice--info}

So how do we shard our tests with native tools like JUnit and [UiAutomator](https://alexilyenko.github.io/uiautomator-basics/)? I would recommend [Spoon](http://square.github.io/spoon/) for this. It's easy-to-use lightweight tool, which main goal is to distribute execution of the tests, making their output more useful. Spoon will help you to shard and run your tests on multiple devices simultaneously with no-brainer. Let's find out how to setup this useful tool.

## Setup
Since we decided to leverage native Android tools for our testing and Gradle is the standard de-facto for all Android projects, we will use [Spoon Gradle Plugin](https://github.com/stanfy/spoon-gradle-plugin).

The first step would be the adding Spoon's class path to top-level `build.gradle` file:
```groovy
buildscript {
 // your configurations go here
 dependencies {
  // other dependencies go here
  classpath 'com.stanfy.spoon:spoon-gradle-plugin:1.2.2'
 }
}
```
The next thing to do is to configure app's `build.gradle`. At first we will apply Spoon plugin and then configure Spoon task.

```groovy
apply plugin: 'spoon'
// rest of your configuration
spoon {
 shard = true
}
```

`shard=true` means that Spoon will use its built-in auto sharding function and we won't need to care about splitting our tests manually. More available settings can be found in the [official documentation](https://github.com/stanfy/spoon-gradle-plugin/blob/master/README.md).

Now let's check if we set up everything correctly. Run `./gradlew tasks` under your project folder. We should be able to see Spoon's tasks under Verification group, like it's shown in the figure below:

Verify if Spoon tasks are available under Verification group

Assuming we were able to see those tasks, we're ready to run our tests on multiple devices in parallel!

## Parallel run
Spoon is designed as a tool for running all of your functional tests across all of the connected devices (i.e. visible by `adb devices` command). Thus if you plug in multiple different phones, tablets, [TVs](https://alexilyenko.github.io/androidtv-automated-tests/) and start various emulators, you'll get great diversity of the targets.

Be sure to unplug all not needed for tests devices and shutdown all non-target emulators before executing Spoon's tasks.
{: .notice--info}

```sh
./gradlew spoon
```

At this point our tests will be sharded across all connected Android devices and emulators.

{% include figure image_path="/assets/images/parallel.gif" alt="Spoon test sharding on Android emulators" caption="Spoon test sharding on Android emulators" %}
## Test reports
Besides being convenient and easy-to-use tool for parallel test run, Spoon's also got some additional functionality, which might be useful for Test Developers.

Once all tests have been completed, an HTML report will be generated with detailed info about tests and devices they were run on. Thanks to the high level data in reports we can determine right-away if the failure is specific to some device or to all of them. Also it provides device logs and optional screenshots.

{% include figure image_path="/assets/images/device_view.png" alt="Parallel Android tests with Spoon" caption="Device View" %}
{% include figure image_path="/assets/images/test_view.png" alt="Spoon test sharding on Android emulators" caption="Test View" %}

## Screenshots
As I said before Spoon allows us to snap screenshots at any points while test is executed. Later they will be automatically included into test report HTML. This can visualize test execution and point to the potential bugs in your app.

To be able to take screenshots we'll need to include Spoon dependency to app's `build.gradle`:
```groovy
dependencies {
 androidTestCompile 'com.squareup.spoon:spoon-client:1.7.1'
}
```
Furthermore since Spoon stores all taken screenshot in the device's memory card, we'll have to enable write storage privileges for our test app. This can be done in `AndroidManifest.xml`, which can be found under `main` folder in your project directory.
```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 package="io.github.alexilyenko.sample">
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <!-- Rest of the Manifest goes below -->
</manifest>
```

Now all we have to do is to invoke static method `Spoon#screenshot` in our tests like this:
```kotlin
Spoon.screenshot(activity, screenshotName, testClassName, testMethodName)
```
Full example of invocation along with the retrieval of current activity can be found in [GitHub repository](https://github.com/alexilyenko/SimpleAndroidCalculator/blob/master/app/src/androidTest/kotlin/io/github/alexilyenko/sample/pageobject/tests/BaseTest.kt). All examples are written in Kotlin, hence if you haven't heard about this programming language I recommend to read my post about [Android Tests in Kotlin](https://alexilyenko.github.io/kotlin-android-tests/).

[](https://alexilyenko.github.io/)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Editor
{
    /// <summary>
    /// Unity has a strange bug when it tries to import a DLL with a ScriptedImporter and an asset that importer is targeting.
    /// The first time, it will not invoke the ScriptedImporter as it's just being imported itself; the second time the ScriptedImporter will be constructed but Unity thinks it fails.
    /// The third time, the import will succeed. This class will invoke the third time import for .gltf, .glb and .room extensions.
    /// </summary>
    public class ScriptedImporterAssetReimporter : AssetPostprocessor
    {
        private static readonly Dictionary<string, int> assetsAttemptedToReimport = new Dictionary<string, int>();

        public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            foreach (string asset in importedAssets)
            {
                string extension = Path.GetExtension(asset);
                if (extension == ".room" || extension == ".glb" || extension == ".gltf")
                {
                    Type assetType = AssetDatabase.GetMainAssetTypeAtPath(asset);
                    if (assetType == typeof(DefaultAsset))
                    {
                        if (!assetsAttemptedToReimport.TryGetValue(asset, out int numAttempts))
                        {
                            numAttempts = 0;
                        }

                        assetsAttemptedToReimport[asset] = ++numAttempts;

                        if (numAttempts <= 3)
                        {
                            Debug.LogWarning($"Asset '{asset}' appears to have failed importing, will attempt to re-import. Attempt: {numAttempts}");
                            AssetDatabase.ImportAsset(asset);
                        }
                        else
                        {
                            Debug.LogWarning($"Asset '{asset}' appears to have failed the re-import 3 times, will not try again.");
                        }
                    }
                }
            }
        }
    }
}