text:
<?php
namespace Test\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Proxy\Exception\InvalidArgumentException;

/** @ORM\Entity */
class Service {

    public static $TYPE_OTRS = "OTRS";

    /**
	 * @ORM\Id
	 * @ORM\GeneratedValue(strategy="AUTO")
	 * @ORM\Column(type="integer")
	 */
	protected $id;

	/** @ORM\Column(type="string", length=255, unique=true) */
	protected $company;

	/** @ORM\Column(type="string", length=255) */
	protected $type;

	/** @ORM\Column(type="string", length=255) */
	protected $location;

	/** @ORM\Column(type="string", length=255) */
	protected $username;

	/** @ORM\Column(type="string", length=255) */
	protected $password;

	/** @ORM\Column(type="string", length=255) */
	protected $namespace;

	public function getId(){
	    return $this->id;
	}

    public function setId($id){
    	$this->id = $id;
    }

    public function getCompany(){
    	return $this->company;
    }

    public function setCompany($company){
    	$this->company = $company;
    }

    public function getType(){
    	return $this->type;
    }

    public function setType($type){
        if (!in_array($type, [self::TYPE_OTRS])) {
        	throw new InvalidArgumentException("Invalid type");
        }
    	$this->type = $type;
    }
    public function getLocation(){
    	return $this->location;
    }

    public function setLocation($location){
    	$this->location = $location;
    }
    public function getUsername(){
    	return $this->username;
    }

    public function setUsername($username){
    	$this->username = $username;
    }
    public function getPassword(){
    	return $this->password;
    }

    public function setPassword($password){
    	$this->password = $password;
    }

    public function getNamespace(){
    	return $this->namespace;
    }

    public function setNamespace($namespace){
    	$this->namespace = $namespace;
    }
}


text:
import React from 'react';
import {Html} from 'slate';

const BLOCK_TAGS = {
  p: 'paragraph',
  ul: 'unordered-list',
  li: 'list-item',
  ol: 'ordered-list',
  img: 'image',
};

const MARK_TAGS = {
  em: 'italic',
  strong: 'bold',
  u: 'underline',
};

const INLINE_TAGS = {
  a: 'link',
};

const rules = [
  {
    deserialize(el, next) {
      const type = BLOCK_TAGS[el.tagName];
      if (!type) {
        return;
      }

      const data = {};
      switch (type) {
        case 'image': {
          data.src = el.attribs.src;
          break;
        }
        default: break;
      }

      return {
        kind: 'block',
        type,
        data,
        nodes: next(el.children)
      };
    },
    serialize(object, children) {
      if (object.kind !== 'block') {
        return;
      }

      switch (object.type) {
        case 'paragraph': return
{children}
;
        case 'list-item': return
{children}
;
        case 'ordered-list': return
{children}
;
        case 'unordered-list': return
{children}
;//data-hook="editor-image"
        case 'image': return ;
        default: return {children};
      }
    }
  },
  {
    deserialize(el, next) {
      const type = MARK_TAGS[el.tagName];
      if (!type) {
        return;
      }

      return {
        kind: 'mark',
        type,
        nodes: next(el.children)
      };
    },
    serialize(object, children) {
      if (object.kind !== 'mark') {
        return;
      }

      switch (object.type) {
        case 'bold': return {children};
        case 'italic': return {children};
        case 'underline': return {children};
        default: return {children};
      }
    }
  },
  {
    deserialize(el, next) {
      const type = INLINE_TAGS[el.tagName];
      if (!type) {
        return;
      }

      return {
        kind: 'inline',
        type,
        data: {
          href: el.attribs.href
        },
        nodes: next(el.children)
      };
    },
    serialize(object, children) {
      if (object.kind !== 'inline') {
        return;
      }

      switch (object.type) {
        case 'link': return {children};
        default: return {children};
      }
    }
  }
];

export default new Html({rules});

redpajama_set_name: RedPajamaGithub


text:
package org.ode4j.ode;

import org.ode4j.math.DVector3;
import org.ode4j.math.DVector3C;

public interface DLMotorJoint extends DJoint {

	/**
	 * Set the number of axes that will be controlled by the LMotor.
	 * @param num can range from 0 (which effectively deactivates the joint) to 3.
	 */
	void setNumAxes (int num);

	/**
	 * Get nr of axes.
	 */
	int getNumAxes();

	/**
	 * Set the AMotor axes.
	 *
	 * <p> REMARK: The axis vector is always specified in global coordinates
	 * regardless of the setting of rel.
	 *
	 * @param anum selects the axis to change (0,1 or 2).
	 * @param rel Each axis can have one of three ``relative orientation'' modes
	 * <li> 0: The axis is anchored to the global frame.
	 * <li> 1: The axis is anchored to the first body.
	 * <li> 2: The axis is anchored to the second body.
	 */
	void setAxis (int anum, int rel, double x, double y, double z);

	/**
	 * Set the AMotor axes.
	 * <p> REMARK: The axis vector is always specified in global coordinates
	 * regardless of the setting of rel.
	 *
	 * @param anum selects the axis to change (0,1 or 2).
	 * @param rel Each axis can have one of three ``relative orientation'' modes
	 * <li> 0: The axis is anchored to the global frame.
	 * <li> 1: The axis is anchored to the first body.
	 * <li> 2: The axis is anchored to the second body.
	 */
	void setAxis (int anum, int rel, DVector3C a);

	/**
	 * Get axis.
	 */
	void getAxis (int anum, DVector3 result);

	/**
	 * Set joint parameter.
	 */
	@Override
	void setParam (PARAM_N parameter, double value);

	/**
	 * Get joint parameter.
	 */
	@Override
	double getParam (PARAM_N parameter);

	double getParamVel();
	double getParamVel2();
	double getParamVel3();
	double getParamFMax();
	double getParamFMax2();
	double getParamFMax3();
	void setParamVel(double d);
	void setParamVel2(double d);
	void setParamVel3(double d);
	void setParamFMax(double d);
	void setParamFMax2(double d);
	void setParamFMax3(double d);

}


text:
<?php

class Ktest extends \Eloquent {
	protected $fillable = [];
	public function college(){
    return $this->belongsTo('College','co_id');
    }
	public function student(){
    return $this->belongsTo('Student','stuid');
    }
}


text:
<template id="button-template">
    <style>
/* Styles adapted from Yahoo's Pure CSS Library
 * github.com/yahoo/pure
 * (Yahoo! Inc. BSD License)
 */
:host {
  /* Structure */
  display: inline-block;
  *display: inline;
  /*IE 6/7*/
  zoom: 1;
  line-height: normal;
  white-space: nowrap;
  vertical-align: baseline;
  text-align: center;
  cursor: pointer;
  -webkit-user-drag: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none; }

/* Firefox: Get rid of the inner focus border */
:host(::-moz-focus-inner) {
  padding: 0;
  border: 0; }

/*csslint outline-none:false*/
:host {
  font-family: inherit;
  font-size: 100%;
  *font-size: 90%;
  /*IE 6/7 - To reduce IE's oversized button text*/
  *overflow: visible;
  /*IE 6/7 - Because of IE's overly large left/right padding on buttons */
  padding: 0.5em 1em;
  color: #444;
  /* rgba not supported (IE 8) */
  color: rgba(0, 0, 0, 0.8);
  /* rgba supported */
  *color: #444;
  /* IE 6 & 7 */
  border: 1px solid #999;
  /*IE 6/7/8*/
  border: none transparent;
  /*IE9 + everything else*/
  background-color: #E6E6E6;
  text-decoration: none;
  border-radius: 2px; }

:host(:hover),
:host(:focus) {
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#1a000000',GradientType=0);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(transparent), color-stop(40%, rgba(0, 0, 0, 0.05)), to(rgba(0, 0, 0, 0.1)));
  background-image: -webkit-linear-gradient(transparent, rgba(0, 0, 0, 0.05) 40%, rgba(0, 0, 0, 0.1));
  background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.05) 0%, rgba(0, 0, 0, 0.1));
  background-image: -o-linear-gradient(transparent, rgba(0, 0, 0, 0.05) 40%, rgba(0, 0, 0, 0.1));
  background-image: linear-gradient(transparent, rgba(0, 0, 0, 0.05) 40%, rgba(0, 0, 0, 0.1)); }

:host(:focus) {
  outline: 0; }

:host(:active) {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15) inset, 0 0 6px rgba(0, 0, 0, 0.2) inset; }

:host([disabled]),
:host([disabled]:hover),
:host([disabled]:focus),
:host([disabled]:active) {
  border: none;
  background-image: none;
  filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
  filter: alpha(opacity=40);
  -khtml-opacity: 0.40;
  -moz-opacity: 0.40;
  opacity: 0.40;
  cursor: not-allowed;
  box-shadow: none; }

/* Firefox: Get rid of the inner focus border */
:host(::-moz-focus-inner) {
  padding: 0;
  border: 0; }

:host(.primary),
:host(.selected),
:host(a.primary),
:host(a.selected) {
  background-color: #0078e7;
  color: #fff; }

</style>
    <content></content>
</template>
<script type="text/javascript" src="pure-button.js"></script>


text:
"""Define and extend configuration settings for your application.
"""

import os
from imcrypt.config.routes import routes  # noqa
from imcrypt.config.dependencies import dependencies  # noqa

debug = {
    'enabled': os.environ.get('DEV_ENV', False)
}


text:
function out = onlineFilterTrials_v2(varargin)
% provide filtering fields and values as parameter-value pairs via varargin
% each pair is a field of structure, BpodSystem.Data
% data types can be numeric or cell arrays of strings

    global BpodSystem

    out = ones(size(BpodSystem.Data.(varargin{1}))); % assuming that you'll always have TrialTypes
    %%
        counter = 1;
    while counter+1 <= length(varargin)
        field = varargin{counter};
        val = varargin{counter+1};
        theseMatches = ismember(BpodSystem.Data.(field), val);
        if isempty(theseMatches)
            warning('*** no matches found ***');
        end
        out = out & theseMatches;
        counter=counter+2;
    end


text:
This directory contains the definition of the Java builder.

## Build the Image
To build the builder image, run:

```bash
bazel build //builders/java:builder.image
```

## Build a Test Application
To build the sample application [gomod_go_sum](../testdata/java/), run:

```bash
pack build sample-java --builder gcp/java --path <path to java app> --trust-builder -v
```

## Acceptance Tests
To run the acceptance tests across all the products, run:

```bash
bazel test //builders/java/acceptance:acceptance_test
```

### Test a Single Product
For each product, there exists a suite of tests. The build target is
`builders/go/acceptance:<product>_test`. Where `<product>` is replaced with the
acronym of the product. For example, to run the tests for Google Cloud
Functions, run:

```bash
bazel test //builders/java/acceptance:gcf_test
```


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

using System.IO;

namespace Microsoft.Common.Core.IO {
    internal sealed class FileSystemWatcherProxy : IFileSystemWatcher {
        private readonly FileSystemWatcher _fileSystemWatcher;

        public FileSystemWatcherProxy(string path, string filter) {
            _fileSystemWatcher = new FileSystemWatcher(path, filter);
        }

        public void Dispose() {
            _fileSystemWatcher.Dispose();
        }

        public bool EnableRaisingEvents {
            get { return _fileSystemWatcher.EnableRaisingEvents; }
            set { _fileSystemWatcher.EnableRaisingEvents = value; }
        }

        public bool IncludeSubdirectories {
            get { return _fileSystemWatcher.IncludeSubdirectories; }
            set { _fileSystemWatcher.IncludeSubdirectories = value; }
        }

        public int InternalBufferSize {
            get { return _fileSystemWatcher.InternalBufferSize; }
            set { _fileSystemWatcher.InternalBufferSize = value; }
        }

        public NotifyFilters NotifyFilter {
            get { return _fileSystemWatcher.NotifyFilter; }
            set { _fileSystemWatcher.NotifyFilter = value; }
        }

        public event FileSystemEventHandler Changed {
            add { _fileSystemWatcher.Changed += value; }
            remove { _fileSystemWatcher.Changed -= value; }
        }

        public event FileSystemEventHandler Created {
            add { _fileSystemWatcher.Created += value; }
            remove { _fileSystemWatcher.Created -= value; }
        }

        public event FileSystemEventHandler Deleted {
            add { _fileSystemWatcher.Deleted += value; }
            remove { _fileSystemWatcher.Deleted -= value; }
        }

        public event RenamedEventHandler Renamed {
            add { _fileSystemWatcher.Renamed += value; }
            remove { _fileSystemWatcher.Renamed -= value; }
        }

        public event ErrorEventHandler Error {
            add { _fileSystemWatcher.Error += value; }
            remove { _fileSystemWatcher.Error -= value; }
        }
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
xjt.workflow.exe 类分层结构
</TITLE>

<META NAME="date" CONTENT="2012-03-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      概述
      软件包
      类
      使用
    树
      已过时
      索引
      帮助

 上一个
 下一个

  框架
 无框架

  所有类

软件包 xjt.workflow.exe 的分层结构

软件包分层结构:
所有软件包

类分层结构

java.lang.Object

org.springframework.dao.support.DaoSupport (implements org.springframework.beans.factory.InitializingBean)

org.springframework.orm.hibernate3.support.HibernateDaoSupport

gov.gdgs.common.database.hibernate.AbstractHibernateDAO

xjt.workflow.exe.OverTimeHandler

xjt.workflow.exe.ExecutionContext
xjt.workflow.exe.Job (implements java.io.Serializable)

xjt.workflow.exe.Token (implements java.io.Serializable)

xjt.workflow.exe.Variable (implements java.io.Serializable)

xjt.workflow.exe.WorkFlowInstance (implements java.io.Serializable)

xjt.workflow.exe.WorkItemInstance (implements java.io.Serializable)

xjt.workflow.exe.WorkItemOwner (implements java.io.Serializable)

接口分层结构

xjt.workflow.exe.ActionHandler
xjt.workflow.exe.DecisionHandler

      概述
      软件包
      类
      使用
    树
      已过时
      索引
      帮助

 上一个
 下一个

  框架
 无框架

  所有类


text:
{% extends "proceedings/proceedings_template.html" %}

{% block content %}

{% include "includes/proceeding_title.html" %}

IRTF Mission

To promote research of importance to the evolution of the future Internet by
	  creating focused, long-term and small Research Groups working on topics related to
	  Internet protocols, applications, architecture and technology.

IRTF Research Groups

The Internet Research Task Force is composed of a number
of small Research Groups. Research Groups are usually focussed and long term, though short lived "task force" like Research Groups are possible.

IRTF Overview

	  The Research Groups work on topics related to
	  Internet protocols, applications, architecture and technology. Research Groups are
	  expected to have the stable long term (with respect to the lifetime of the Research Group) membership needed to promote the development of
	  research collaboration and teamwork in exploring research issues. Participation is by
	  individual contributors, rather than by representatives of organizations.

The IRTF is managed by the IRTF Chair in consultation with the Internet Research
	  Steering Group (IRSG). The IRSG membership includes the IRTF Chair, the chairs of the
	  various Research Group and possibly other individuals ("members at large") from
	  the research community.

The IRTF Chair is appointed by the Internet
	  Architecture Board (IAB), the Research Group chairs are appointed as part of the
	  formation of Research Groups and the IRSG members at large are chosen by the IRTF Chair in
	  consultation with the rest of the IRSG and on approval of the IAB. In addition to managing
	  the Research Groups, the IRSG may from time to time hold topical workshops focusing on
	  research areas of importance to the evolution of the Internet, or more general workshops
	  to, for example, discuss research priorities from an Internet perspective.

The IRTF Research Groups guidelines and procedures are described more fully in
	  RFC 2014 (BCP 8).

Mail Lists

Each IRTF Research Group maintains one or more open mailing lists.
	    Information on these lists is available on the individual research
	    group's pages.

The IRTF
	    Announce list receive notices of IRTF Research Group creation
	    and termination, document publication, invitations for feedback and
	    participation, and other IRTF activities.

Sponsors

The IRTF gratefully acknowledges support from the following organizations:

The Internet Engineering Task Force (IETF)

The Internet Society (ISOC)

IRTF Chair

{{ irtf_chair.person }} currently serves as IRTF Chair; he can
	    be reached at irtf-chair@irtf.org.

{% endblock %}


text:
<?php

namespace PHPCI\Plugin;

use PHPCI\Builder;
use PHPCI\Model\Build;

/**
 * XMPP Notification - Send notification for successful or failure build.
 *
 * @author       Alexandre Russo <dev.github@ange7.com>
 */
class Xmpp implements \PHPCI\Plugin
{
    protected $directory;
    protected $phpci;
    protected $build;

    /**
     * @var string, username of sender account xmpp
     */
    protected $username;

    /**
     * @var string, alias server of sender account xmpp
     */
    protected $server;

    /**
     * @var string, password of sender account xmpp
     */
    protected $password;

    /**
     * @var string, alias for sender
     */
    protected $alias;

    /**
     * @var string, use tls
     */
    protected $tls;

    /**
     * @var array, list of recipients xmpp accounts
     */
    protected $recipients;

    /**
     * @var string, mask to format date
     */
    protected $date_format;

    /**
     * @param Builder $phpci
     * @param Build   $build
     * @param array   $options
     */
    public function __construct(Builder $phpci, Build $build, array $options = array())
    {
        $this->phpci = $phpci;
        $this->build = $build;

        $this->username = '';
        $this->password = '';
        $this->server = '';
        $this->alias = '';
        $this->recipients = array();
        $this->tls = false;
        $this->date_format = '%c';

        /*
         * Set recipients list
         */
        if (!empty($options['recipients'])) {
            if (is_string($options['recipients'])) {
                $this->recipients = array($options['recipients']);
            } elseif (is_array($options['recipients'])) {
                $this->recipients = $options['recipients'];
            }
        }

        $this->setOptions($options);
    }

    /**
     * Set options configuration for plugin.
     *
     * @param array $options
     */
    protected function setOptions($options)
    {
        foreach (array('username', 'password', 'alias', 'tls', 'server', 'date_format') as $key) {
            if (array_key_exists($key, $options)) {
                $this->{$key} = $options[$key];
            }
        }
    }

    /**
     * Get config format for sendxmpp config file.
     *
     * @return string
     */
    protected function getConfigFormat()
    {
        $conf = $this->username;
        if (!empty($this->server)) {
            $conf .= ';'.$this->server;
        }

        $conf .= ' '.$this->password;

        if (!empty($this->alias)) {
            $conf .= ' '.$this->alias;
        }

        return $conf;
    }

    /**
     * Find config file for sendxmpp binary (default is .sendxmpprc).
     */
    public function findConfigFile()
    {
        if (file_exists($this->phpci->buildPath.DIRECTORY_SEPARATOR.'.sendxmpprc')) {
            if (md5(file_get_contents($this->phpci->buildPath.DIRECTORY_SEPARATOR.'.sendxmpprc'))
                !== md5($this->getConfigFormat())) {
                return;
            }

            return true;
        }

        return;
    }

    /**
     * Send notification message.
     */
    public function execute()
    {
        $sendxmpp = $this->phpci->findBinary('sendxmpp');

        /*
         * Without recipients we can't send notification
         */
        if (count($this->recipients) == 0) {
            return false;
        }

        /*
         * Try to build conf file
         */
        $config_file = $this->phpci->buildPath.DIRECTORY_SEPARATOR.'.sendxmpprc';
        if (is_null($this->findConfigFile())) {
            file_put_contents($config_file, $this->getConfigFormat());
            chmod($config_file, 0600);
        }

        /*
         * Enabled ssl for connection
         */
        $tls = '';
        if ($this->tls) {
            $tls = ' -t';
        }

        $message_file = $this->phpci->buildPath.DIRECTORY_SEPARATOR.uniqid('xmppmessage');
        if ($this->buildMessage($message_file) === false) {
            return false;
        }

        /*
         * Send XMPP notification for all recipients
         */
        $cmd = $sendxmpp.'%s -f %s -m %s %s';
        $recipients = implode(' ', $this->recipients);

        $success = $this->phpci->executeCommand($cmd, $tls, $config_file, $message_file, $recipients);

        echo $this->phpci->getLastOutput();

        /*
         * Remove temp message file
         */
        $this->phpci->executeCommand('rm -rf '.$message_file);

        return $success;
    }

    /**
     * @param $message_file
     *
     * @return int
     */
    protected function buildMessage($message_file)
    {
        if ($this->build->isSuccessful()) {
            $message = '✔ ['.$this->build->getProjectTitle().'] Build #'.$this->build->getId().' successful';
        } else {
            $message = '✘ ['.$this->build->getProjectTitle().'] Build #'.$this->build->getId().' failure';
        }

        $message .= ' ('.strftime($this->date_format).')';

        return file_put_contents($message_file, $message);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.easemob.easeui.widget.EaseChatPrimaryMenu xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/primary_menu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" /><!-- From: file:/Users/Logan/development/android/as_workspace/EaseChatDemo/easeUI/src/main/res/layout/ease_layout_chat_primary_menu.xml -->


text:
#ifndef BOOST_FUSION_ADAPTED_ADT_HPP
#define BOOST_FUSION_ADAPTED_ADT_HPP

#include <lslboost/fusion/adapted/adt/adapt_assoc_adt_named.hpp>
#include <lslboost/fusion/adapted/adt/adapt_assoc_adt.hpp>
#include <lslboost/fusion/adapted/adt/adapt_adt_named.hpp>
#include <lslboost/fusion/adapted/adt/adapt_adt.hpp>

#endif


text:
"""
:Author Patrik Valkovic
:Created 28.08.2017 14:37
:Licence MIT
Part of grammpy

"""
from unittest import TestCase, main
from grammpy import *
from grammpy.parsers import cyk
from grammpy.transforms import ContextFree, InverseContextFree

class S(Nonterminal): pass
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class RuleSABC(Rule):
    rule = ([S], [A, B, C])
class RuleA0(Rule):
    rule = ([A], [0])
class RuleB1(Rule):
    rule = ([B], [1])
class RuleC2(Rule):
    rule = ([C], [2])

class OneRuleWithMultipleNonterminalsTest(TestCase):
    def test_transform(self):
        g = Grammar(terminals=[0, 1, 2],
                    nonterminals=[S, A, B, C],
                    rules=[RuleSABC, RuleA0, RuleB1, RuleC2],
                    start_symbol=S)
        com = ContextFree.transform_to_chomsky_normal_form(g)
        pars = cyk(com, [0, 1, 2])
        trans = InverseContextFree.transform_from_chomsky_normal_form(pars)
        self.assertIsInstance(trans, S)
        self.assertIsInstance(trans.to_rule, RuleSABC)
        a = trans.to_rule.to_symbols[0]
        b = trans.to_rule.to_symbols[1]
        c = trans.to_rule.to_symbols[2]
        self.assertIsInstance(a, A)
        self.assertIsInstance(a.to_rule, RuleA0)
        self.assertIsInstance(a.to_rule.to_symbols[0], Terminal)
        self.assertEqual(a.to_rule.to_symbols[0].s, 0)
        self.assertIsInstance(b, B)
        self.assertIsInstance(b.to_rule, RuleB1)
        self.assertIsInstance(b.to_rule.to_symbols[0], Terminal)
        self.assertEqual(b.to_rule.to_symbols[0].s, 1)
        self.assertIsInstance(c, C)
        self.assertIsInstance(c.to_rule, RuleC2)
        self.assertIsInstance(c.to_rule.to_symbols[0], Terminal)
        self.assertEqual(c.to_rule.to_symbols[0].s, 2)

if __name__ == '__main__':
    main()


text:
package net.automatalib.modelchecking.lasso;

import java.util.SortedSet;
import java.util.TreeSet;

import net.automatalib.words.Alphabet;
import net.automatalib.words.Word;
import net.automatalib.words.impl.Alphabets;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * Tests whether lassos are constructed correctly for any automaton.
 *
 * @param <L> the {@link AbstractLasso} type to test.
 *
 * @author Jeroen Meijer
 */
public abstract class AbstractLassoTest<L extends AbstractLasso<String, ?>> {

    private final Alphabet<String> alphabet = Alphabets.singleton("a");

    private L lasso1;
    private L lasso2;
    private L lasso3;

    protected abstract L getLasso(Word<String> prefix, Word<String> loop, int unfoldTimes);

    public Alphabet<String> getAlphabet() {
        return alphabet;
    }

    @BeforeClass
    public void setUp() {
        lasso1 = getLasso(Word.epsilon(), Word.fromSymbols("a"), 1);
        lasso2 = getLasso(Word.fromSymbols("a"), Word.fromSymbols("a"), 1);
        lasso3 = getLasso(Word.fromSymbols("a"), Word.fromSymbols("a", "a"), 1);
    }

    @Test
    public void testGetWord() {
        Assert.assertEquals(lasso1.getWord(), Word.fromSymbols("a"));
        Assert.assertEquals(lasso2.getWord(), Word.fromSymbols("a", "a"));
        Assert.assertEquals(lasso3.getWord(), Word.fromSymbols("a", "a", "a"));
    }

    @Test
    public void testGetLoop() {
        Assert.assertEquals(lasso1.getLoop(), Word.fromSymbols("a"));
        Assert.assertEquals(lasso2.getLoop(), Word.fromSymbols("a"));
        Assert.assertEquals(lasso3.getLoop(), Word.fromSymbols("a", "a"));
    }

    @Test
    public void testGetPrefix() {
        Assert.assertEquals(lasso1.getPrefix(), Word.epsilon());
        Assert.assertEquals(lasso2.getPrefix(), Word.fromSymbols("a"));
        Assert.assertEquals(lasso3.getPrefix(), Word.fromSymbols("a"));
    }

    @Test
    public void testGetLoopBeginIndices() {
        final SortedSet<Integer> indices = new TreeSet<>();
        indices.add(0);
        indices.add(1);
        Assert.assertEquals(lasso1.getLoopBeginIndices(), indices);

        indices.clear();
        indices.add(1);
        indices.add(2);
        Assert.assertEquals(lasso2.getLoopBeginIndices(), indices);

        indices.clear();
        indices.add(1);
        indices.add(3);
        Assert.assertEquals(lasso3.getLoopBeginIndices(), indices);
    }

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ark. Bot. 23A(4 (14)): 22 (1931)

#### Original name
Burrillia limnanthemi Cif., 1931

### Remarks
null


text:
package com.github.zouzhberk.cli.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER })
public @interface Param {
	String sname() default "";

	String value();

	String desc() default "";

	boolean required() default false;

}


text:
package com.streamsets.datacollector.execution;

import com.streamsets.pipeline.api.ExecutionMode;

import java.util.Map;

public interface PipelineState {

  public String getUser();

  public String getName();

  public String getRev();

  public long getTimeStamp();

  public PipelineStatus getStatus();

  public String getMessage();

  public Map<String, Object> getAttributes();

  public ExecutionMode getExecutionMode();

  public String getMetrics();

  public int getRetryAttempt();

  public long getNextRetryTimeStamp();

}


text:
package org.lnu.is.converter.broadcasting;

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

import org.lnu.is.annotations.Converter;
import org.lnu.is.converter.AbstractConverter;
import org.lnu.is.domain.broadcasting.BroadcastingMessage;
import org.lnu.is.domain.group.Group;
import org.lnu.is.resource.broadcasting.BroadcastingMessageResource;

/**
 * Broadcasting Resource Converter.
 * @author ivanursul
 *
 */
@Converter("broadcastingResourceConverter")
public class BroadcastingResourceConverter extends AbstractConverter<BroadcastingMessageResource, BroadcastingMessage> {

	@Override
	public BroadcastingMessage convert(final BroadcastingMessageResource source, final BroadcastingMessage target) {

		target.setContent(source.getContent());
		target.setTopic(source.getTopic());
		target.setRecipients(source.getRecipients());

		if (source.getGroups() != null) {
			List<Group> groups = convertGroups(source);
			target.setGroups(groups);
		}

		return target;
	}

	/**
	 * Method for converting list of groups.
	 * @param source
	 * @return groups.
	 */
	private List<Group> convertGroups(final BroadcastingMessageResource source) {
		List<Group> groups = new ArrayList<Group>();

		for (Long groupId: source.getGroups()) {
			Group group = new Group();
			group.setId(groupId);
			groups.add(group);
		}
		return groups;
	}

	@Override
	public BroadcastingMessage convert(final BroadcastingMessageResource source) {
		return convert(source, new BroadcastingMessage());
	}

}


text:
import {DataInput, DataOutput} from './Data';
import {PortableWriter, PortableReader} from './portable/PortableSerializer';
export interface IdentifiedDataSerializable {
    readData(input: DataInput): any;
    writeData(output: DataOutput): void;
    getFactoryId(): number;
    getClassId(): number;
}

export interface IdentifiedDataSerializableFactory {
    create(type: number): IdentifiedDataSerializable;
}

export interface Portable {
    getFactoryId(): number;
    getClassId(): number;
    writePortable(writer: PortableWriter): void;
    readPortable(reader: PortableReader): void;
}

export interface VersionedPortable extends Portable {
    getVersion(): number;
}

export interface PortableFactory {
    create(classId: number): Portable;
}


text:
/**
Archivo encargado de realizar todas las peticiones a API https://coimco.herokuapp.com
*/
import { Injectable } from '@angular/core';
import { Http, Jsonp, Headers, Response, RequestOptions, Request, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ChartsAPI {
  token: JSON;
  data_json: any;

  constructor(private http: Http, private jsonp: Jsonp) {
    this.token = JSON.parse(localStorage.getItem('tokenUser'));
  }
  /**
  * @returns  HEADERS de la conexión con API.{Authorization and Accept}.
  */
  createHeaders(): any {
    const auth = `Bearer ${this.token}`;
    const headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Authorization', auth);
    const options = new RequestOptions({ 'headers': headers });
    return options;
  }
  /**
  * @param filter filtros utilizado para la petición a la base de datos
  * @returns body del mensaje (filtro) enviado a la API
  */
  createBody(filter: JSON): any {
    const start = filter['start'] + 'T10:00:00Z';
    const end = filter['end'] + 'T10:00:00Z';
    let body = JSON.stringify({ start: start, end: end });
    return body;
  }

  /**
  * @param filtro con fechas y la cantidad 'k' de muestras a retornar por API.
  * @returns Observable de la conexión dentro de este se encuentran las 'k' muestras solicitadas
   */
  getBestSeller(filter: JSON) {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const url = 'https://coimco.herokuapp.com/api/productsrank-k/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega los k productos más vendidos por categoría
  * @param filtro con fechas, la cantidad 'k' y la categoría de productos de muestras a retornar por API.
  * @returns Observable de la conexión dentro de este se encuentran las 'k' muestras solicitadas
   */
  getRankCategory(filter: JSON): Observable<JSON[]> {

    const category = filter['category'];
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    const url = 'https://coimco.herokuapp.com/api/productsrank-cs/' + k + '/' + category;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega los k productos más vendidos por marca
  * @param filtro con fechas, la cantidad 'k' y la marca de productos de muestras a retornar por API.
  * @returns Observable de la conexión dentro de este se encuentran las 'k' muestras solicitadas
   */
  getRankBran(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const brand = filter['brand'];
    let k;
    for (var ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/productsrank-b/' + k + '/' + brand;
    let body = this.createBody(filter);
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));

  }
  //METHOD USING IN searcherProduct.component
  /** Método que entrega todos los productos
  * @returns Observable de la conexión dentro de este se encuentran todos los productos.
   */
  getProducts(): Observable<JSON[]> {
    const headers = this.createHeaders();
    const url = 'http://coimco.herokuapp.com/api/products';
    return this.http.get(url, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el historial de venta de un producto
  * @param filtro con fechas y id del producto que se desea consultar.
  * @returns Observable de la conexión dentro de este se encuentran las ventas del producto.
   */
  getProductSales(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();

    const id = filter['id'];
    const url = 'https://coimco.herokuapp.com/api/productsrec/' + id;
    let body = this.createBody(filter);
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el precio de venta de producto elegido
  * @param filtro con fechas y el id del producto que se desea consultar.
  * @returns Observable de la conexión dentro de este se encuentra la fecha y precio de venta del producto elegido.
   */
  getProductPrice(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const id = filter['id'];
    const url = 'https://coimco.herokuapp.com/api/salesrec-p/' + id;
    let body = this.createBody(filter);
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de proveedores, con información de estos, y el precio al que venden del producto elegido.
  * @param filtro con fechas y id del producto elegido.
  * @returns Observable de la conexión dentro de este se encuentra la información de los proveedores del producto elegido.
   */
  getRankPPrice(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const id = filter['id'];
    const url = 'https://coimco.herokuapp.com/api/productsrank-pp/' + id;
    let body = this.createBody(filter);

    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  /** Método que entrega el precio de compra de producto elegido
  * @param filtro con fechas y el id del producto que se desea consultar.
  * @returns Observable de la conexión dentro de este se encuentra la fecha y precio de compra del producto elegido.
   */
  getProductPriceTime(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const id = filter['id'];
    const url = 'https://coimco.herokuapp.com/api/salesrec-p/' + id;
    let body = this.createBody(filter);
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  /** Método que entrega todos los productos
  * @returns Observable de la conexión dentro de este se encuentran todos los productos.
   */
  getProviders(): Observable<JSON[]> {
    const headers = this.createHeaders();
    const url = 'http://coimco.herokuapp.com/api/providers';
    return this.http.get(url, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega las compras de un producto en el tiempo por categoria
  * @param filtro con fechas, los 'k' productos y la categoria del producto que se desea consultar.
  * @returns Observable de la conexión dentro de este se encuentra la fecha y el total de compras de los productos de la categoria elegida.
   */
  getRankProviderTime(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    console.log(filter);
    const id = filter['category'];
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/purchasesrank-cp/' + k + '/' + id;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de top 'k' compras.
  * @param filtro con fechas y las top 'k' compras.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del proveedor y producto, cantidad, precio y total acumulado de compra.
   */
  getRankPurchase(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/purchasesrank-k/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega los 'k' productos comprados al proveedor elegido.
  * @param filtro con fechas , los 'k' productos y el id del proveedor.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del producto y el precio.
   */
  getRankProviderPP(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    const k = filter['k'];
    const id = filter['id'];
    const url = 'http://coimco.herokuapp.com/api/providersrank-pp/' + k + '/' + id;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega los proveedores de mayor solicitud.
  * @param filtro con fechas y los 'k' proveedores.
  * @returns Observable de la conexión dentro de este se encuentra toda la información de contacto de proveedor.
   */
  getRankProviderP(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/providersrank-v/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega los 'k' productos más comprados por categoría.
  * @param filtro con fechas, los 'k' productos y el nombre de la categoria elegida.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del producto y la cantidad comprada.
   */
  getRankPurchaseC(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const category = filter['category'];
    const url = 'http://coimco.herokuapp.com/api/productsrank-cp/' + k + '/' + category;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /*** Método que entrega el ranking de 'k' proveedores por su tiempo de despacho.
  * @param filtro con fechas y  los 'k' proveedores
  * @returns Observable de la conexión dentro de este se encuentra el nombre del producto y la cantidad comprada.
   */
  getProviderTime(filter: JSON) {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/providersrank-k/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  /*** Método que entrega a todos los clientes
  * @returns Observable de la conexión dentro de este se encuentra el nombre y id de todos los clientes
   */
  getCustomers(): Observable<JSON[]> {
    const headers = this.createHeaders();
    const url = 'http://coimco.herokuapp.com/api/customers';
    return this.http.get(url, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el monto total ingresado por un cliente elegido.
  * @param filtro con fechas y  los 'k' proveedores
  * @returns Observable de la conexión dentro de este se encuentra el nombre y el total acumulado por ventas a el cliente elegido.
   */
  getCollected(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    //const k = filter['k'];
    const id = filter['id'];
    const url = 'http://coimco.herokuapp.com/api/customersrec-c/' + id;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /*** Método que entrega el ranking de productos comprados por el cliente elegido
  * @param filtro con fechas y el id del cliente elegido
  * @returns Observable de la conexión dentro de este se encuentra el nombre del product y el monto total comprado por el cliente.
   */
  getRankProductCustomer(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    //const k = filter['k'];
    const id = filter['id'];
    const url = 'http://coimco.herokuapp.com/api/customersrec-p/' + id;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega la frecuencia de compra del cliente en veces por mes
  * @param filtro con fechas y los 'k' clientes que se desean.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del cliente y la frequencia de compra en terminos de veces por mes
   */
  getFrequency(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    //const k = filter['k'];
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/customersrank-f/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de clientes por total ingresado por ventas
  * @param filtro con fechas y los 'k' clientes que se solicitan.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del cliente junto con el total de veces que compro y el total acumulado de dinero.
   */
  getRankCustomer(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var prop in filter) {
      if (prop === '[object Object]' && filter[prop]) {
        k = filter[prop];
      }
    }
    //const id = filter['id'];
    const url = 'http://coimco.herokuapp.com/api/customersrank-k/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de 'k' clientes que compraron los 'L' productos más vendidos de la empresa
  * @param filtro con fechas, los 'k' clientes que se solicitan y los 'L' produtos más vendidos.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del cliente, su rut y la cantidad comprada.
   */
  getCustomerBP(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    console.log(filter);
    let k;
    let l = '10';
    for (var ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/customersrank-p/' + k + '/' + l;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de 'k' productos por su rentabilidad.
  * @param filtro con fechas y los 'k' productos que se solicitan.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del producto y la rentabilidad de este.
   */
  getRankingCollected(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (let ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/productsrank-r/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de clientes por veces de compras y total acumulado ingresado
  * @param filtro con fechas y los 'k' clientes que se solicitan.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del cliente, el total de compras y el total acumulado de ingreso.
   */
  getRankTotalSale(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/customersrank-k/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de clientes por veces de compras
  * @param filtro con fechas y los 'k' clientes que se solicitan.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del cliente y el total de compras.
   */
  getCustomersByProduct(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);

    let k;
    for (var ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/customersrank-v/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de clientes por  monto total acumulado de compras.
  * @param filtro con fechas y los 'k' clientes que se solicitan.
  * @returns Observable de la conexión dentro de este se encuentra el nombre del cliente y el total acumulado por las compras.
   */
  getRankingSale(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/salesrank-k/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de 'k' productos vendidos por categoría.
  * @param filtro con fechas y los 'k' productos que se solicitan.
  * @returns Observable de la conexión dentro de este se encuentra el nombre de los productos y el total vendido.
   */
  getRankingSaleCategory(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const category = filter['category'];
    const url = 'http://coimco.herokuapp.com/api/salesrank-c/' + k + '/' + category;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el ranking de 'k' productos de mayor ingreso para la empresa
  * @param filtro con fechas y los 'k' productos que se solicitan.
  * @returns Observable de la conexión dentro de este se encuentra el nombre de los productos y el total ingresado.
   */
  getRankingSaleProduct(filter: JSON): Observable<JSON[]> {
    const headers = this.createHeaders();
    const body = this.createBody(filter);
    let k;
    for (var ix in filter) {
      if (ix === '[object Object]' && filter[ix]) {
        k = filter[ix];
      }
    }
    const url = 'http://coimco.herokuapp.com/api/salesrank-p/' + k;
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error:
        any) => Observable.throw(error.json().error || 'Server error'));
  }
  /** Método que entrega el monto total ingresado entre fechas elegidas.
  * @param filtro con fechas.
  * @returns Observable de la conexión dentro de este se encuentra el total ingresado por ventas.
   */
  getSalesRecord(): Observable<JSON[]> {
    const headers = this.createHeaders();
    const start = '2016-01-01T10:00:00Z';
    const end = '2017-06-01T10:00:00Z';
    const body = JSON.stringify({ start: start, end: end });
    //const body = this.createBody(filter);
    const url = 'http://coimco.herokuapp.com/api/sales-total';
    return this.http.post(url, body, headers)
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

}


text:
<?php
use Zend\ServiceManager\ServiceManager;

// Create a ServiceManager from service_manager config and register the merged config as a service
$config = include __DIR__ . '/config.php';
$config['service_manager']['services']['config'] = $config; // Save the config itself under the config key
$sm = new ServiceManager(isset($config['service_manager']) ? $config['service_manager'] : []);

// Return the fully configured ServiceManager
return $sm;


text:
INSERT INTO category (name)
VALUES
("Agriculture, Agroalimentaire"),
("Artisanat"),
("Audiovisuel, cinéma"),
("Automobile"),
("Banque, assurance"),
("Bâtiment, travaux publics"),
("Biologie, chimie, pharmacie"),
("Commerce, distribution"),
("Comptabilité, Secrétariat"),
("Création, métiers d'art"),
("Culture, patrimoine"),
("Défense, sécurité"),
("Droit"),
("Edition, livre"),
("Environnement"),
("Hôtellerie, restauration"),
("Immobilier"),
("Informatique, télécoms, Web"),
("Journalisme"),
("Langues"),
("Marketing, publicité"),
("Médical"),
("Mode, textile"),
("Psychologie"),
("Ressources humaines"),
("Spectacle, Métiers de la scène"),
("Sport"),
("Tourisme")


text:
package com.mediatek.mcstutorial;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.mediatek.mcs.Utils.UIUtils;
import com.mediatek.mcs.domain.McsDataChannel;
import com.mediatek.mcs.domain.McsResponse;
import com.mediatek.mcs.entity.DataChannelEntity;
import com.mediatek.mcs.entity.DataPointEntity;
import com.mediatek.mcs.entity.HistoryDataPointsEntity;
import com.mediatek.mcs.entity.api.DeviceInfoEntity;
import com.mediatek.mcs.entity.api.DeviceSummaryEntity;
import com.mediatek.mcs.net.McsJsonRequest;
import com.mediatek.mcs.net.RequestApi;
import com.mediatek.mcs.net.RequestManager;
import com.mediatek.mcs.socket.McsSocketListener;
import com.mediatek.mcs.socket.SocketManager;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Exchanger;
import java.util.concurrent.RunnableFuture;

import org.json.JSONException;
import org.json.JSONObject;

public class newActivity extends FragmentActivity {

    String mDeviceId = "";
    DeviceInfoEntity mDeviceInfo;
    McsDataChannel mDataChannel;
    TextView condition, comfort, health, all;
    ImageButton btn;
    Map<String, Float> data = new HashMap<String, Float>();

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private TimerTask timer;
    private Runnable runner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_request);
        this.condition = (TextView) findViewById((R.id.condition));
        this.comfort = (TextView) findViewById((R.id.comfort));
        this.health = (TextView) findViewById((R.id.health));
        this.all = (TextView) findViewById(R.id.all);
        btn = (ImageButton) findViewById(R.id.btn);
        final Intent intent = new Intent(newActivity.this, SessionActivity.class);
        startActivity(intent);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

        requestDevices();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                requestDeviceInfo(mDeviceId);
            }}, 2000);
//        Intent i = new Intent(newActivity.this, IntentServiceMCS.class);
//        Bundle b = new Bundle();
//        b.putString("id", mDeviceId);
//        i.putExtras(b);
//        startActivity(i);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               requestDeviceInfo(mDeviceId);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * GET device list.
     */
    private void requestDevices() {
        // Default method is GET
        int method = McsJsonRequest.Method.GET;
        String url = RequestApi.DEVICES;
        McsResponse.SuccessListener<JSONObject> successListener =
                new McsResponse.SuccessListener<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject response) {
                        List<DeviceSummaryEntity> summary = new Gson().fromJson(
                                response.toString(), DeviceSummaryEntity.class).getResults();

                        if (summary.size() > 0) {
                            mDeviceId = summary.get(0).getDeviceId();
                        }
                        //   printJson(response);
                    }
                };

        /**
         * Optional.
         * Default error message would be shown in logcat.
         */
        McsResponse.ErrorListener errorListener = new McsResponse.ErrorListener() {
            @Override
            public void onError(Exception e) {

            }
        };

        McsJsonRequest request = new McsJsonRequest(method, url, successListener, errorListener);
        RequestManager.sendInBackground(request);
    }

    /**
     * GET device info.
     */
    private void requestDeviceInfo(String deviceId) {
        McsJsonRequest request = new McsJsonRequest(
                RequestApi.DEVICE
                        .replace("{deviceId}", deviceId),
                new McsResponse.SuccessListener<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject response) {
                        mDeviceInfo = UIUtils.getFormattedGson()
                                .fromJson(response.toString(), DeviceInfoEntity.class)
                                .getResults().get(0);
                        List<DataChannelEntity> d = mDeviceInfo.getDataChannels();

                        if(d != null){
                            for(int i = 0; i < d.size(); i++){
                                if(d.get(i).getDataPoint() != null){
                                    String s = d.get(i).getDataChnId();
                                    float value = Float.valueOf(d.get(i).getDataPoint().getValues().getValue());
                                    data.put(s,value);

                                }
                            }
                        }

                        else Toast.makeText(newActivity.this, "No data to show", Toast.LENGTH_SHORT).show();
                        calculate();

                    }
                }
        );

        RequestManager.sendInBackground(request);
    }

    /**
     * Socket control of single data channel
     */
    private void turnOnSocket() {
        SocketManager.connectSocket();
        SocketManager.registerSocket(mDataChannel, mDataChannel.getMcsSocketListener());
    }

    private void turnOffSocket() {
        SocketManager.unregisterSocket(mDataChannel, mDataChannel.getMcsSocketListener());
        SocketManager.disconnectSocket();
    }

    private void calculate(){

      float outA = data.get("fsr_3");
      float inA = data.get("fsr_4");
      float outB = data.get("fsr_2");
      float inB = data.get("fsr_5");
      float outC = data.get("fsr_1");
      float inC = data.get("fsr_6");
      float temp = data.get("temp");
      float hum =  data.get("hum");
      float A = inA + outA;
      float B = inB + outB;
      float C = inC + outC;
      float in = inA + inB + inC;
      float out = outA + outB + outC;

      if(A == 0 && B == 0 && C == 0){
          all.setText("尚無資料");
          condition.setText("");
          health.setText("");
          comfort.setText("");
      }

      else{
          float arch = B/(A+B+C);
          float dir = in/out;
          int total = 10;

          if((temp > 28 && temp < 30) && hum > 60){
              comfort.setText("不適");
              total -= 3;
          }
          else if(temp > 30 && hum > 88){
              comfort.setText("極度不適");
              total -= 5;
          }
          else comfort.setText("舒適");

          if(A > 0 && B > 0 && C > 0){
              condition.setText("站立");
              if(arch > 0.3){
                  health.setText("足弓過低");
                  total -= 5;
              }
              else if(arch < 0.15){
                  health.setText("足弓過高");
                  total -= 5;
              }
              else health.setText("健康");
          }
          else{
              condition.setText("步行");
              if(out == 0){
                  health.setText("內八");
                  total -= 5;
              }
              else if(in == 0){
                  health.setText("外八");
                  total -= 5;
              }
              else health.setText("健康");
          }

          all.setText(String.valueOf(total) + " / 10");
      }

      for(int i = 0; i < data.size(); i++) data.remove(i);

    }
    /**
     * Pretty-print a JSONObject.
     */
//    private void printJson(JSONObject jsonObject) {
//        try {
//            comfort_tude.setText(jsonObject.toString(2));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "new Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.mediatek.mcstutorial/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "new Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.mediatek.mcstutorial/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

}